Skip to contentSkip to conversation

nfs: prepare for locking changes.

PATCH Superseded NeilBrown 3 participants 31 messages Oct 28 – Oct 29

Subsystems (5)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

NeilBrown

author
#0 lore raw

v4 cover nfs: prepare for locking changes.

Now that the requirement for this are upstream this could go via the NFS tree or the VFS tree.

Thanks,
NeilBrown

This v4 fixes the problems with patch 1 which Jonathan Flynn helped me to understand. And *actually* adds Anna's Acked-by.

Before this v3 fixed three bugs found by Sashiko - all error-path related.

1/ patch 5 - make sure d_drop() gets called in all error cases 2/ patch 8 - dput() sdentry on all error paths
3/ patch 9 - check error return from d_duplicate() correctly.

Original intro:
I am working on changes to directory locking. The medium term goal is to lift d_alloc_parallel() locking above i_rwsem, so d_alloc_paralle() can be run unlocked, and consequently cannot be called when ->i_rwsem is held.

The requires:
1/ the d_alloc_parallel() not be called while i_rwsem is held. NFS does
this in a few places. New interfaces d_alloc_trylock() and d_duplicate() are now available and can be used instead.

2/ a dentry must not be d_drop()ed while an operation is ongoing, as an
unlocked d_alloc_parallel() would then be able to create a new dentry with the same name. In particular d_rehash() must be phased out as it won't be safe. Various techiniques are used to avoid the need for d_drop(), particularly that d_splice_alias() is now able to splice a hashed alias.

Further, the first two patches here fixes bugs that I found while developing and reviewing these changes.

[PATCH v4 1/9] nfs: fix open-blocking with d_fsdata [PATCH v4 2/9] nfs: fix nfs_call_unlink()
[PATCH v4 3/9] nfs: remove d_drop()/d_alloc_parallel() from [PATCH v4 4/9] nfs: use d_splice_alias() in nfs_link() [PATCH v4 5/9] nfs: don't d_drop() before d_splice_alias() [PATCH v4 6/9] nfs: don't d_drop() before d_splice_alias() in [PATCH v4 7/9] nfs: Use d_alloc_trylock() in nfs_prime_dcache() [PATCH v4 8/9] nfs: use d_alloc_trylock() in silly-rename [PATCH v4 9/9] nfs: use d_duplicate()

author
#1 lore raw

PATCH v4 1/9 nfs: fix open-blocking with d_fsdata

From: NeilBrown <[email protected]>

The logic described in block_revalidate() that ->d_lock must be taken in lookup_open() missed the fact that sometimes lookup_open() isn't called.

If open_last_lookups() is called while still in RCU-walk and lookup_fast() finds a dentry, it does not take ->d_lock or increment d_count() before calling d_revalidate() - only afterwards.

So on that path d_count() can be incremented and the file opened *after* nfs_unlink() has checked d_count() and set NFS_FSDATA_BLOCKED. So an application could have the file open when it is unlinked on the server.

To fix this we need block_revalidate() to ensure the RCU-walk path is blocked as well. This is easily done with
write_seqcount_invalidate(&dentry->d_seq);

legitimize_path() will increment d_count() and then check d_seq. The write_seqcount_invalidate() call will cause that check to fail if nfs_unlink() has already seen d_count() being only 1. So the RCU-walk will fail with -ECHILD and it will be retried as a ref-walk. This requires that ->d_fsdata is loaded *after* read_seqcount_begin() loaded ->d_seq, so the smp_load_acquire() in __nfs_lookup_revalidate() is important.

Fixes 99bc9f2eb3f7 ("NFS: add barriers when testing for NFS_FSDATA_BLOCKED")
---
 fs/nfs/dir.c | 30 ++++++++++++++++++++++++------
 1 file changed, 24 insertions(+), 6 deletions(-)
fs/nfs/dir.c +24 -6
index 354f986e60c4..cde963e2bcb8 100644
@@ -1835,7 +1835,11 @@ __nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
 		if (dentry->d_fsdata == NFS_FSDATA_BLOCKED)
 			return -ECHILD;
 	} else {
-		/* Wait for unlink to complete - see unblock_revalidate() */
+		/* Wait for unlink to complete - see unblock_revalidate().
+		 * smp_load_acquire() ensures ->d_fsdata is read after
+		 * ->d_seq was read, matching block_revalidate() which
+		 * sets ->d_fsdata before ->d_seq.
+		 */
 		wait_var_event(&dentry->d_fsdata,
 			       smp_load_acquire(&dentry->d_fsdata)
 			       != NFS_FSDATA_BLOCKED);
@@ -1856,15 +1860,29 @@ static void block_revalidate(struct dentry *dentry)
 	/* old devname - just in case */
 	kfree(dentry->d_fsdata);
 
+	dentry->d_fsdata = NFS_FSDATA_BLOCKED;
+
 	/* Any new reference that could lead to an open
-	 * will take ->d_lock in lookup_open() -> d_lookup().
-	 * Holding this lock ensures we cannot race with
-	 * __nfs_lookup_revalidate() and removes and need
-	 * for further barriers.
+	 * will either:
+	 *  - take ->d_lock in lookup_open() -> d_lookup() or
+	 *  - will check d_seq in legitimize_path() or similar
+	 *    after taking the reference.
+	 *
+	 * Holding this lock and invalidating ->d_seq *after* recording
+	 * NFS_FSDATA_BLOCKED ensures we cannot race with
+	 * __nfs_lookup_revalidate().
+	 * If __nfs_lookup_revalidate() doesn't see NFS_FSDATA_BLOCKED then:
+	 * In the ref-walk case - d_lookup() will have incremented
+	 * d_count() before we check it.
+	 * In the RCU-walk case - ->d_seq must have been sampled before
+	 * we call write_seqcount_invalidate() below (because it was sampled
+	 * before we set NFS_FSDATA_BLOCKED) so d_count() will have been
+	 * incremented or the d_seq check will fail in legitimize_path()
+	 * (or both).
 	 */
 	lockdep_assert_held(&dentry->d_lock);
+	write_seqcount_invalidate(&dentry->d_seq);
 
-	dentry->d_fsdata = NFS_FSDATA_BLOCKED;
 }
 
 static void unblock_revalidate(struct dentry *dentry)

base-commit: 864c07de0c7dcbca58b61625dfa2e461ae63b242

Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#2 lore raw

PATCH v4 2/9 nfs: fix nfs_call_unlink()

In reply to NeilBrown

From: NeilBrown <[email protected]>

nfs_call_unlink() calls d_alloc_parallel() on a dentry which has not had the d_hash calculated. d_alloc_parallel() assumes this is calculated and doesn't calculate it itself.
So this will never find an existing dentry and so will not detect the races it aims to detect.

(This dentry ("alias") is never hashed so there is no lasting inconsistency in the dcache.)

Fix this by calling full_name_hash()

Fixes 565277f63c61 ("NFS: Fix a race in sillyrename")
---
 fs/nfs/unlink.c | 3 +++
 1 file changed, 3 insertions(+)
fs/nfs/unlink.c +3 -0
index c8d712204e64..11a46a993e11 100644
@@ -125,6 +125,9 @@ static int nfs_call_unlink(struct dentry *dentry, struct inode *inode, struct nf
 	struct dentry *alias;
 
 	down_read_non_owner(&NFS_I(dir)->rmdir_sem);
+	data->args.name.hash = full_name_hash(dentry->d_parent,
+					      data->args.name.name,
+					      data->args.name.len);
 	alias = d_alloc_parallel(dentry->d_parent, &data->args.name);
 	if (IS_ERR(alias)) {
 		up_read_non_owner(&NFS_I(dir)->rmdir_sem);
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
#3 lore raw

cover nfs: fix the silly-delete hand-off that 2/9 makes reachable

Hi Neil,

Your "nfs: fix nfs_call_unlink()" computes the silly name's hash before d_alloc_parallel(), so nfs_call_unlink() can now find another cached entry for that name and hand it the pending silly-delete. With it applied, that happens: an entry made by a fresh lookup of the silly name, after the original entry was invalidated, receives the delete when the file is closed. Three problems in the hand-off become reachable with it, and these patches fix them:

1/3 the hand-off can overwrite NFS_FSDATA_BLOCKED on an entry whose
REMOVE or RENAME is in flight (Sashiko's review of 2/9 reports this too);
2/3 the other order: nfs_rename() tests its target before it takes
->d_lock, so a hand-off landing in between is kfree()d by block_revalidate(), leaving DCACHE_NFSFS_RENAMED set with no data and a NULL dereference at the final dput(); a hand-off that the VFS's unlocked test missed also trips the WARN_ON()s in nfs_unlink() and nfs_rename(). nfs_rename() now tests under ->d_lock, and both return -EBUSY, as may_delete_dentry() does;
3/3 nfs_call_unlink() holds rmdir_sem for read across its lookup and
across the dput() of the alias, and either can kill a dentry carrying a silly-delete, which re-enters nfs_call_unlink() with rmdir_sem still held: that deadlocks against a waiting rmdir() (Sashiko's review of 2/9 reports the alias case). It now takes rmdir_sem only for the REMOVE it sends, which also closes an older route to the same re-entry that does not need 2/9:
NFSv4's delegation return in ->unlink_setup().

They have to go wherever 2/9 goes, and its Fixes: tag will take it to stable. Fold them into 2/9 if you prefer, as you did with the d_seq fix in 1/9.

One window is not covered, and you may prefer to close it another way. After nfs_unlink() or nfs_rename() clears the mark, and before the VFS's d_delete() or nfs_rename()'s d_move(), a hand-off can still land on the entry. For an unlink, that costs only a second REMOVE, which finds nothing. For a rename onto the silly name, the target is left owing a REMOVE of a name that now belongs to the renamed file. That REMOVE is normally dropped, because nfs_call_unlink() then finds the renamed file's own entry and its file handle differs; but if that entry has left the dcache by the time the target's last reference goes, the REMOVE is sent and deletes the renamed file. Closing the rename case would take the hand-off refusing an alias that is no longer hashed, and nfs_rename() dropping, under ->d_lock and after d_move(), a silly-delete that landed after its mark cleared. I have a draft of that, and can test and send it if you want it.

Tested with your v4 and these patches on a 7.3-based kernel, over NFSv4.2 to a pNFS metadata server that is not knfsd. The hand-off happens as described above. With 3/3, the nested nfs_call_unlink() that follows it starts with rmdir_sem not held, where without 3/3 it ran with rmdir_sem held for read, and the REMOVE is sent once. The removal race tests of my RFC, posted in reply to your 0/9, passed on this kernel, as did a PROVE_LOCKING and KASAN build running them, though lockdep does not see rmdir_sem's read hold, which is taken with down_read_non_owner(). No test here hits the races that 1/3 and 2/3 close, or the deadlock itself, so for those the fixes rest on the code.

The series applies to 83f32c773255 in Linus's tree with your v4, and fs/ compiles without warnings at each patch.

Tools: these patches, their changelogs and this letter were written with Claude Code, using Anthropic's Claude Opus 5 and Claude Opus 5.5 models, at my direction. It found the problems fixed by 1/3 and 2/3, and two of the three routes in 3/3, reading the code with and without Sashiko's review prompts; Sashiko's own review of 2/9 reported the problem in 1/3 as well, and the route through the alias in 3/3.

Thanks,
Jonathan

Jonathan Flynn (3):
nfs: do not transfer a sillydelete onto a blocked dentry
nfs: answer a handed-off silly-delete on a removal target with -EBUSY
nfs: take rmdir_sem for a silly-delete only when its REMOVE is sent

 fs/nfs/dir.c    | 32 ++++++++++++++++++++++++++------
 fs/nfs/unlink.c | 39 ++++++++++++++++++++++++++++++++-------
 2 files changed, 58 insertions(+), 13 deletions(-)

base-commit: 83f32c773255720a661aa45d83e36278135f23f5
prerequisite-patch-id: 3405b4d6ab8b0bf24ba63a898083d617deec4f24
prerequisite-patch-id: 096657d6d80d7ca533ccb574d2af65611ede4af2
prerequisite-patch-id: 1a2319c14739918aef86116647fea28ae85ad4df
prerequisite-patch-id: 725cb18c3936d50141ef27dafc159bf50b64a5bd
prerequisite-patch-id: b39cdd352b97e2cd247311fd5db620dbff227bd7
prerequisite-patch-id: f9f3f0e945cadf96113d4ac9ab8f7b0c207af4e5
prerequisite-patch-id: 4c09a15390bb556d79bea1ee733f52a58bec80ef
prerequisite-patch-id: 7c026717a97b2c86a169539822f5d14650f68f8a
prerequisite-patch-id: a702d54495d0f3d7f88b82411d884dcf5aacf9a0

Signature · 1 line
2.43.0
#4 lore raw

PATCH 1/3 nfs: do not transfer a sillydelete onto a blocked dentry

Harden the hand-off of a pending silly-delete. When the last user of a silly-renamed file goes away, the client can move the delete it still owes onto another cached entry for the same name. Leave that entry alone if a removal of the name, or a rename onto it, is already in flight on it. Moving the delete there would overwrite the mark that makes lookups of the name wait for that removal: the wait would end early, the removal could report success without removing anything, the pending delete would be leaked, and a later release of the entry would dereference a NULL pointer. If that removal succeeds, the silly-delete was redundant; if it fails, the silly-renamed file stays on the server, which is the cost of skipping rather than waiting.

The mark and the hand-off have shared ->d_fsdata since the commit named below, which reasoned that no silly-delete is pending on an entry being removed or renamed over, but not that a hand-off could arrive while that removal is in flight. The hand-off has stayed unreachable since then only because nfs_call_unlink() passed d_alloc_parallel() a name whose hash it had not computed, so the lookup for the other entry never found it. NeilBrown's "nfs: fix nfs_call_unlink()" computes that hash, which makes the hand-off reachable even though every removal holds the parent directory exclusive: the hand-off does not take that lock. That fix adds no test of the mark; this is the test, and a tree that takes that fix needs this one too. It does not depend on any other patch.

This was found by an AI coding assistant (Claude Code) reading the code; Sashiko's review of NeilBrown's patch reports it too. The hand-off itself has been reproduced with that patch applied; its race with a removal or rename has not.

Fixes 3c59366c207e ("NFS: don't unhash dentry during unlink/rename")

---

Notes:
For reviewers and review tools; not part of the changelog.

Known and not fixed by this series: a hand-off that lands after nfs_unlink() or nfs_rename() clears the mark, and before the VFS's d_delete() or nfs_rename()'s d_move(). The cover letter describes it, with what it costs and a fix offered.

 fs/nfs/unlink.c | 19 ++++++++++++++++++-
 1 file changed, 18 insertions(+), 1 deletion(-)
fs/nfs/unlink.c +18 -1
index 0eddc7ee11..491ebd8582 100644
@@ -142,9 +142,26 @@ static int nfs_call_unlink(struct dentry *dentry, struct inode *inode, struct nf
 		 * the sillyrename information to the aliased dentry.
 		 */
 		spin_lock(&alias->d_lock);
+		/*
+		 * Not if a removal of this name already owns the alias:
+		 * ->d_fsdata == NFS_FSDATA_BLOCKED means nfs_unlink() has a
+		 * REMOVE of exactly this name, or nfs_rename() a RENAME onto
+		 * it, in flight and ->d_revalidate() is waiting on that field,
+		 * so storing over it would lift the block early and the later
+		 * unblock_revalidate() would store NULL over @data.  Tested
+		 * under the same ->d_lock block_revalidate() stores under.
+		 * Skip rather than wait: that removal makes this sillydelete
+		 * redundant if it succeeds, and a wait here would sleep in a
+		 * dput() path -- the nfsiod callback that releases a
+		 * silly-rename among its callers -- for the length of another
+		 * task's RPC, with ->d_lock dropped and these tests redone.
+		 * If that removal then fails, the silly-renamed file stays on
+		 * the server: the price of skipping.
+		 */
 		if (d_really_is_positive(alias) &&
 		    !nfs_compare_fh(NFS_FH(inode), NFS_FH(d_inode(alias))) &&
-		    !(alias->d_flags & DCACHE_NFSFS_RENAMED)) {
+		    !(alias->d_flags & DCACHE_NFSFS_RENAMED) &&
+		    alias->d_fsdata != NFS_FSDATA_BLOCKED) {
 			devname_garbage = alias->d_fsdata;
 			alias->d_fsdata = data;
 			alias->d_flags |= DCACHE_NFSFS_RENAMED;
Signature · 1 line
2.43.0
#5 lore raw

PATCH 2/3 nfs: answer a handed-off silly-delete on a removal target with -EBUSY

In reply to Jonathan Flynn

When the last user of a silly-renamed file goes away, nfs_call_unlink() can hand the delete it still owes to another cached entry for the same
name: it marks that entry DCACHE_NFSFS_RENAMED and stores its struct nfs_unlinkdata in ->d_fsdata, under the entry's ->d_lock. NeilBrown's "nfs: fix nfs_call_unlink()" makes that hand-off reachable; before it, the lookup for the other entry was given a name with no hash and never found one.

The VFS refuses to remove an entry so marked, or to rename over one, with -EBUSY, but may_delete_dentry() tests the flag without ->d_lock, and a hand-off can land after it. nfs_unlink() repeats the test under ->d_lock and treats a marked entry as a bug: it warns and returns -ETXTBSY. nfs_rename() makes the same test before it takes ->d_lock, so a hand-off can also land between the test and block_revalidate(), which then kfree()s the nfs_unlinkdata as if it were a device name. Its credential and name are leaked, DCACHE_NFSFS_RENAMED stays set with no data behind it, and the final dput() of the target reaches nfs_call_unlink() with a NULL pointer, which it dereferences.

Take the target's ->d_lock before the tests in nfs_rename(), as nfs_unlink() already does, and answer a marked entry in both with -EBUSY and no warning, as may_delete_dentry() does. No hand-off can land between the test and the store any more, and one that landed before the test makes the entry the busy file the VFS already refuses.

This was found by an AI coding assistant (Claude Code) reading the code. The hand-off itself has been reproduced with "nfs: fix nfs_call_unlink()" applied; its race with a removal or rename has not.

Fixes 3c59366c207e ("NFS: don't unhash dentry during unlink/rename")

---

Notes:
For reviewers and review tools; not part of the changelog.

A hand-off that lands while nfs_rename() is in its silly-rename branch (the target's count above 2, with ->d_lock dropped before d_duplicate()) still gets -ETXTBSY: nfs_sillyrename() fails with -EBUSY, and that branch returns -ETXTBSY for every nfs_sillyrename() failure. This patch leaves the branch as it was, and the handed-off data is neither freed nor leaked there, since nfs_async_unlink() tests and stores under ->d_lock. An automated review (Claude Code running Sashiko's review prompts) raised this; it was checked and dropped as not introduced here.

 fs/nfs/dir.c | 32 ++++++++++++++++++++++++++------
 1 file changed, 26 insertions(+), 6 deletions(-)
fs/nfs/dir.c +26 -6
index 36cb99f746..dc7784b666 100644
@@ -2605,10 +2605,18 @@ int nfs_unlink(struct inode *dir, struct dentry *dentry)
 	 * completes.  ->d_revalidate will wait for ->d_fsdata
 	 * to clear.  We set it here to ensure no lookup succeeds until
 	 * the unlink is complete on the server.
+	 *
+	 * may_delete_dentry() refused an entry carrying a silly-delete,
+	 * but without ->d_lock, and nfs_call_unlink() can have handed
+	 * this one a silly-delete since.  It is busy, as the VFS says.
 	 */
+	error = -EBUSY;
+	if (dentry->d_flags & DCACHE_NFSFS_RENAMED) {
+		spin_unlock(&dentry->d_lock);
+		goto out;
+	}
 	error = -ETXTBSY;
-	if (WARN_ON(dentry->d_flags & DCACHE_NFSFS_RENAMED) ||
-	    WARN_ON(dentry->d_fsdata == NFS_FSDATA_BLOCKED)) {
+	if (WARN_ON(dentry->d_fsdata == NFS_FSDATA_BLOCKED)) {
 		spin_unlock(&dentry->d_lock);
 		goto out;
 	}
@@ -2801,13 +2809,25 @@ int nfs_rename(const struct mnt_idmap *idmap, struct inode *old_dir,
 		 * completes.  ->d_revalidate will wait for ->d_fsdata
 		 * to clear.  We set it here to ensure no lookup succeeds until
 		 * the unlink is complete on the server.
+		 *
+		 * Test under ->d_lock, which nfs_call_unlink() hands a
+		 * silly-delete over under and block_revalidate() below
+		 * stores under, so that no hand-off lands between the test
+		 * and the store, which would kfree() it.  A target carrying
+		 * one is busy, as may_delete_dentry() says when it sees the
+		 * flag first.
 		 */
+		spin_lock(&new_dentry->d_lock);
+		error = -EBUSY;
+		if (new_dentry->d_flags & DCACHE_NFSFS_RENAMED) {
+			spin_unlock(&new_dentry->d_lock);
+			goto out;
+		}
 		error = -ETXTBSY;
-		if (WARN_ON(new_dentry->d_flags & DCACHE_NFSFS_RENAMED) ||
-		    WARN_ON(new_dentry->d_fsdata == NFS_FSDATA_BLOCKED))
+		if (WARN_ON(new_dentry->d_fsdata == NFS_FSDATA_BLOCKED)) {
+			spin_unlock(&new_dentry->d_lock);
 			goto out;
-
-		spin_lock(&new_dentry->d_lock);
+		}
 		if (d_count(new_dentry) > 2) {
 			int err;
 
Signature · 1 line
2.43.0
#6 lore raw

PATCH 3/3 nfs: take rmdir_sem for a silly-delete only when its REMOVE is sent

In reply to Jonathan Flynn

nfs_call_unlink() takes the directory's rmdir_sem for read before it looks the silly name up, and keeps it until the REMOVE it sends is done or, when it hands the silly-delete to another cached entry for the name instead, until it has dropped that alias. Several things inside that hold can drop the last reference to a dentry marked DCACHE_NFSFS_RENAMED:
the dput() of an alias that has just been handed the silly-delete; the dput()s in d_alloc_parallel() of an entry it found but will not return, after a failed ->d_seq recheck or after waiting for an in-lookup entry that changed; and ->unlink_setup(), where NFSv4 returns the file's delegation, putting the open contexts it reclaims and waiting for writeback whose completion can put others. Such a dentry is killed at
once: nfs_dentry_delete() asks for that, and nfs_dentry_iput() passes it to nfs_complete_unlink(), which calls nfs_call_unlink() again, in this thread or in the one completing the writeback. That call takes rmdir_sem for read while the first hold is still taken. If an rmdir() of the directory is waiting for rmdir_sem as a writer by then, the second reader waits behind it, the writer waits for the first reader, and none of them returns.

Take rmdir_sem only when the REMOVE is about to be submitted, after ->unlink_setup(), and hold it until the REMOVE is done, as before. The hand-off sends no REMOVE and needs no hold; the alias sends it later, through a call of its own. An rmdir() that runs before the hold is taken finds the silly-renamed file still there, as it would have a moment earlier.

The ->unlink_setup() route does not depend on NeilBrown's "nfs: fix nfs_call_unlink()": it needs a second silly-renamed name of the same inode in the same directory, such as a hard link removed while open, and a delegation still held when the silly-delete is sent. That patch makes the other two reachable, along with the hand-off itself. With it applied, the re-entry through the alias has been reproduced: an unused second entry for a silly name received the delete when the file was closed, and nfs_call_unlink() ran again with rmdir_sem held for read. The deadlock needs a waiting rmdir() and has not been reproduced. Sashiko's review of that patch reported the alias case; an AI coding assistant (Claude Code) found the other two while reviewing this fix.

Fixes 884be175351e ("nfs: per-name sillyunlink exclusion")
---
 fs/nfs/unlink.c | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
fs/nfs/unlink.c +14 -6
index 491ebd8582..679ef22637 100644
@@ -113,6 +113,19 @@ static void nfs_do_call_unlink(struct inode *inode, struct nfs_unlinkdata *data)
 
 	NFS_PROTO(dir)->unlink_setup(&msg, data->dentry, inode);
 
+	/*
+	 * Hold off an rmdir() of the directory from here until the REMOVE
+	 * is done (nfs_async_unlink_release()), and not before.  Until the
+	 * REMOVE is submitted, the lookup in nfs_call_unlink(), its dput()
+	 * of an alias, and ->unlink_setup() (where NFSv4 returns the
+	 * file's delegation, putting open contexts and waiting for
+	 * writeback) can each drop the last reference to a dentry carrying
+	 * a silly-delete.  Its kill calls nfs_call_unlink() again, in this
+	 * thread or in one this thread waits for, and if rmdir_sem were
+	 * held here by then, that call's read hold would wait behind an
+	 * rmdir() waiting for this one.
+	 */
+	down_read_non_owner(&NFS_I(dir)->rmdir_sem);
 	task_setup_data.rpc_client = NFS_CLIENT(dir);
 	task = rpc_run_task(&task_setup_data);
 	if (!IS_ERR(task))
@@ -121,18 +134,14 @@ static void nfs_do_call_unlink(struct inode *inode, struct nfs_unlinkdata *data)
 
 static int nfs_call_unlink(struct dentry *dentry, struct inode *inode, struct nfs_unlinkdata *data)
 {
-	struct inode *dir = d_inode(dentry->d_parent);
 	struct dentry *alias;
 
-	down_read_non_owner(&NFS_I(dir)->rmdir_sem);
 	data->args.name.hash = full_name_hash(dentry->d_parent,
 					      data->args.name.name,
 					      data->args.name.len);
 	alias = d_alloc_parallel(dentry->d_parent, &data->args.name);
-	if (IS_ERR(alias)) {
-		up_read_non_owner(&NFS_I(dir)->rmdir_sem);
+	if (IS_ERR(alias))
 		return 0;
-	}
 	if (!d_in_lookup(alias)) {
 		int ret;
 		void *devname_garbage = NULL;
@@ -170,7 +179,6 @@ static int nfs_call_unlink(struct dentry *dentry, struct inode *inode, struct nf
 			ret = 0;
 		spin_unlock(&alias->d_lock);
 		dput(alias);
-		up_read_non_owner(&NFS_I(dir)->rmdir_sem);
 		/*
 		 * If we'd displaced old cached devname, free it.  At that
 		 * point dentry is definitely not a root, so we won't need
Signature · 1 line
2.43.0
author
#7 lore raw

Re: [PATCH 0/3] nfs: fix the silly-delete hand-off that 2/9 makes reachable

In reply to Jonathan Flynn
Quoted 9 lines · Jonathan Flynn

Hi Neil,

Your "nfs: fix nfs_call_unlink()" computes the silly name's hash before d_alloc_parallel(), so nfs_call_unlink() can now find another cached entry for that name and hand it the pending silly-delete. With it applied, that happens: an entry made by a fresh lookup of the silly name, after the original entry was invalidated, receives the delete when the file is closed. Three problems in the hand-off become reachable with it, and these patches fix them:

Hi Jonathan,
thanks for these. The first 2 definitely make sense. I haven't completely thought through the third but it is probably good too.

But it all seems rather ugly and I'm hoping there is a better way. I would like to avoid the hand-off altogether.

There is a tiny window between the silly dentry being unhashed, and the ->d_iput() call which triggers the d_alloc_parallel of a new name. A new lookup has to happen in this window to cause a problem. I'd like to prevent that lookup from completing.

I wonder if we could link all the nfs_unlinkdata for a given parent directory together and change nfs_lookup() to check that list first. Hopefully it would mostly be empty...
I think it would be safe to only add a nfs_unlink to the per-directory list in nfs_dentry_delete() if DCACHE_NFSFS_RENAMED is set. We then remove it once the d_alloc_parallel() completes.
If nfs_lookup() ever finds the name it wants on the list it ... uhmmm maybe blocks on ->rmdir_sem.
We would need to change the d_alloc_parallel() in nfs_call_unlink() to d_alloc_trylock().

Then we wouldn't need the hand-off at all. Once nfs_dentry_delete() adds the dentry to the per-directory list, the unlink must complete and no other dentry will be involved.

Does that make any sense to you? Do you think it is worth a try?

Thanks,
NeilBrown

Quoted 87 lines

1/3 the hand-off can overwrite NFS_FSDATA_BLOCKED on an entry whose
REMOVE or RENAME is in flight (Sashiko's review of 2/9 reports this too);
2/3 the other order: nfs_rename() tests its target before it takes
->d_lock, so a hand-off landing in between is kfree()d by block_revalidate(), leaving DCACHE_NFSFS_RENAMED set with no data and a NULL dereference at the final dput(); a hand-off that the VFS's unlocked test missed also trips the WARN_ON()s in nfs_unlink() and nfs_rename(). nfs_rename() now tests under ->d_lock, and both return -EBUSY, as may_delete_dentry() does;
3/3 nfs_call_unlink() holds rmdir_sem for read across its lookup and
across the dput() of the alias, and either can kill a dentry carrying a silly-delete, which re-enters nfs_call_unlink() with rmdir_sem still held: that deadlocks against a waiting rmdir() (Sashiko's review of 2/9 reports the alias case). It now takes rmdir_sem only for the REMOVE it sends, which also closes an older route to the same re-entry that does not need 2/9:
NFSv4's delegation return in ->unlink_setup().

They have to go wherever 2/9 goes, and its Fixes: tag will take it to stable. Fold them into 2/9 if you prefer, as you did with the d_seq fix in 1/9.

One window is not covered, and you may prefer to close it another way. After nfs_unlink() or nfs_rename() clears the mark, and before the VFS's d_delete() or nfs_rename()'s d_move(), a hand-off can still land on the entry. For an unlink, that costs only a second REMOVE, which finds nothing. For a rename onto the silly name, the target is left owing a REMOVE of a name that now belongs to the renamed file. That REMOVE is normally dropped, because nfs_call_unlink() then finds the renamed file's own entry and its file handle differs; but if that entry has left the dcache by the time the target's last reference goes, the REMOVE is sent and deletes the renamed file. Closing the rename case would take the hand-off refusing an alias that is no longer hashed, and nfs_rename() dropping, under ->d_lock and after d_move(), a silly-delete that landed after its mark cleared. I have a draft of that, and can test and send it if you want it.

Tested with your v4 and these patches on a 7.3-based kernel, over NFSv4.2 to a pNFS metadata server that is not knfsd. The hand-off happens as described above. With 3/3, the nested nfs_call_unlink() that follows it starts with rmdir_sem not held, where without 3/3 it ran with rmdir_sem held for read, and the REMOVE is sent once. The removal race tests of my RFC, posted in reply to your 0/9, passed on this kernel, as did a PROVE_LOCKING and KASAN build running them, though lockdep does not see rmdir_sem's read hold, which is taken with down_read_non_owner(). No test here hits the races that 1/3 and 2/3 close, or the deadlock itself, so for those the fixes rest on the code.

The series applies to 83f32c773255 in Linus's tree with your v4, and fs/ compiles without warnings at each patch.

Tools: these patches, their changelogs and this letter were written with Claude Code, using Anthropic's Claude Opus 5 and Claude Opus 5.5 models, at my direction. It found the problems fixed by 1/3 and 2/3, and two of the three routes in 3/3, reading the code with and without Sashiko's review prompts; Sashiko's own review of 2/9 reported the problem in 1/3 as well, and the route through the alias in 3/3.

Thanks,
Jonathan

Jonathan Flynn (3):
nfs: do not transfer a sillydelete onto a blocked dentry
nfs: answer a handed-off silly-delete on a removal target with -EBUSY
nfs: take rmdir_sem for a silly-delete only when its REMOVE is sent

 fs/nfs/dir.c    | 32 ++++++++++++++++++++++++++------
 fs/nfs/unlink.c | 39 ++++++++++++++++++++++++++++++++-------
 2 files changed, 58 insertions(+), 13 deletions(-)

base-commit: 83f32c773255720a661aa45d83e36278135f23f5
prerequisite-patch-id: 3405b4d6ab8b0bf24ba63a898083d617deec4f24
prerequisite-patch-id: 096657d6d80d7ca533ccb574d2af65611ede4af2
prerequisite-patch-id: 1a2319c14739918aef86116647fea28ae85ad4df
prerequisite-patch-id: 725cb18c3936d50141ef27dafc159bf50b64a5bd
prerequisite-patch-id: b39cdd352b97e2cd247311fd5db620dbff227bd7
prerequisite-patch-id: f9f3f0e945cadf96113d4ac9ab8f7b0c207af4e5
prerequisite-patch-id: 4c09a15390bb556d79bea1ee733f52a58bec80ef
prerequisite-patch-id: 7c026717a97b2c86a169539822f5d14650f68f8a
prerequisite-patch-id: a702d54495d0f3d7f88b82411d884dcf5aacf9a0

Signature · 1 line
2.43.0
author
#8 lore raw

PATCH v4 3/9 nfs: remove d_drop()/d_alloc_parallel() from nfs_atomic_open()

In reply to NeilBrown

From: NeilBrown <[email protected]>

It is important that two non-create NFS "open"s of a negative dentry don't race. They both have only a shared lock on i_rwsem and so could run concurrently, but they might both try to call d_splice_alias() at the same time which is confusing at best.

nfs_atomic_open() currently avoids this by discarding the negative dentry and creating a new one using d_alloc_parallel(). Only one thread can successfully get the d_in_lookup() dentry, the other will wait for the first to finish, and can use the result of that first lookup.

A proposed locking change inverts the order between i_rwsem and d_alloc_parallel() so it will not be safe to call d_alloc_parallel() while holding i_rwsem - even shared.

We can achieve the same effect by causing ->d_revalidate to invalidate a negative dentry when LOOKUP_OPEN is set. Doing this is consistent with the "close to open" caching semantics of NFS which requires the server to be queried whenever opening a file - cached information must not be trusted.

With this change to ->d_revaliate (implemented in nfs_neg_need_reval()) we can be sure that we have exclusive access to any dentry that reaches nfs_atomic_open(). Either O_CREAT was requested and so the parent is locked exclusively, or the dentry will have DCACHE_PAR_LOOKUP set. [Note that when nfs_neg_need_reval() returns 1, ->d_revalidate returns 0
which triggers invalidation].

This means that the d_drop() and d_alloc_parallel() calls in nfs_atomic_lookup() are no longer needed to provide exclusion

There is still a d_drop() which allows d_splice_alias() to succeed. This will be removed in a future patch.

---
 fs/nfs/dir.c | 30 +++++++-----------------------
 1 file changed, 7 insertions(+), 23 deletions(-)
fs/nfs/dir.c +7 -23
index cde963e2bcb8..cf366329666f 100644
@@ -1656,6 +1656,13 @@ int nfs_neg_need_reval(struct inode *dir, struct dentry *dentry,
 {
 	if (flags & (LOOKUP_CREATE | LOOKUP_RENAME_TARGET))
 		return 0;
+	if (flags & LOOKUP_OPEN)
+		/* close-to-open semantics require we go to the server
+		 * on each open.  By invalidating the dentry we
+		 * also ensure nfs_atomic_open() always has exclusive
+		 * access to the dentry.
+		 */
+		return 1;
 	if (NFS_SERVER(dir)->flags & NFS_MOUNT_LOOKUP_CACHE_NONEG)
 		return 1;
 	/* Case insensitive server? Revalidate negative dentries */
@@ -2129,7 +2136,6 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 	struct inode *inode;
 	unsigned int lookup_flags = 0;
 	unsigned long dir_verifier;
-	bool switched = false;
 	int created = 0;
 	int err;
 
@@ -2174,17 +2180,6 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 		attr.ia_size = 0;
 	}
 
-	if (!(open_flags & O_CREAT) && !d_in_lookup(dentry)) {
-		d_drop(dentry);
-		switched = true;
-		dentry = d_alloc_parallel(dentry->d_parent,
-					  &dentry->d_name);
-		if (IS_ERR(dentry))
-			return PTR_ERR(dentry);
-		if (unlikely(!d_in_lookup(dentry)))
-			return finish_no_open(file, dentry);
-	}
-
 	ctx = create_nfs_open_context(dentry, open_flags, file);
 	err = PTR_ERR(ctx);
 	if (IS_ERR(ctx))
@@ -2235,10 +2230,6 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 	trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
 	put_nfs_open_context(ctx);
 out:
-	if (unlikely(switched)) {
-		d_lookup_done(dentry);
-		dput(dentry);
-	}
 	return err;
 
 no_open:
@@ -2261,13 +2252,6 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 			res = ERR_PTR(-EOPENSTALE);
 		}
 	}
-	if (switched) {
-		d_lookup_done(dentry);
-		if (!res)
-			res = dentry;
-		else
-			dput(dentry);
-	}
 	return finish_no_open(file, res);
 }
 EXPORT_SYMBOL_GPL(nfs_atomic_open);
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#9 lore raw

PATCH v4 4/9 nfs: use d_splice_alias() in nfs_link()

In reply to NeilBrown

From: NeilBrown <[email protected]>

When filename_linkat() calls filename_create() which ultimately calls ->lookup, the flags LOOKUP_CREATE|LOOKUP_EXCL are passed. nfs_lookup() treats this as an exclusive create (which it is) and skips the ->lookup, leaving the dentry unchanged.

Currently that means nfs_link() can get a hashed dentry (if the name was already in the cache) or an unhashed dentry (if it wasn't). As none of d_add(), d_instantiate(), d_splice_alias() could handle both of these, nfs_link() calls d_drop() and then d_add().

Recent changes to d_splice_alias() mean that it *can* work with either hashed or unhashed dentries. Future changes to locking mean that it will be unsafe to d_drop() a dentry while an operation (in this case "link()") is still ongoing.

So change to use d_splice_alias(), and not to d_drop() until an error is detected (as in that case was can't be sure what is actually on the server).

Also update the comment for nfs_is_exclusive_create() to note that link(), mkdir(), mknod(), symlink() all appear as exclusive creates. Those other than link() already used d_splice_alias() via nfs_add_or_obtain().

Possibly nfs_is_exclusive_create() should return true even with NFSv2 when the request isn't an open (not LOOKUP_OPEN).

---
 fs/nfs/dir.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
fs/nfs/dir.c +6 -2
index cf366329666f..e4c7acaaf2ba 100644
@@ -1570,6 +1570,9 @@ static int nfs_check_verifier(struct inode *dir, struct dentry *dentry,
 /*
  * Use intent information to check whether or not we're going to do
  * an O_EXCL create using this path component.
+ * Note that link(), mkdir(), mknod(), symlink() all appear as
+ * exclusive creation.  Regular file creation could be distinguished
+ * with LOOKUP_OPEN.
  */
 static int nfs_is_exclusive_create(struct inode *dir, unsigned int flags)
 {
@@ -2715,14 +2718,15 @@ nfs_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry)
 		old_dentry, dentry);
 
 	trace_nfs_link_enter(inode, dir, dentry);
-	d_drop(dentry);
 	if (S_ISREG(inode->i_mode))
 		nfs_sync_inode(inode);
 	error = NFS_PROTO(dir)->link(inode, dir, &dentry->d_name);
 	if (error == 0) {
 		nfs_set_verifier(dentry, nfs_save_change_attribute(dir));
 		ihold(inode);
-		d_add(dentry, inode);
+		d_splice_alias(inode, dentry);
+	} else {
+		d_drop(dentry);
 	}
 	trace_nfs_link_exit(inode, dir, dentry, error);
 	return error;
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#10 lore raw

PATCH v4 5/9 nfs: don't d_drop() before d_splice_alias()

In reply to NeilBrown

From: NeilBrown <[email protected]>

nfs_add_or_obtain() is used, often via nfs_instantiate(), to attach a newly created inode to the appropriate dentry - or to provide an alternate dentry.
It has to drop the dentry first, which is problematic for proposed locking changes.

As d_splice_alias() now works with hashed dentries, the d_drop() is no longer needed.

However we still d_drop() on error as the status of the name is uncertain.

_nfs4_open_and_get_state() is only used for files so we should be able to use d_instantiate(). However as that depends on the server for correctness, it is safer to stay with the current code pattern and use d_splice_alias() there too.

---
 fs/nfs/dir.c      | 4 ++--
 fs/nfs/nfs4proc.c | 1 -
 2 files changed, 2 insertions(+), 3 deletions(-)
fs/nfs/dir.c +2 -2
index e4c7acaaf2ba..b29dc1260d91 100644
@@ -2362,8 +2362,6 @@ nfs_add_or_obtain(struct dentry *dentry, struct nfs_fh *fhandle,
 	struct dentry *d;
 	int error;
 
-	d_drop(dentry);
-
 	if (fhandle->size == 0) {
 		error = NFS_PROTO(dir)->lookup(dir, dentry, &dentry->d_name,
 					       fhandle, fattr);
@@ -2381,6 +2379,8 @@ nfs_add_or_obtain(struct dentry *dentry, struct nfs_fh *fhandle,
 	inode = nfs_fhget(dentry->d_sb, fhandle, fattr);
 	d = d_splice_alias(inode, dentry);
 out:
+	if (IS_ERR(d))
+		d_drop(dentry);
 	dput(parent);
 	return d;
 out_error:
fs/nfs/nfs4proc.c +0 -1
index 21e5df7e5251..e8ca92b07190 100644
@@ -3113,7 +3113,6 @@ static int _nfs4_open_and_get_state(struct nfs4_opendata *opendata,
 	nfs_set_verifier(dentry, dir_verifier);
 	if (d_really_is_negative(dentry)) {
 		struct dentry *alias;
-		d_drop(dentry);
 		alias = d_splice_alias(igrab(state->inode), dentry);
 		/* d_splice_alias() can't fail here - it's a non-directory */
 		if (alias) {
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#11 lore raw

PATCH v4 6/9 nfs: don't d_drop() before d_splice_alias() in atomic_create.

In reply to NeilBrown

From: NeilBrown <[email protected]>

When atomic_create fails with -ENOENT we currently d_drop() the dentry and then re-add it (d_splice_alias()) with a NULL inode. This drop-and-re-add will not work with proposed locking changes.

As d_splice_alias() now supports hashed dentries, we don't need the d_drop() until it is determined that some other error has occurred.

---
 fs/nfs/dir.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
fs/nfs/dir.c +4 -3
index b29dc1260d91..b296d90c8e14 100644
@@ -2196,7 +2196,6 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 		err = PTR_ERR(inode);
 		trace_nfs_atomic_open_exit(dir, ctx, open_flags, err);
 		put_nfs_open_context(ctx);
-		d_drop(dentry);
 		switch (err) {
 		case -ENOENT:
 			if (nfs_server_capable(dir, NFS_CAP_CASE_INSENSITIVE))
@@ -2205,7 +2204,7 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 				dir_verifier = nfs_save_change_attribute(dir);
 			nfs_set_verifier(dentry, dir_verifier);
 			d_splice_alias(NULL, dentry);
-			break;
+			goto out;
 		case -EISDIR:
 		case -ENOTDIR:
 			if (open_flags & __O_REGULAR) {
@@ -2221,6 +2220,7 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 		default:
 			break;
 		}
+		d_drop(dentry);
 		goto out;
 	}
 	file->f_mode |= FMODE_CAN_ODIRECT;
@@ -2254,7 +2254,8 @@ int nfs_atomic_open(struct inode *dir, struct dentry *dentry,
 			dput(res);
 			res = ERR_PTR(-EOPENSTALE);
 		}
-	}
+	} else
+		d_drop(dentry);
 	return finish_no_open(file, res);
 }
 EXPORT_SYMBOL_GPL(nfs_atomic_open);
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#12 lore raw

PATCH v4 7/9 nfs: Use d_alloc_trylock() in nfs_prime_dcache()

In reply to NeilBrown

From: NeilBrown <[email protected]>

NFS uses the results of readdir to prime the dcache. Using d_alloc_parallel() can block if there is a concurrent lookup. Blocking in that case is pointless as the lookup will add info to the dcache and there is no value in the readdir waiting to see if it should add the info too.

Also this call to d_alloc_parallel() is made while the parent directory is locked. A proposed change to locking will lock the parent later, after d_alloc_parallel(). This means it won't be safe to wait in d_alloc_parallel() while holding the directory lock.

So change to use d_alloc_trylock(), which removes the need for calculating the hash or doing a preliminary lookup.

---
 fs/nfs/dir.c | 11 ++++-------
 1 file changed, 4 insertions(+), 7 deletions(-)
fs/nfs/dir.c +4 -7
index b296d90c8e14..4ceab6209e4a 100644
@@ -749,15 +749,12 @@ void nfs_prime_dcache(struct dentry *parent, struct nfs_entry *entry,
 		if (filename.len == 2 && filename.name[1] == '.')
 			return;
 	}
-	filename.hash = full_name_hash(parent, filename.name, filename.len);
 
-	dentry = d_lookup(parent, &filename);
 again:
-	if (!dentry) {
-		dentry = d_alloc_parallel(parent, &filename);
-		if (IS_ERR(dentry))
-			return;
-	}
+	dentry = d_alloc_trylock(parent, &filename);
+	if (IS_ERR(dentry))
+		return;
+
 	if (!d_in_lookup(dentry)) {
 		/* Is there a mountpoint here? If so, just exit */
 		if (!nfs_fsid_equal(&NFS_SB(dentry->d_sb)->fsid,
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#13 lore raw

PATCH v4 8/9 nfs: use d_alloc_trylock() in silly-rename

In reply to NeilBrown

From: NeilBrown <[email protected]>

Rather than performing a normal lookup (which will be awkward with future locking changes) use d_alloc_trylock() to find a dentry for an unused name, and then open-code the rest of lookup_slow() to see if it is free on the server.

---
 fs/nfs/unlink.c | 59 ++++++++++++++++++++++++++++++++-----------------
 1 file changed, 39 insertions(+), 20 deletions(-)
fs/nfs/unlink.c +39 -20
index 11a46a993e11..0eddc7ee1115 100644
@@ -451,7 +451,7 @@ nfs_sillyrename(struct inode *dir, struct dentry *dentry)
 	static unsigned int sillycounter;
 	unsigned char silly[SILLYNAME_LEN + 1];
 	unsigned long long fileid;
-	struct dentry *sdentry;
+	struct dentry *sdentry, *old;
 	struct inode *inode = d_inode(dentry);
 	struct rpc_task *task;
 	int            error = -EBUSY;
@@ -468,26 +468,45 @@ nfs_sillyrename(struct inode *dir, struct dentry *dentry)
 
 	fileid = d_inode(dentry)->i_ino;
 
-	sdentry = NULL;
-	do {
+newname:
+	sillycounter++;
+	scnprintf(silly, sizeof(silly),
+		  SILLYNAME_PREFIX "%0*llx%0*x",
+		  SILLYNAME_FILEID_LEN, fileid,
+		  SILLYNAME_COUNTER_LEN, sillycounter);
+
+	dfprintk(VFS, "NFS: trying to rename %pd to %s\n", dentry, silly);
+	sdentry = d_alloc_trylock(dentry->d_parent, &QSTR(silly));
+	if (sdentry == ERR_PTR(-EWOULDBLOCK))
+		/* Name currently being looked up */
+		goto newname;
+	if (IS_ERR(sdentry))
+		goto out;
+	if (!d_in_lookup(sdentry)) {
+		if (d_really_is_negative(sdentry)) {
+			/* try to get an in-lookup dentry */
+			d_drop(sdentry);
+			sillycounter--;
+		}
 		dput(sdentry);
-		sillycounter++;
-		scnprintf(silly, sizeof(silly),
-			  SILLYNAME_PREFIX "%0*llx%0*x",
-			  SILLYNAME_FILEID_LEN, fileid,
-			  SILLYNAME_COUNTER_LEN, sillycounter);
-
-		dfprintk(VFS, "NFS: trying to rename %pd to %s\n",
-				dentry, silly);
-
-		sdentry = lookup_noperm(&QSTR(silly), dentry->d_parent);
-		/*
-		 * N.B. Better to return EBUSY here ... it could be
-		 * dangerous to delete the file while it's in use.
-		 */
-		if (IS_ERR(sdentry))
-			goto out;
-	} while (d_inode(sdentry) != NULL); /* need negative lookup */
+		goto newname;
+	}
+	/* This name isn't known locally - check on server */
+	old = nfs_lookup(dir, sdentry, 0);
+	d_lookup_done(sdentry);
+	/*
+	 * N.B. Better to return EBUSY here ... it could be
+	 * dangerous to delete the file while it's in use.
+	 */
+	if (IS_ERR(old)) {
+		dput(sdentry);
+		goto out;
+	}
+	if (old || d_is_positive(sdentry)) {
+		dput(old);
+		dput(sdentry);
+		goto newname;
+	}
 
 	ihold(inode);
 
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
author
#14 lore raw

PATCH v4 9/9 nfs: use d_duplicate()

In reply to NeilBrown

From: NeilBrown <[email protected]>

As preparation for d_alloc_parallel() being allowed without the directory locked, use d_duplicate() to duplicate a dentry for silly rename.

This results in an in-lookup name, so d_lookup_done() must be called.

---
 fs/nfs/dir.c | 13 ++++++++-----
 1 file changed, 8 insertions(+), 5 deletions(-)
fs/nfs/dir.c +8 -5
index 4ceab6209e4a..1a5f64ed26b6 100644
@@ -2819,11 +2819,12 @@ int nfs_rename(const struct mnt_idmap *idmap, struct inode *old_dir,
 			spin_unlock(&new_dentry->d_lock);
 
 			/* copy the target dentry's name */
-			dentry = d_alloc(new_dentry->d_parent,
-					 &new_dentry->d_name);
-			if (!dentry)
+			dentry = d_duplicate(new_dentry);
+			if (IS_ERR(dentry)) {
+				/* Keep using -ETXTBSY error */
+				dentry = NULL;
 				goto out;
-
+			}
 			/* silly-rename the existing target ... */
 			err = nfs_sillyrename(new_dir, new_dentry);
 			if (err)
@@ -2888,8 +2889,10 @@ int nfs_rename(const struct mnt_idmap *idmap, struct inode *old_dir,
 		nfs_dentry_handle_enoent(old_dentry);
 
 	/* new dentry created? */
-	if (dentry)
+	if (dentry) {
+		d_lookup_done(dentry);
 		dput(dentry);
+	}
 	return error;
 }
 EXPORT_SYMBOL_GPL(nfs_rename);
Signature · 1 line
2.50.0.107.gf914562f5916.dirty
maintainer
#15 lore raw
In reply to NeilBrown

Hi Neil,

Quoted 2 lines · NeilBrown

Now that the requirement for this are upstream this could go via the NFS tree or the VFS tree.

Sounds good! I think we should plan to take this through the NFS tree.

Thanks,
Anna

Quoted 46 lines

Thanks,
NeilBrown

This v4 fixes the problems with patch 1 which Jonathan Flynn helped me to understand. And *actually* adds Anna's Acked-by.

Before this v3 fixed three bugs found by Sashiko - all error-path related.

1/ patch 5 - make sure d_drop() gets called in all error cases 2/ patch 8 - dput() sdentry on all error paths
3/ patch 9 - check error return from d_duplicate() correctly.

Original intro:
I am working on changes to directory locking. The medium term goal is to lift d_alloc_parallel() locking above i_rwsem, so d_alloc_paralle() can be run unlocked, and consequently cannot be called when ->i_rwsem is held.

The requires:
1/ the d_alloc_parallel() not be called while i_rwsem is held. NFS does
this in a few places. New interfaces d_alloc_trylock() and d_duplicate() are now available and can be used instead.

2/ a dentry must not be d_drop()ed while an operation is ongoing, as an
unlocked d_alloc_parallel() would then be able to create a new dentry with the same name. In particular d_rehash() must be phased out as it won't be safe. Various techiniques are used to avoid the need for d_drop(), particularly that d_splice_alias() is now able to splice a hashed alias.

Further, the first two patches here fixes bugs that I found while developing and reviewing these changes.

[PATCH v4 1/9] nfs: fix open-blocking with d_fsdata [PATCH v4 2/9] nfs: fix nfs_call_unlink()
[PATCH v4 3/9] nfs: remove d_drop()/d_alloc_parallel() from [PATCH v4 4/9] nfs: use d_splice_alias() in nfs_link() [PATCH v4 5/9] nfs: don't d_drop() before d_splice_alias() [PATCH v4 6/9] nfs: don't d_drop() before d_splice_alias() in [PATCH v4 7/9] nfs: Use d_alloc_trylock() in nfs_prime_dcache() [PATCH v4 8/9] nfs: use d_alloc_trylock() in silly-rename [PATCH v4 9/9] nfs: use d_duplicate()

#16 lore raw

cover vfs, nfs: concurrent create and unlink in one directory

In reply to NeilBrown

Hi Neil,

Thank you for this series; it is what makes these patches possible. I had them on your v3 and have rebased them onto v4. They extend it so that processes on one NFSv4 client can create and remove files in one directory concurrently.

  operations per second   parent exclusive   parent shared   ratio
  creates                            2,616          29,939   11.4x
  removals                           2,157          32,360   15.0x

One client, 96 processes in one directory, each creating files (open O_CREAT, a small write, close) for a set time, then removing them all; NFSv4.2 to a pNFS metadata server that is not knfsd; your v4, the 7.4 VFS changes it builds on, the three silly-delete fixes and this series on a 7.3-based kernel, among other patches. Each row switched only its own path, by a test-only module parameter not in this series, with the other path on; one run each. The creates row comes from 300 s of creates. The removals row comes from 120 s of creates, and each of its runs removed about 3.7 million files; the removal rates vary with that number, so it is given. With the parent held exclusive, operations go one server round trip at a time. 2/12 quotes an earlier measurement, on a 7.1.13-based kernel.

How it works. 2/12 lets a filesystem have the parent locked shared for O_CREAT (a flag in a new ->iop_flags field), and 6/12 for unlink(2) (->unlink_shared() and ->unlink_shared_done()). The dentry then excludes the name: for a create, its in-lookup state, all nfs_atomic_open() needs since your 3/9; for a removal, an NFS mark that lookups, opens and creates of the name wait on until ->unlink_shared_done(), which the VFS calls after the fsnotify delete event, if any. What NFS cannot order that way, such as an open file, it hands back to ->unlink() under the exclusive lock; where the server reports itself case-insensitive or not case-preserving, NFS sets SB_I_NAMES_COLLIDE (3/12) and both keep the exclusive lock. Both paths call d_alloc_parallel() under the shared lock, as lookup does. When your directory-locking changes lift d_alloc_parallel() above i_rwsem, these calls have to move with lookup's; the exclusion does not change, and the opt-ins go once the VFS stops taking the parent lock (2/12, 6/12).

Patch flow:

  prereq   1  store re-read server capabilities in one step, for 3
  create   2  VFS opt-in to take the parent lock shared for O_CREAT
           3  NFS sets SB_I_NAMES_COLLIDE where names can collide
           4  NFSv4 directories opt in for O_CREAT
  remove   5  factor vfs_unlink() into a helper, no functional change
           6  VFS opt-in: ->unlink_shared(), ->unlink_shared_done()
           7  a second ->d_fsdata mark, for removals under a shared lock
           8  keep a dentry carrying that mark hashed
           9  no new dentries from a listing that a removal overlapped
          10  the removal method, handing back what it cannot order
          11  look a name up again once its removal has unhashed it
          12  NFSv4 directories opt in for unlink

Three fixes for the silly-delete hand-off, which your 2/9 makes reachable, are posted separately, in reply to 2/9.

Tested on the same kernel over NFSv4.2, with the new paths on and off:
removal races (with listings, and with tasks killed); O_EXCL creates racing unlink, with a kernel-side check that no revalidation trusted a removed entry; inotify event order; two clients; and an overlayfs mount whose lower file another client renamed away and back. All passed, with no kernel warning or hung task, except the two-client test's check that nothing was left behind: on this kernel and on one with an earlier revision of this series, it found one silly-renamed file in three of four runs, with the new paths off as well as on, so they are not the cause. Each time, the file left behind was not the one that had been
silly-renamed: the silly-rename's RENAME, which goes by name, had moved another file of that name onto the hidden name. A PROVE_LOCKING and KASAN build ran the removal, killed-task and O_EXCL tests with no report. A case-insensitive server, where two spellings of a name never made two files, was tested on that earlier revision only; that code has not changed since. Not run: fstests, knfsd as the server, NFSv4.0 or 4.1, directory delegations (the server grants none), CONFIG_DEBUG_VFS, a weakly ordered CPU.

One question: are the opt-ins in 2/12 and 6/12 acceptable as interim interfaces until the directory-locking changes land?

The series applies to 83f32c773255 in Linus's tree on top of your v4 and the three silly-delete fixes. fs/ compiles there without warnings at every commit, with and without CONFIG_DEBUG_VFS and lockdep; I have run it only on the 7.3-based kernel above.

Tools: these patches, their changelogs, the race tests and this letter were written with Claude Code, using Anthropic's Claude Opus 5 and Claude Opus 5.5 models, at my direction over many sessions: I chose among the designs it proposed and directed each revision. It found, by reading the code, the bug that 1/12 fixes: while the client reads a server's capabilities again, a capability the server still offers can look missing. The three silly-delete fixes, posted separately, say which of their problems it found and how they were tested.

Thanks,
Jonathan

Jonathan Flynn (12):
nfs: update a server's capabilities in one step
vfs: allow the parent lock to be shared for O_CREAT
nfs: tell the VFS when two names can be one entry on the server
nfs: concurrent O_CREAT in one NFSv4 directory
vfs: factor file removal into a helper, no functional change
vfs: let a filesystem remove files with the parent directory locked
shared
nfs: add a second mark for a removal made with the parent locked
shared
nfs: keep the dentry of a shared-parent removal hashed
nfs: do not cache a name from a listing that a removal overlapped
nfs: add the removal method for a parent directory locked shared
nfs: look a name up again once its removal has unhashed it
nfs: remove files with the parent directory locked shared on NFSv4

 .../filesystems/directory-locking.rst         |  60 +++
 Documentation/filesystems/locking.rst         | 259 ++++++++++++-
 Documentation/filesystems/porting.rst         |  35 ++
 Documentation/filesystems/vfs.rst             |  25 ++
 fs/namei.c                                    | 360 +++++++++++++++++-
 fs/nfs/client.c                               |   1 +
 fs/nfs/dir.c                                  | 300 ++++++++++++++-
 fs/nfs/inode.c                                |   2 +
 fs/nfs/internal.h                             | 211 ++++++++++
 fs/nfs/nfs4file.c                             |   9 +-
 fs/nfs/nfs4proc.c                             |  35 +-
 fs/nfs/nfstrace.h                             |   2 +
 fs/nfs/super.c                                |   2 +
 fs/nfs/unlink.c                               |  16 +-
 include/linux/fs.h                            |  72 ++++
 include/linux/fs/super_types.h                |   1 +
 include/linux/nfs_fs.h                        |  28 ++
 17 files changed, 1361 insertions(+), 57 deletions(-)

base-commit: 83f32c773255720a661aa45d83e36278135f23f5
prerequisite-patch-id: 3405b4d6ab8b0bf24ba63a898083d617deec4f24
prerequisite-patch-id: 096657d6d80d7ca533ccb574d2af65611ede4af2
prerequisite-patch-id: 1a2319c14739918aef86116647fea28ae85ad4df
prerequisite-patch-id: 725cb18c3936d50141ef27dafc159bf50b64a5bd
prerequisite-patch-id: b39cdd352b97e2cd247311fd5db620dbff227bd7
prerequisite-patch-id: f9f3f0e945cadf96113d4ac9ab8f7b0c207af4e5
prerequisite-patch-id: 4c09a15390bb556d79bea1ee733f52a58bec80ef
prerequisite-patch-id: 7c026717a97b2c86a169539822f5d14650f68f8a
prerequisite-patch-id: a702d54495d0f3d7f88b82411d884dcf5aacf9a0
prerequisite-patch-id: a7e7263e8916612f3e4b767946b5d9259029f50e
prerequisite-patch-id: a8e5414df9d9912dcdf9bb1dbb2811ce326a1e1f
prerequisite-patch-id: e8050b998d5790f3bb4311bc65011735ed7d8b2f

Signature · 1 line
2.43.0
#17 lore raw

RFC PATCH 1/12 nfs: update a server's capabilities in one step

When the client reads a server's capabilities again, on remount, on migration, or when a later mount reuses a filesystem that is already mounted, it clears a group of them and then sets again, one at a time, each one the server still offers. Anything that tests one of them on another CPU in between sees it missing: a case-insensitive server looks case-sensitive, a server that supports security labels looks as if it does not.

Build the new set first and store it once, as the NFSv3 path already does.

This was found by an AI coding assistant (Claude Code) reviewing how the client derives these capabilities, and has not been reproduced.

---
 fs/nfs/nfs4proc.c | 28 ++++++++++++++++++----------
 1 file changed, 18 insertions(+), 10 deletions(-)
fs/nfs/nfs4proc.c +18 -10
index 22a2a4009d..113c199a6f 100644
@@ -3896,6 +3896,7 @@ static bool nfs4_server_delegtime_capable(struct nfs4_server_caps_res *res)
 
 static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *fhandle)
 {
+	unsigned int caps;
 	u32 minorversion = server->nfs_client->cl_minorversion;
 	u32 bitmask[3] = {
 		[0] = FATTR4_WORD0_SUPPORTED_ATTRS,
@@ -3953,7 +3954,13 @@ static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *f
 				     res.attr_bitmask[2];
 		}
 		memcpy(server->attr_bitmask, res.attr_bitmask, sizeof(server->attr_bitmask));
-		server->caps &=
+		/*
+		 * Build the new set in a local and store it once: a reader of
+		 * server->caps during the probe, such as a remount or migration
+		 * of a mounted filesystem, must not see these capabilities
+		 * cleared and then set again one by one.
+		 */
+		caps = server->caps &
 			~(NFS_CAP_ACLS | NFS_CAP_HARDLINKS | NFS_CAP_SYMLINKS |
 			  NFS_CAP_SECURITY_LABEL | NFS_CAP_FS_LOCATIONS |
 			  NFS_CAP_OPEN_XOR | NFS_CAP_DELEGTIME |
@@ -3961,22 +3968,22 @@ static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *f
 		server->fattr_valid = NFS_ATTR_FATTR_V4;
 		if (res.attr_bitmask[0] & FATTR4_WORD0_ACL &&
 				res.acl_bitmask & ACL4_SUPPORT_ALLOW_ACL)
-			server->caps |= NFS_CAP_ACLS;
+			caps |= NFS_CAP_ACLS;
 		if (res.has_links != 0)
-			server->caps |= NFS_CAP_HARDLINKS;
+			caps |= NFS_CAP_HARDLINKS;
 		if (res.has_symlinks != 0)
-			server->caps |= NFS_CAP_SYMLINKS;
+			caps |= NFS_CAP_SYMLINKS;
 		if (res.case_insensitive)
-			server->caps |= NFS_CAP_CASE_INSENSITIVE;
+			caps |= NFS_CAP_CASE_INSENSITIVE;
 		if ((res.attr_bitmask[0] & FATTR4_WORD0_CASE_PRESERVING) &&
 		    !res.case_preserving)
-			server->caps |= NFS_CAP_CASE_NONPRESERVING;
+			caps |= NFS_CAP_CASE_NONPRESERVING;
 #ifdef CONFIG_NFS_V4_SECURITY_LABEL
 		if (res.attr_bitmask[2] & FATTR4_WORD2_SECURITY_LABEL)
-			server->caps |= NFS_CAP_SECURITY_LABEL;
+			caps |= NFS_CAP_SECURITY_LABEL;
 #endif
 		if (res.attr_bitmask[0] & FATTR4_WORD0_FS_LOCATIONS)
-			server->caps |= NFS_CAP_FS_LOCATIONS;
+			caps |= NFS_CAP_FS_LOCATIONS;
 		if (!(res.attr_bitmask[0] & FATTR4_WORD0_FILEID))
 			server->fattr_valid &= ~NFS_ATTR_FATTR_FILEID;
 		if (!(res.attr_bitmask[1] & FATTR4_WORD1_MODE))
@@ -4009,9 +4016,10 @@ static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *f
 
 		if (res.open_caps.oa_share_access_want[0] &
 		    NFS4_SHARE_WANT_OPEN_XOR_DELEGATION)
-			server->caps |= NFS_CAP_OPEN_XOR;
+			caps |= NFS_CAP_OPEN_XOR;
 		if (nfs4_server_delegtime_capable(&res))
-			server->caps |= NFS_CAP_DELEGTIME;
+			caps |= NFS_CAP_DELEGTIME;
+		WRITE_ONCE(server->caps, caps);
 
 		memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
 		server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
Signature · 1 line
2.43.0
#18 lore raw

RFC PATCH 2/12 vfs: allow the parent lock to be shared for O_CREAT

In reply to Jonathan Flynn

The VFS chooses the mode of the parent directory's lock for an open from the open flags alone: O_CREAT takes it exclusive, everything else shared. That choice is made before any filesystem method is reachable, so a filesystem has nowhere to say that it does not need the exclusive lock for a create. For a network filesystem the consequence is direct:
a create is a server round trip, and the exclusive parent lock serializes those round trips, so creates in one directory proceed one round trip at a time however many threads are creating.

Add an ->iop_flags field to struct inode_operations, mirroring ->fop_flags, with one flag, IOPF_ATOMIC_OPEN_CREATE_SHARED. It is
transitional: it chooses how the parent is locked for a create, and goes away once the VFS no longer takes the parent lock for one. When a directory's operations set it and provide ->atomic_open(), lookup_open() takes the parent shared for an O_CREAT open as well, and then passes ->atomic_open() only an in-lookup dentry; dentry_create(), which nfsd uses, is still called with the parent held exclusive. A filesystem that does not set the flag sees no change: the field is zero. The field is the last member of a cacheline-aligned structure, so it occupies padding that was already there and no existing member moves.

With the parent held shared, exclusion for the name being created comes from the in-lookup protocol that lookup already relies on under a shared lock: the first thread to resolve a name publishes an in-lookup dentry that a second finds and waits on, and the name enters the main hash once. Every other directory-modifying operation -- create without an open, link, unlink, symlink, mkdir, rmdir, mknod and rename -- still takes the parent exclusive, so a shared create runs concurrently only with other creates and with what already holds the parent shared:
lookup, readdir and opens without O_CREAT. Unlink joins them only where a filesystem also provides ->unlink_shared(), added later in this series.

One case keeps the exclusive lock even where the flag is set: a superblock on which two names the dcache tells apart can be one directory entry, as on a case-insensitive server whose client does not fold case. The in-lookup protocol would exclude a second create of "foo" but not a create of "FOO", so such a filesystem sets SB_I_NAMES_COLLIDE in ->s_iflags, and may set or clear it while mounted; creates in its directories then take the parent exclusive.

The VFS has one gap of its own to close. A cached negative dentry that revalidates reaches the atomic-open method already hashed, outside the in-lookup protocol: safe under the exclusive lock, but under a shared one two threads could each hash a dentry for the name, leaving two hashed dentries for one name with nothing to detect it. So, for a create with the parent held shared, reject such a dentry and go round the existing loop, so that ->atomic_open() is then only ever handed an in-lookup dentry. On the filesystem that opts in later in this series this happens on every such create over a cached negative dentry, not only in a race, at the cost of a dentry allocation and an unhash but no extra round trip. The rest of what the exclusive lock provided, for the filesystem's own per-directory state and for a plain open of the same name, becomes the filesystem's responsibility, as Documentation/filesystems/locking.rst now states.

Since NeilBrown's "VFS: move mnt_want_write() and locking into lookup_open()", lookup_open() takes and drops the parent lock itself, so the flag is read there, once per pass, and decides both the lock mode and the rejection, with nothing threaded through a signature. With CONFIG_DEBUG_VFS, lookup_open() also warns if a create made with the parent held shared is about to hand ->atomic_open() a dentry that is not in-lookup; lockdep cannot see a missing exclusion, so nothing else would catch one.

This relies on in-lookup dentries being allocated with the parent's ->i_rwsem held, as d_alloc_parallel() is here. NeilBrown's "multiple-filesystems: prepare for changes to VFS locking" plans to invert that order; if it does, the lookup of the name being created moves ahead of the shared parent lock, and the exclusion, which is the dentry's in-lookup state and not the parent lock, is unchanged.

Measured with "nfs: concurrent O_CREAT in one NFSv4 directory" on a 7.1.13-based kernel carrying an earlier revision of both patches, using a test-only switch, not part of this series, to choose the lock mode at run time: with 60 processes on one client creating files (open with O_CREAT, a small write, close) in one directory, creates went from about 2,700 a second with the parent held exclusive to about 29,700 with it held shared. The shared rate stayed about flat from one to four clients, because one client already reached the server's limit.

---

Notes:
For reviewers and review tools; not part of the changelog.

An automated review of this patch (Claude Code running Sashiko's review prompts) reported that locking.rst misdescribes a d_rehash() of the in-lookup dentry, because a concurrent d_alloc_parallel() would find that dentry on the in-lookup chain and wait on it. It was checked and dropped: atomic_open() calls d_lookup_done() as soon as ->atomic_open() returns, and that takes the dentry off the in-lookup chain without the ->i_dir_seq window. A d_alloc_parallel() that sampled ->i_dir_seq and missed the hash before the d_rehash(), and scans the chain after the d_lookup_done(), neither retries nor waits, and hashes a second dentry for the name: the outcome the text describes.

 .../filesystems/directory-locking.rst         | 19 ++++
 Documentation/filesystems/locking.rst         | 81 ++++++++++++++++-
 fs/namei.c                                    | 86 +++++++++++++++++--
 include/linux/fs.h                            | 35 ++++++++
 include/linux/fs/super_types.h                |  1 +
 5 files changed, 214 insertions(+), 8 deletions(-)
Documentation/filesystems/directory-locking.rst +19 -0
index 6fdf0b02df..316f10cb3d 100644
@@ -25,6 +25,25 @@ For our purposes all operations fall in 6 classes:
 
 	* lock the directory we are accessing (exclusive)
 
+	An O_CREAT open is the one exception: if the filesystem has set
+	IOPF_ATOMIC_OPEN_CREATE_SHARED in ->iop_flags and its superblock has
+	not set SB_I_NAMES_COLLIDE, its ->atomic_open() for such an open is
+	called with the directory locked shared, and exclusion for the name
+	being created comes from the in-lookup state of the dentry instead -
+	see Documentation/filesystems/locking.rst.
+	That takes an existing lock in shared mode; it adds no lock and no
+	new ordering, so the ordering analysis below is unaffected.  That
+	holds while d_alloc_parallel() is called with the parent's ->i_rwsem
+	held, as it is here; once in-lookup dentries are taken before
+	->i_rwsem, the create's lookup has to move ahead of the shared parent
+	lock with them.
+
+	Such a create can sleep waiting for an in-lookup dentry while
+	holding the parent shared.  That is not a new wait: a shared-mode
+	lookup already does it, and no thread that has published an
+	in-lookup dentry needs the parent's ->i_rwsem to finish with it, so
+	the waiter cannot be blocking the thread that must wake it.
+
 3. object removal.  Locking rules:
 
 	* lock the parent (exclusive)
Documentation/filesystems/locking.rst +80 -1

93 lines not on this page · raw message

fs/namei.c +79 -7

120 lines not on this page · raw message

include/linux/fs.h +35 -0
index 3e240579e2..f14520194b 100644
@@ -1995,6 +1995,8 @@ enum fs_update_time {
 	FS_UPD_CMTIME,
 };
 
+typedef unsigned int __bitwise iop_flags_t;
+
 struct inode_operations {
 	struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
 	const char * (*get_link) (struct dentry *, struct inode *, struct delayed_call *);
@@ -2038,8 +2040,41 @@ struct inode_operations {
 			    struct dentry *dentry, struct file_kattr *fa);
 	int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
 	struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
+	iop_flags_t iop_flags;
 } ____cacheline_aligned;
 
+/*
+ * ->atomic_open() may be called with the parent directory's i_rwsem held
+ * shared even when O_CREAT is set.  A filesystem setting this accepts that,
+ * for such an open, the only exclusion against another opener of the same
+ * name is the in-lookup state of the dentry it is given:
+ *
+ *  - that dentry is always in-lookup (DCACHE_PAR_LOOKUP), so a concurrent
+ *    d_alloc_parallel() for the name finds it and waits on it;
+ *  - it must be hashed only through d_add() or d_splice_alias(), which end
+ *    the in-lookup state under the parent's i_dir_seq (d_add_ci() leaves it
+ *    unhashed and publishes the case-exact name instead).  Hashing it
+ *    with d_rehash() instead loses the exclusion: the name becomes findable
+ *    without the in-lookup state ending, so a concurrent d_alloc_parallel()
+ *    neither waits nor retries and a second dentry for the name can be
+ *    hashed;
+ *  - d_drop() on it does not break that: it unhashes from the main hash
+ *    only, leaving the in-lookup hash entry and the waiters in place;
+ *  - no other directory-modifying operation becomes concurrent.  ->create,
+ *    ->link, ->unlink, ->symlink, ->mkdir, ->rmdir, ->mknod and ->rename
+ *    still run with i_rwsem held exclusive, so an O_CREAT open is
+ *    serialized against all of them.  It runs concurrently with other
+ *    O_CREAT opens, with an ->atomic_open() for the same or another name
+ *    without O_CREAT, and with ->lookup() and ->iterate_shared(), which
+ *    already run with i_rwsem held shared.
+ *
+ * Ignored unless the filesystem also provides ->atomic_open, and ignored on
+ * a superblock with SB_I_NAMES_COLLIDE set in ->s_iflags: there the in-lookup
+ * state of "foo" does not exclude a create of "FOO", which the filesystem
+ * may make the same entry, so the parent is taken exclusive.
+ */
+#define IOPF_ATOMIC_OPEN_CREATE_SHARED	((__force iop_flags_t)(1 << 0))
+
 /* Did the driver provide valid mmap hook configuration? */
 static inline bool can_mmap_file(struct file *file)
 {
include/linux/fs/super_types.h +1 -0
index ecd96aeb1c..91f1522a0d 100644
@@ -352,5 +352,6 @@ struct super_block {
 #define SB_I_NOIDMAP	0x00002000	/* No idmapped mounts on this superblock */
 #define SB_I_ALLOW_HSM	0x00004000	/* Allow HSM events on this superblock */
 #define SB_I_NO_DATA_INTEGRITY	0x00008000 /* fs cannot guarantee data persistence on sync */
+#define SB_I_NAMES_COLLIDE	0x00010000 /* names the dcache tells apart can be one entry */
 
 #endif /* _LINUX_FS_SUPER_TYPES_H */
Signature · 1 line
2.43.0
#19 lore raw

RFC PATCH 3/12 nfs: tell the VFS when two names can be one entry on the server

In reply to Jonathan Flynn

A server that reports itself case-insensitive, or as not preserving case, can make one entry of two names that the client caches apart, because the client compares names byte for byte. Mark the filesystem on such a server with SB_I_NAMES_COLLIDE, from "vfs: allow the parent lock to be shared for O_CREAT", so that the VFS keeps the exclusive directory lock for creates there: the per-name exclusion that replaces the lock for a create made with it held shared covers one byte string, not the names the server treats as equal. The client learns this when it reads the server's capabilities, which it does again on remount, on migration and when a later mount reuses the filesystem, and it updates the mark each time.

This is a conservative fallback. A server that declares itself case-insensitive should itself treat the two names as one, but one that did not was seen making two files of one name when such creates arrived together. No filesystem relies on the mark yet, so nothing changes.

---
 fs/nfs/client.c   |  1 +
 fs/nfs/internal.h | 35 +++++++++++++++++++++++++++++++++++
 fs/nfs/nfs4proc.c |  1 +
 fs/nfs/super.c    |  2 ++
 4 files changed, 39 insertions(+)
fs/nfs/client.c +1 -0
index ea99b3c105..30206b309c 100644
@@ -975,6 +975,7 @@ static int nfs_probe_fsinfo(struct nfs_server *server, struct nfs_fh *mntfh, str
 			server->caps &= ~(NFS_CAP_CASE_INSENSITIVE |
 					  NFS_CAP_CASE_NONPRESERVING);
 		}
+		nfs_server_publish_name_caps(server);
 	}
 
 	if (clp->rpc_ops->discover_trunking != NULL &&
fs/nfs/internal.h +35 -0
index 5af6a032f1..34b8aff4e0 100644
@@ -224,6 +224,41 @@ int nfs_init_server_rpcclient(struct nfs_server *, const struct rpc_timeout *t,
 struct nfs_server *nfs_alloc_server(void);
 void nfs_server_copy_userdata(struct nfs_server *, struct nfs_server *);
 
+/*
+ * Tell the VFS whether this server can make one directory entry of two names
+ * that differ as byte strings.  NFS installs no ->d_hash or ->d_compare, so
+ * the dcache compares names byte for byte, while a server that is
+ * case-insensitive, or does not preserve case, makes "foo" and "FOO" one
+ * entry.  On such a server SB_I_NAMES_COLLIDE keeps the parent of an O_CREAT
+ * open locked exclusive; see atomic_open_create_shared() in fs/namei.c.
+ *
+ * server->caps is derived again on every probe of the server: at mount, at
+ * remount, on migration, and when a later mount reuses this superblock
+ * (nfs4_proc_get_root()).  So this is called wherever the case bits of
+ * server->caps are written, once they have their final value, and when the
+ * superblock is set up, because the first probe runs before it exists.  The
+ * value is what the probed file handle reported, normally the mount root's;
+ * the homogeneous attribute is not fetched, so a server whose answer differs
+ * below the root is described by the root.  Migration runs the probe from
+ * the state manager without ->s_umount, so the update is atomic, and it is
+ * made only when the value changes.  Two probes of one server at once can
+ * leave the bit as the earlier of them derived it; that needs the server's
+ * answer to change between them, and server->caps has the same race.
+ */
+static inline void nfs_server_publish_name_caps(struct nfs_server *server)
+{
+	struct super_block *sb = server->super;
+	unsigned long bits = 0;
+
+	if (!sb)
+		return;
+	if (READ_ONCE(server->caps) & (NFS_CAP_CASE_INSENSITIVE |
+				       NFS_CAP_CASE_NONPRESERVING))
+		bits = SB_I_NAMES_COLLIDE;
+	if ((READ_ONCE(sb->s_iflags) & SB_I_NAMES_COLLIDE) != bits)
+		set_mask_bits(&sb->s_iflags, SB_I_NAMES_COLLIDE, bits);
+}
+
 extern void nfs_put_client(struct nfs_client *);
 extern void nfs_free_client(struct nfs_client *);
 void nfs_cb_idr_remove(struct nfs_client *clp);
fs/nfs/nfs4proc.c +1 -0
index 113c199a6f..fac8450b65 100644
@@ -4020,6 +4020,7 @@ static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *f
 		if (nfs4_server_delegtime_capable(&res))
 			caps |= NFS_CAP_DELEGTIME;
 		WRITE_ONCE(server->caps, caps);
+		nfs_server_publish_name_caps(server);
 
 		memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
 		server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
fs/nfs/super.c +2 -0
index 23292680ad..e70cef88fb 100644
@@ -1082,6 +1082,8 @@ static void nfs_fill_super(struct super_block *sb, struct nfs_fs_context *ctx)
 			sb->s_export_op = &nfs_export_ops;
 		break;
 	}
+	/* The first probe of the caps ran before this superblock existed */
+	nfs_server_publish_name_caps(server);
 
 	sb->s_magic = NFS_SUPER_MAGIC;
 
Signature · 1 line
2.43.0
author
#20 lore raw

Re: [PATCH RFC 03/12] nfs: tell the VFS when two names can be one entry on the server

Quoted 12 lines · Jonathan Flynn

A server that reports itself case-insensitive, or as not preserving case, can make one entry of two names that the client caches apart, because the client compares names byte for byte. Mark the filesystem on such a server with SB_I_NAMES_COLLIDE, from "vfs: allow the parent lock to be shared for O_CREAT", so that the VFS keeps the exclusive directory lock for creates there: the per-name exclusion that replaces the lock for a create made with it held shared covers one byte string, not the names the server treats as equal. The client learns this when it reads the server's capabilities, which it does again on remount, on migration and when a later mount reuses the filesystem, and it updates the mark each time.

Quoted 4 lines

This is a conservative fallback. A server that declares itself case-insensitive should itself treat the two names as one, but one that did not was seen making two files of one name when such creates arrived together. No filesystem relies on the mark yet, so nothing changes.

We don't normally work around server bugs in the client. We tell the server maintainers to fix their server.

But we *certainly* don't work around them in the VFS with SB_I_NAMES_COLLIDE. That sort of fs behaviour might be tolerable for files but it is a real problem for directories!

Once we move directory locking into the filesystem, the NFS client code might choose to add extra locking for servers that might be problematic. It would then be entirely in the NFS code then, and up to the NFS maintainers to decide what to do.
But this logic does not, I think, belong in the VFS layer at all.

This just confirms me in my preference to continue on the path I have planned.

Hopefully next week I'll put together an RFC for the next steps, and we pursue the prep patches that haven't been acked yet.

Thanks,
NeilBrown

Quoted 96 lines
---
 fs/nfs/client.c   |  1 +
 fs/nfs/internal.h | 35 +++++++++++++++++++++++++++++++++++
 fs/nfs/nfs4proc.c |  1 +
 fs/nfs/super.c    |  2 ++
 4 files changed, 39 insertions(+)
fs/nfs/client.c +1 -0
index ea99b3c105..30206b309c 100644
@@ -975,6 +975,7 @@ static int nfs_probe_fsinfo(struct nfs_server *server, struct nfs_fh *mntfh, str
 			server->caps &= ~(NFS_CAP_CASE_INSENSITIVE |
 					  NFS_CAP_CASE_NONPRESERVING);
 		}
+		nfs_server_publish_name_caps(server);
 	}
 
 	if (clp->rpc_ops->discover_trunking != NULL &&
fs/nfs/internal.h +35 -0
index 5af6a032f1..34b8aff4e0 100644
@@ -224,6 +224,41 @@ int nfs_init_server_rpcclient(struct nfs_server *, const struct rpc_timeout *t,
 struct nfs_server *nfs_alloc_server(void);
 void nfs_server_copy_userdata(struct nfs_server *, struct nfs_server *);
 
+/*
+ * Tell the VFS whether this server can make one directory entry of two names
+ * that differ as byte strings.  NFS installs no ->d_hash or ->d_compare, so
+ * the dcache compares names byte for byte, while a server that is
+ * case-insensitive, or does not preserve case, makes "foo" and "FOO" one
+ * entry.  On such a server SB_I_NAMES_COLLIDE keeps the parent of an O_CREAT
+ * open locked exclusive; see atomic_open_create_shared() in fs/namei.c.
+ *
+ * server->caps is derived again on every probe of the server: at mount, at
+ * remount, on migration, and when a later mount reuses this superblock
+ * (nfs4_proc_get_root()).  So this is called wherever the case bits of
+ * server->caps are written, once they have their final value, and when the
+ * superblock is set up, because the first probe runs before it exists.  The
+ * value is what the probed file handle reported, normally the mount root's;
+ * the homogeneous attribute is not fetched, so a server whose answer differs
+ * below the root is described by the root.  Migration runs the probe from
+ * the state manager without ->s_umount, so the update is atomic, and it is
+ * made only when the value changes.  Two probes of one server at once can
+ * leave the bit as the earlier of them derived it; that needs the server's
+ * answer to change between them, and server->caps has the same race.
+ */
+static inline void nfs_server_publish_name_caps(struct nfs_server *server)
+{
+	struct super_block *sb = server->super;
+	unsigned long bits = 0;
+
+	if (!sb)
+		return;
+	if (READ_ONCE(server->caps) & (NFS_CAP_CASE_INSENSITIVE |
+				       NFS_CAP_CASE_NONPRESERVING))
+		bits = SB_I_NAMES_COLLIDE;
+	if ((READ_ONCE(sb->s_iflags) & SB_I_NAMES_COLLIDE) != bits)
+		set_mask_bits(&sb->s_iflags, SB_I_NAMES_COLLIDE, bits);
+}
+
 extern void nfs_put_client(struct nfs_client *);
 extern void nfs_free_client(struct nfs_client *);
 void nfs_cb_idr_remove(struct nfs_client *clp);
fs/nfs/nfs4proc.c +1 -0
index 113c199a6f..fac8450b65 100644
@@ -4020,6 +4020,7 @@ static int _nfs4_server_capabilities(struct nfs_server *server, struct nfs_fh *f
 		if (nfs4_server_delegtime_capable(&res))
 			caps |= NFS_CAP_DELEGTIME;
 		WRITE_ONCE(server->caps, caps);
+		nfs_server_publish_name_caps(server);
 
 		memcpy(server->cache_consistency_bitmask, res.attr_bitmask, sizeof(server->cache_consistency_bitmask));
 		server->cache_consistency_bitmask[0] &= FATTR4_WORD0_CHANGE|FATTR4_WORD0_SIZE;
fs/nfs/super.c +2 -0
index 23292680ad..e70cef88fb 100644
@@ -1082,6 +1082,8 @@ static void nfs_fill_super(struct super_block *sb, struct nfs_fs_context *ctx)
 			sb->s_export_op = &nfs_export_ops;
 		break;
 	}
+	/* The first probe of the caps ran before this superblock existed */
+	nfs_server_publish_name_caps(server);
 
 	sb->s_magic = NFS_SUPER_MAGIC;
 
Signature · 1 line
2.43.0
#21 lore raw

RFC PATCH 4/12 nfs: concurrent O_CREAT in one NFSv4 directory

In reply to Jonathan Flynn

Set IOPF_ATOMIC_OPEN_CREATE_SHARED in nfs4_dir_inode_operations, so that the VFS takes the parent shared rather than exclusive for an O_CREAT open in an NFSv4 directory. Creates of different names in one directory then stop serializing on the parent inode, except on a server that reports itself case-insensitive or not case-preserving, where "nfs: tell the VFS when two names can be one entry on the server" has set SB_I_NAMES_COLLIDE and creates keep the exclusive lock.

This is the only user of "vfs: allow the parent lock to be shared for O_CREAT", and what it needs from it is the guarantee that the dentry reaching the atomic-open method for a create is in-lookup. NFSv4 keeps the dentry the VFS gives it when O_CREAT is set, and publishes the new inode on that dentry; because it is in-lookup, the dentry is not in the main hash, so dropping it is a no-op and publishing it is permitted. The name enters the hash exactly once, and until it does, a concurrent lookup or create of the same name finds the in-lookup dentry and waits.

NFS does not use the exclusive parent lock to serialize its own per-directory state, which is what that patch asks an opting-in filesystem to promise. Both pieces of state a create touches are already under finer locks: the directory's change attribute and the cache-validity bookkeeping that moves with it are updated under the directory's own spinlock, and a dentry's directory verifier is stored under that dentry's lock. Neither needs the parent lock held exclusive, or held at all. The verifier is also ordered so that losing a race can only cost work: a verifier offered against a directory state it no longer reflects is declined rather than stored, so the failure direction is an extra revalidation, never a dentry claiming stale validity.

Lookup and readdir already run with the parent held shared, and readdir already instantiates dentries there under that lock:
nfs_prime_dcache() takes an in-lookup dentry with d_alloc_trylock(), skipping a name another thread holds in-lookup, and invalidates and retries a hashed dentry that no longer matches the listing. A create joins concurrency NFS already handles.

NeilBrown's "nfs: remove d_drop()/d_alloc_parallel() from nfs_atomic_open()" states that the method has exclusive access to the dentry in one of two ways: O_CREAT, where the parent is held exclusive, or a dentry carrying DCACHE_PAR_LOOKUP. Setting the flag removes the first of those for open(2), which reaches the method through lookup_open(); nfsd reaches it through dentry_create(), which still holds the parent exclusive. "vfs: allow the parent lock to be shared for O_CREAT" supplies the second in its place: with the parent held shared for a create, a hashed negative dentry is rejected and the lookup retried, so an in-lookup dentry is what reaches the method. NFS's invalidation of a cached negative for LOOKUP_OPEN and that rejection do not overlap: nfs_neg_need_reval() returns 0 for LOOKUP_CREATE before it can reach the LOOKUP_OPEN case that invalidates a cached negative, so the invalidation that covers a plain open never fires for a create, and the rejection in "vfs: allow the parent lock to be shared for O_CREAT" never fires for anything else. The opener newly in company with a shared create is one opening the same name without O_CREAT, and that is the opener the invalidation covers.

The flag goes on the NFSv4 directory operations only. NFSv2 and NFSv3 reach a different atomic-open path, which has not been analysed or exercised under a shared parent lock, so it does not get the flag; adding it later is one line. Referral and automount directories are unaffected, since they are given different operations vectors.

Every other directory-modifying operation still takes the parent exclusive; for unlink that changes when "nfs: remove files with the parent directory locked shared on NFSv4", later in this series, gives NFSv4 ->unlink_shared().

The measured effect, from a 7.1.13-based kernel carrying an earlier revision of both patches, is in "vfs: allow the parent lock to be shared for O_CREAT".

---
 fs/nfs/nfs4proc.c | 1 +
 1 file changed, 1 insertion(+)
fs/nfs/nfs4proc.c +1 -0
index fac8450b65..808bb8f1c1 100644
@@ -10869,6 +10869,7 @@ static const struct inode_operations nfs4_dir_inode_operations = {
 	.setattr	= nfs_setattr,
 	.listxattr	= nfs4_listxattr,
 	.fileattr_get	= nfs_fileattr_get,
+	.iop_flags	= IOPF_ATOMIC_OPEN_CREATE_SHARED,
 };
 
 static const struct inode_operations nfs4_file_inode_operations = {
Signature · 1 line
2.43.0
#22 lore raw

RFC PATCH 5/12 vfs: factor file removal into a helper, no functional change

In reply to Jonathan Flynn

Move the body of vfs_unlink() into a static helper, __vfs_unlink(), that calls the method it is passed in place of ->unlink(), or ->unlink() when passed NULL. vfs_unlink() becomes a wrapper that passes NULL, so every caller behaves exactly as before; its kerneldoc, including the requirement that the caller hold the parent directory's lock exclusive, does not change.

This prepares for a second removal method, called with the parent directory's lock held shared, which a following patch adds.

---
 fs/namei.c | 26 ++++++++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)
fs/namei.c +24 -2
index ce10a408d3..1b3a605ded 100644
@@ -5679,6 +5679,12 @@ SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
 	return filename_rmdir(AT_FDCWD, name);
 }
 
+static int __vfs_unlink(const struct mnt_idmap *idmap, struct inode *dir,
+			struct dentry *dentry,
+			struct delegated_inode *delegated_inode,
+			int (*method)(struct inode *dir,
+				      struct dentry *dentry));
+
 /**
  * vfs_unlink - unlink a filesystem object
  * @idmap:	idmap of the mount the inode was found from
@@ -5706,6 +5712,20 @@ SYSCALL_DEFINE1(rmdir, const char __user *, pathname)
  */
 int vfs_unlink(const struct mnt_idmap *idmap, struct inode *dir,
 	       struct dentry *dentry, struct delegated_inode *delegated_inode)
+{
+	return __vfs_unlink(idmap, dir, dentry, delegated_inode, NULL);
+}
+EXPORT_SYMBOL(vfs_unlink);
+
+/*
+ * The body of vfs_unlink().  @method, if not NULL, is called in place of
+ * dir->i_op->unlink(); vfs_unlink() passes NULL.
+ */
+static int __vfs_unlink(const struct mnt_idmap *idmap, struct inode *dir,
+			struct dentry *dentry,
+			struct delegated_inode *delegated_inode,
+			int (*method)(struct inode *dir,
+				      struct dentry *dentry))
 {
 	struct inode *target = dentry->d_inode;
 	int error = may_delete_dentry(idmap, dir, dentry, false);
@@ -5730,7 +5750,10 @@ int vfs_unlink(const struct mnt_idmap *idmap, struct inode *dir,
 			error = try_break_deleg(target, 0, delegated_inode);
 			if (error)
 				goto out;
-			error = dir->i_op->unlink(dir, dentry);
+			if (method)
+				error = method(dir, dentry);
+			else
+				error = dir->i_op->unlink(dir, dentry);
 			if (!error) {
 				dont_mount(dentry);
 				detach_mounts(dentry);
@@ -5750,7 +5773,6 @@ int vfs_unlink(const struct mnt_idmap *idmap, struct inode *dir,
 
 	return error;
 }
-EXPORT_SYMBOL(vfs_unlink);
 
 /*
  * Make sure that the actual truncation of the file will occur outside its
Signature · 1 line
2.43.0
#23 lore raw

RFC PATCH 6/12 vfs: let a filesystem remove files with the parent directory locked shared

In reply to Jonathan Flynn

Let removals of different files in one directory run concurrently on a filesystem that orders them itself. Today they are serialized by the directory's lock even when a server does the ordering, so tasks removing their own files from one shared directory wait for one another.

A filesystem opts in by providing two new inode operations alongside ->unlink(): ->unlink_shared() is called to unlink a file with the directory locked shared, and ->unlink_shared_done() after any delete event for that removal and before the lock is dropped, to end the exclusion for the name that ->unlink_shared() set up. The existing ->unlink() is still called only with the lock held exclusive, by every caller it has today, so neither removal method has to ask how the lock is held. ->unlink_shared() can hand a removal back by returning UNLINK_NEED_EXCL, having done nothing; the VFS then retries it with the lock held exclusive, through ->unlink(). A directory found by the shared lookup is retried the same way without the method being called, unless the name ends in a slash, which is answered -EISDIR from the type alone, as before. On a superblock marked SB_I_NAMES_COLLIDE, where two names the dcache tells apart can be one entry, removals take the lock exclusive from the start, as O_CREAT opens do there.

Because the exclusion lasts until the delete event for the removal has been emitted, an O_CREAT open of the same name made with the directory locked shared, as IOPF_ATOMIC_OPEN_CREATE_SHARED allows, emits its create event after that one. A create that arrives only once the removal has unhashed the dentry is not ordered against it while that event is being emitted.

The locking documentation sets out what the shared lock still guarantees, what the filesystem takes on in its place, and the costs. A handed-back removal goes through its permission, security and delegation checks, and its audit record, twice. Removals made with the lock shared bypass vfs_unlink(), so a probe on it no longer sees them; the security hooks and notifications still run. The victim is looked up through d_alloc_parallel() under the shared lock, and the argument that this adds no deadlock assumes, as today, that nothing holding an in-lookup dentry waits for the directory's lock.

No filesystem provides the methods yet, so nothing changes.

---
 .../filesystems/directory-locking.rst         |  41 +++
 Documentation/filesystems/locking.rst         | 180 +++++++++++-
 Documentation/filesystems/porting.rst         |  35 +++
 Documentation/filesystems/vfs.rst             |  25 ++
 fs/namei.c                                    | 260 +++++++++++++++++-
 include/linux/fs.h                            |  39 ++-
 6 files changed, 563 insertions(+), 17 deletions(-)
Documentation/filesystems/directory-locking.rst +41 -0
index 316f10cb3d..2d9533f824 100644
@@ -50,6 +50,47 @@ For our purposes all operations fall in 6 classes:
 	* find the victim
 	* lock the victim (exclusive)
 
+	unlink(2) of a non-directory is the one exception: if the
+	filesystem provides ->unlink_shared() together with ->unlink() and
+	->unlink_shared_done(), and its superblock has not set
+	SB_I_NAMES_COLLIDE, the parent is locked shared for it, the victim
+	is found through d_alloc_parallel() and locked exclusive as before,
+	and exclusion for the name comes from the filesystem instead - see
+	Documentation/filesystems/locking.rst.  That takes an existing lock
+	in shared mode and in the existing order, parent before victim; it
+	adds no lock and no new ordering.  That holds while
+	d_alloc_parallel() is called with the parent's ->i_rwsem held, as it
+	is here; once in-lookup dentries are taken before ->i_rwsem, the
+	lookup of the victim has to move ahead of the shared parent lock with
+	them.  If the filesystem declines, or the victim turns out to be a
+	directory, everything is dropped and the removal is done again under
+	the rules above; a name ending in a slash is instead answered -EISDIR
+	or -ENOTDIR from the victim's type alone, as before.
+
+	The victim's parent and name are stable under the shared lock
+	because it is not a directory.  Splicing (see below) moves only
+	directory aliases, and can do so holding the old parent no more
+	than shared, which is why a directory found by the shared lookup is
+	let go with nothing but its type examined.  Any other change of a
+	dentry's parent or name is made by __d_move() for a rename, and
+	every rename holds the parents involved exclusive.  That includes a
+	filesystem renaming the victim to carry out a removal, which
+	->unlink_shared() must therefore hand back.  With the victim's
+	parent and name stable, the ordering analysis below is unaffected.
+
+	Such a removal can make a lookup of its name wait in
+	->d_revalidate() while that lookup holds the parent shared.  The
+	wake comes after the VFS has emitted the delete event, which the
+	removal reaches having let the victim go: by then it needs ->d_lock
+	and the victim's ->i_lock for the unhash, and the notification
+	subsystem's own locks and an allocation for the event.  A waiter in
+	->d_revalidate() holds the parent shared and a reference on the
+	dentry and takes no lock of its own, so it still cannot be blocking
+	the thread that must wake it; the wait is as long as the removal and
+	its delete event together.  An O_CREAT open made under the exception
+	in class 2 can wait there in the same way, and for the same reason
+	cannot be blocking the remover either.
+
 4. link creation.  Locking rules:
 
 	* lock the parent (exclusive)
Documentation/filesystems/locking.rst +175 -5

212 lines not on this page · raw message

Documentation/filesystems/porting.rst +35 -0
index c38f5df755..029c178e2f 100644
@@ -1422,3 +1422,38 @@ helpers take a const struct mnt_idmap *. mnt_idmap() and file_mnt_idmap()
 return one. The idmapping is immutable so nothing should have modified it
 anyway. References are taken and dropped via mnt_idmap_get() and
 mnt_idmap_put() as before, both accept a const pointer.
+
+---
+
+**informational**
+
+->unlink_shared() is added, as an optional inode operation.  A filesystem
+that does not provide it sees no change: ->unlink() is still called with the
+parent's ->i_rwsem held exclusive.  One that provides it has unlink(2) call
+it with the parent held shared instead, and takes on ordering a removal
+against the lookups and opens of the same name that the lock no longer
+excludes, and against its own directory listings.  It may return
+UNLINK_NEED_EXCL, having done nothing, to have ->unlink() called for that
+removal with the parent held exclusive after all; ->unlink() has to stay
+correct for that case and for every other caller of vfs_unlink().
+
+->unlink_shared() is paired with ->unlink_shared_done() and needs it: a
+filesystem that provides one without the other has not opted in.  Whatever
+->unlink_shared() installed to order the removal against the resolvers of the
+name is still installed when it returns, and ->unlink_shared_done() ends it,
+after any delete event the VFS emits for the removal.  The VFS calls it for
+every call of ->unlink_shared() that did not return a positive value, and for
+no other.
+
+For such a filesystem the ->iterate_shared() entry above no longer holds in
+full.  ->iterate_shared() is not excluded from that removal, and for dcache
+pre-seeding d_alloc_parallel() alone is not enough: a listing that may have
+been produced before a removal took effect, including one begun while the
+removal was in flight, must not instantiate the removed name, or refresh the
+inode being removed, once that removal may have completed.  See
+Documentation/filesystems/locking.rst.
+
+If the filesystem has also set IOPF_ATOMIC_OPEN_CREATE_SHARED, the opens
+that the lock no longer excludes include O_CREAT ones.  That flag already
+makes the ->iterate_shared() entry untrue for those opens, which hold the
+parent shared alongside ->iterate_shared().
Documentation/filesystems/vfs.rst +25 -0
index 1824462a43..a6eeac44e1 100644
@@ -419,6 +419,8 @@ As of kernel 2.6.22, the following members are defined:
 		struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
 		int (*link) (struct dentry *,struct inode *,struct dentry *);
 		int (*unlink) (struct inode *,struct dentry *);
+		int (*unlink_shared) (struct inode *,struct dentry *);
+		void (*unlink_shared_done) (struct inode *,struct dentry *);
 		int (*symlink) (const struct mnt_idmap *, struct inode *,struct dentry *,const char *);
 		struct dentry *(*mkdir) (const struct mnt_idmap *, struct inode *,struct dentry *,umode_t);
 		int (*rmdir) (struct inode *,struct dentry *);
@@ -481,6 +483,29 @@ otherwise noted.
 	called by the unlink(2) system call.  Only required if you want
 	to support deleting inodes
 
+``unlink_shared``
+	optional.  As ``unlink``, but called by the unlink(2) system
+	call with the parent directory's i_rwsem held shared, not
+	exclusive, and never for a directory.  Providing it, together
+	with ``unlink`` and ``unlink_shared_done``, is how a filesystem
+	opts in to concurrent removals in one directory; the filesystem
+	then itself orders a removal against the lookups and opens of the
+	same name that the lock no longer excludes, and against its own
+	directory listings.  It may return UNLINK_NEED_EXCL, having done
+	nothing, and the VFS then calls ``unlink`` for that removal with
+	the lock held exclusive.  ``unlink`` is still what every other
+	caller uses.  ``unlink_shared`` is not called on a superblock that
+	has set SB_I_NAMES_COLLIDE, except by a removal that read the bit
+	before it was set.  See Documentation/filesystems/locking.rst.
+
+``unlink_shared_done``
+	required with ``unlink_shared``.  Called after every call of
+	``unlink_shared`` that did not return a positive value, whether
+	the removal succeeded or not, after any delete event for it and
+	before the parent directory's i_rwsem is dropped, to end the
+	exclusion for the name that ``unlink_shared`` set up.  See
+	Documentation/filesystems/locking.rst.
+
 ``symlink``
 	called by the symlink(2) system call.  Only required if you want
 	to support symlinks.  You will probably need to call
fs/namei.c +249 -11

340 lines not on this page · raw message

include/linux/fs.h +38 -1
index f14520194b..c3dea996c0 100644
@@ -2041,8 +2041,41 @@ struct inode_operations {
 	int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
 	struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
 	iop_flags_t iop_flags;
+	/* Last, not beside ->unlink, so that no other member moves */
+	int (*unlink_shared)(struct inode *dir, struct dentry *dentry);
+	void (*unlink_shared_done)(struct inode *dir, struct dentry *dentry);
 } ____cacheline_aligned;
 
+/**
+ * enum unlink_shared_returns - positive returns of ->unlink_shared()
+ *
+ * @UNLINK_NEED_EXCL: this removal cannot be made with the parent's i_rwsem
+ *	held shared, and nothing was done.  The VFS drops the lock, takes it
+ *	exclusive, looks the name up again and calls ->unlink() for it, which
+ *	cannot ask again.
+ *
+ * ->unlink_shared() is ->unlink() for a filesystem that can remove a
+ * non-directory with the parent's i_rwsem held shared; providing it, along
+ * with ->unlink() and ->unlink_shared_done(), is the opt-in.  The VFS calls
+ * it only with the lock held shared and goes on calling ->unlink() only with
+ * the lock held exclusive, so neither method has to ask which mode it was
+ * given.  It returns 0, a negative errno, or a value from this enum, which
+ * no other inode operation may return.  What the VFS still provides under
+ * the shared lock, and what the filesystem owes for the exclusion the lock
+ * no longer gives, is set out in Documentation/filesystems/locking.rst.
+ *
+ * ->unlink_shared() returns with whatever it installed to order the removal
+ * against the resolvers of the name still installed, and
+ * ->unlink_shared_done() ends it.  The VFS calls that after any delete
+ * event for the removal and before it drops the parent's i_rwsem, for every
+ * call of ->unlink_shared() that did not return a positive value and for no
+ * other, so a filesystem providing one without the other has not opted in
+ * and its removals keep the exclusive lock.
+ */
+enum unlink_shared_returns {
+	UNLINK_NEED_EXCL	= 1,
+};
+
 /*
  * ->atomic_open() may be called with the parent directory's i_rwsem held
  * shared even when O_CREAT is set.  A filesystem setting this accepts that,
@@ -2066,7 +2099,11 @@ struct inode_operations {
  *    serialized against all of them.  It runs concurrently with other
  *    O_CREAT opens, with an ->atomic_open() for the same or another name
  *    without O_CREAT, and with ->lookup() and ->iterate_shared(), which
- *    already run with i_rwsem held shared.
+ *    already run with i_rwsem held shared.  A filesystem that also
+ *    provides ->unlink_shared() adds the removal of a non-directory to
+ *    that list, the same name included: it orders the two itself, and
+ *    ->unlink_shared_done() is what keeps the order of their
+ *    notifications for one name.  See enum unlink_shared_returns above.
  *
  * Ignored unless the filesystem also provides ->atomic_open, and ignored on
  * a superblock with SB_I_NAMES_COLLIDE set in ->s_iflags: there the in-lookup
Signature · 1 line
2.43.0
#24 lore raw

RFC PATCH 7/12 nfs: add a second mark for a removal made with the parent locked shared

In reply to Jonathan Flynn

Prepare the client to remove a file while its directory is locked shared. While a REMOVE of a cached name, or a RENAME onto it, is in flight, the client stores NFS_FSDATA_BLOCKED in the dentry's ->d_fsdata, and ->d_revalidate() waits for it to clear. Add a second mark, NFS_FSDATA_BLOCKED_SHARED, for a removal made with the directory locked shared. ->d_revalidate() waits on either, and nfs_call_unlink() does not hand a pending silly-delete to a dentry carrying either. The WARN_ON()s in nfs_unlink() and nfs_rename() still test for NFS_FSDATA_BLOCKED alone: they run with the directory locked exclusive, where the new mark cannot be present. Document every value ->d_fsdata can hold.

Nothing stores the new mark yet, so nothing changes. The lookup check is shared with NFSv2 and NFSv3, whose behavior is unchanged.

---
 fs/nfs/dir.c           | 11 +++++---
 fs/nfs/internal.h      | 58 ++++++++++++++++++++++++++++++++++++++++++
 fs/nfs/unlink.c        | 16 ++++++------
 include/linux/nfs_fs.h | 21 +++++++++++++++
 4 files changed, 94 insertions(+), 12 deletions(-)
fs/nfs/dir.c +7 -4
index dc7784b666..68a1e578e1 100644
@@ -1839,17 +1839,20 @@ static int
 __nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
 {
 	if (flags & LOOKUP_RCU) {
-		if (dentry->d_fsdata == NFS_FSDATA_BLOCKED)
+		/* One load: no lock is held and there are two values */
+		if (nfs_fsdata_blocked(READ_ONCE(dentry->d_fsdata)))
 			return -ECHILD;
 	} else {
+		void **fsdata = &dentry->d_fsdata;
+
 		/* Wait for unlink to complete - see unblock_revalidate().
 		 * smp_load_acquire() ensures ->d_fsdata is read after
 		 * ->d_seq was read, matching block_revalidate() which
 		 * sets ->d_fsdata before ->d_seq.
 		 */
-		wait_var_event(&dentry->d_fsdata,
-			       smp_load_acquire(&dentry->d_fsdata)
-			       != NFS_FSDATA_BLOCKED);
+		wait_var_event(fsdata,
+			       /* one load: there are two values to test */
+			       !nfs_fsdata_blocked(smp_load_acquire(fsdata)));
 	}
 	return 0;
 }
fs/nfs/internal.h +58 -0

64 lines not on this page · raw message

fs/nfs/unlink.c +8 -8
index 679ef22637..a2845198d6 100644
@@ -152,13 +152,13 @@ static int nfs_call_unlink(struct dentry *dentry, struct inode *inode, struct nf
 		 */
 		spin_lock(&alias->d_lock);
 		/*
-		 * Not if a removal of this name already owns the alias:
-		 * ->d_fsdata == NFS_FSDATA_BLOCKED means nfs_unlink() has a
-		 * REMOVE of exactly this name, or nfs_rename() a RENAME onto
-		 * it, in flight and ->d_revalidate() is waiting on that field,
-		 * so storing over it would lift the block early and the later
-		 * unblock_revalidate() would store NULL over @data.  Tested
-		 * under the same ->d_lock block_revalidate() stores under.
+		 * Not if a removal of this name already owns the alias: a
+		 * sentinel in ->d_fsdata means that a REMOVE of exactly this
+		 * name, or a RENAME onto it, is in flight, whichever way its
+		 * parent is locked, and ->d_revalidate() is waiting on that
+		 * field, so storing over it would lift the block early and
+		 * the later unblock_revalidate() would store NULL over @data.
+		 * Tested under the same ->d_lock the sentinel is stored under.
 		 * Skip rather than wait: that removal makes this sillydelete
 		 * redundant if it succeeds, and a wait here would sleep in a
 		 * dput() path -- the nfsiod callback that releases a
@@ -170,7 +170,7 @@ static int nfs_call_unlink(struct dentry *dentry, struct inode *inode, struct nf
 		if (d_really_is_positive(alias) &&
 		    !nfs_compare_fh(NFS_FH(inode), NFS_FH(d_inode(alias))) &&
 		    !(alias->d_flags & DCACHE_NFSFS_RENAMED) &&
-		    alias->d_fsdata != NFS_FSDATA_BLOCKED) {
+		    !nfs_dentry_is_blocked(alias)) {
 			devname_garbage = alias->d_fsdata;
 			alias->d_fsdata = data;
 			alias->d_flags |= DCACHE_NFSFS_RENAMED;
include/linux/nfs_fs.h +21 -0
index d2c716322c..b45952727c 100644
@@ -678,8 +678,29 @@ static inline bool nfs_ooo_test(struct nfs_inode *nfsi)
  * but deleted on the server resulting in ESTALE.
  * So use ->d_fsdata to record when the unlink is happening
  * and block dentry revalidation while it is set.
+ *
+ * ->d_fsdata of an NFS dentry holds one of:
+ *  - NULL;
+ *  - a mount's device name, a string kept on the mount's root dentry.
+ *    Whatever stores over it frees it, and ->d_release() frees it
+ *    otherwise;
+ *  - a pending silly-delete, a struct nfs_unlinkdata, exactly while
+ *    DCACHE_NFSFS_RENAMED is set, which is what tells it apart;
+ *  - NFS_FSDATA_BLOCKED, while a REMOVE of the name, or a RENAME onto it,
+ *    is in flight with the parent's i_rwsem held exclusive.  It outlives
+ *    that hold only when a rename is killed, until its RENAME completes;
+ *  - NFS_FSDATA_BLOCKED_SHARED, from the store in the client's
+ *    ->unlink_shared(), with the parent's i_rwsem held shared, until its
+ *    ->unlink_shared_done(), which the VFS calls after any delete event
+ *    for the removal, whether or not it succeeded, and before it drops
+ *    that hold.  The dentry may be negative, or positive and unhashed,
+ *    by then.
+ * Both sentinels are stored under ->d_lock and cleared by
+ * unblock_revalidate(), and ->d_revalidate() waits while either is set.
+ * fs/nfs/internal.h says what else has to respect them.
  */
 #define NFS_FSDATA_BLOCKED ((void*)1)
+#define NFS_FSDATA_BLOCKED_SHARED ((void *)2)
 
 # undef ifdebug
 # ifdef NFS_DEBUG
Signature · 1 line
2.43.0
#25 lore raw

RFC PATCH 8/12 nfs: keep the dentry of a shared-parent removal hashed

In reply to Jonathan Flynn

With the directory locked shared, a removal stays ordered against lookups and opens of the same name only through the name's dentry, whose ->d_revalidate() waits while the dentry is marked. Three paths act on a cached dentry without that wait: nfs_prime_dcache(), which unhashes a dentry that a directory listing disagrees with and otherwise refreshes its inode from the listing; nfs4_file_open() when the open fails; and recovery of open state. Make each of them leave a dentry marked by such a removal alone, so that it stays hashed until the removal itself deletes it, and so that a listing that may predate the removal does not stop the removal from dropping the link count.

Have nfs_prime_dcache() also leave alone a dentry that has been unhashed. When the listing holds a reference, a successful removal unhashes the dentry, rather than making it negative, before it clears the mark, and a refresh from a listing that predates the removal could then put back the link count that the removal took away. Without that reference the removal makes the dentry negative instead, and the listing treats the name as one it has no dentry for: the case that "nfs: do not cache a name from a listing that a removal overlapped" handles.

Of the three, only the listing runs beside such a removal by design, since it holds the directory shared too. The other two hold no directory lock, and can meet a marked dentry only through a reference taken after it was marked, by a path that does not wait for the mark:
an open by file handle, which NFSv4.1 and later mounts support. A lockless path walk that checked the dentry before it was marked fails its recheck and retries, because marking it also invalidates the dentry's sequence count.

Nothing marks a dentry this way yet, so the one change is that nfs_prime_dcache() leaves alone a dentry that something else has unhashed, rather than refreshing its inode or caching a replacement for it.

---
 fs/nfs/dir.c      | 42 +++++++++++++++++++++++++++++++++++++++
 fs/nfs/internal.h | 50 +++++++++++++++++++++++++++++++++++++++++++++++
 fs/nfs/nfs4file.c |  9 ++++++++-
 fs/nfs/nfs4proc.c |  3 ++-
 4 files changed, 102 insertions(+), 2 deletions(-)
fs/nfs/dir.c +42 -0
index 68a1e578e1..2a4c059064 100644
@@ -756,6 +756,48 @@ void nfs_prime_dcache(struct dentry *parent, struct nfs_entry *entry,
 		return;
 
 	if (!d_in_lookup(dentry)) {
+		bool hands_off;
+
+		/*
+		 * Leave alone a dentry that a removal made under a shared
+		 * parent anchors on, or that has been unhashed.  readdir holds
+		 * the parent shared as well, so it can run beside such a
+		 * removal, and while the REMOVE is in flight neither of the
+		 * two things done below is safe: unhashing the dentry would
+		 * let a lookup or open of the name overtake the REMOVE, and
+		 * refreshing its inode from this reply would advance the
+		 * attribute generation that the remover's nfs_drop_nlink()
+		 * compares against, so that the removed file kept its link
+		 * count.  Nor is a refresh safe once the REMOVE has succeeded,
+		 * since this reply can still list the name: on a server that
+		 * reports how its change attribute behaves, nfs_refresh_inode()
+		 * takes attributes with a newer change attribute whatever
+		 * their generation, and would put back the link count that
+		 * the removal took away.
+		 *
+		 * Both are tested once, before anything else is done with the
+		 * dentry, in a ->d_lock section of their own.  This caller has
+		 * held a counted reference since before the test, and the
+		 * remover stores the sentinel only on a dentry whose count it
+		 * reads as one in the section it stores in: either the remover
+		 * sees this reference and hands the removal back, or the
+		 * sentinel was stored first.  If the REMOVE then succeeds, the
+		 * VFS calls d_delete() before ->unlink_shared_done() clears the
+		 * sentinel.  A d_delete() that finds this reference only
+		 * unhashes the dentry, under ->d_lock, so a test that finds the
+		 * sentinel gone comes after that section and sees the unhash.
+		 * One that ran before this reference was taken left the dentry
+		 * negative instead, and the code below drops a negative dentry
+		 * and treats the name as one it has no dentry for.  -ENOENT
+		 * ends either way too, through nfs_dentry_handle_enoent(), and
+		 * any other failure leaves the file in place.
+		 */
+		spin_lock(&dentry->d_lock);
+		hands_off = nfs_dentry_is_shared_anchor(dentry) ||
+			    d_unhashed(dentry);
+		spin_unlock(&dentry->d_lock);
+		if (hands_off)
+			goto out;
 		/* Is there a mountpoint here? If so, just exit */
 		if (!nfs_fsid_equal(&NFS_SB(dentry->d_sb)->fsid,
 					&entry->fattr->fsid))
fs/nfs/internal.h +50 -0

56 lines not on this page · raw message

fs/nfs/nfs4file.c +8 -1
index 9a434f5dda..ccb801ab38 100644
@@ -101,7 +101,14 @@ nfs4_file_open(struct inode *inode, struct file *filp)
 	return err;
 
 out_drop:
-	d_drop(dentry);
+	/*
+	 * Unhash, unless a removal made under a shared parent anchors on
+	 * the dentry.  For an open by path, -EOPENSTALE makes the VFS redo
+	 * the lookup either way, and that lookup waits for the removal in
+	 * ->d_revalidate(); an open by file handle is not looked up again,
+	 * as it never was.
+	 */
+	nfs_d_drop_unless_anchored(dentry);
 	err = -EOPENSTALE;
 	goto out_put_ctx;
 }
fs/nfs/nfs4proc.c +2 -1
index 808bb8f1c1..fbf9e97815 100644
@@ -2791,8 +2791,9 @@ static int _nfs4_open_expired(struct nfs_open_context *ctx, struct nfs4_state *s
 	 */
 	opendata->o_arg.open_flags = O_DIRECT;
 	ret = nfs4_open_recover(opendata, state);
+	/* Unhash, unless a removal under a shared parent anchors here */
 	if (ret == -ESTALE)
-		d_drop(ctx->dentry);
+		nfs_d_drop_unless_anchored(ctx->dentry);
 	nfs4_opendata_put(opendata);
 	return ret;
 }
Signature · 1 line
2.43.0
#26 lore raw

RFC PATCH 9/12 nfs: do not cache a name from a listing that a removal overlapped

In reply to Jonathan Flynn

With a removal holding the directory lock shared, a directory listing, which holds it shared too, can run beside it, and the server can build the listing before the removal while the client reads it after. The client would then put the removed name back in its cache as a valid entry, and keep it for as long as it trusts its cached view of the directory.

Count, per directory, the removals made with the directory locked shared:
those waiting for the server's answer, and those that have had it. A listing notes the second count before it is requested, and adds no new name to the cache while a removal is waiting or once one has been answered since. Positive entries already in the cache are covered by "nfs: keep the dentry of a shared-parent removal hashed".

Nothing counts a removal yet, so nothing changes. NFSv2 and NFSv3 listings note the count too, and NFSv3 listings that return attributes make the same check; the behavior of both is unchanged.

---
 fs/nfs/dir.c           | 16 +++++++++--
 fs/nfs/inode.c         |  2 ++
 fs/nfs/internal.h      | 63 ++++++++++++++++++++++++++++++++++++++++++
 include/linux/nfs_fs.h |  8 ++++++
 4 files changed, 87 insertions(+), 2 deletions(-)
fs/nfs/dir.c +14 -2
index 2a4c059064..d9ba3cb1d7 100644
@@ -165,6 +165,7 @@ struct nfs_readdir_descriptor {
 
 	__be32		verf[NFS_DIR_VERIFIER_SIZE];
 	unsigned long	dir_verifier;
+	unsigned long	shared_removal_seq;
 	unsigned long	timestamp;
 	unsigned long	gencount;
 	unsigned long	attr_gencount;
@@ -603,6 +604,7 @@ static int nfs_readdir_xdr_filler(struct nfs_readdir_descriptor *desc,
 	timestamp = jiffies;
 	gencount = nfs_inc_attr_generation_counter();
 	desc->dir_verifier = nfs_save_change_attribute(inode);
+	desc->shared_removal_seq = nfs_dir_shared_removal_seq(inode);
 	error = NFS_PROTO(inode)->readdir(&arg, &res);
 	if (error < 0) {
 		/* We requested READDIRPLUS, but the server doesn't grok it */
@@ -723,7 +725,7 @@ static void nfs_lookup_advise_force_readdirplus(struct inode *dir,
 
 static
 void nfs_prime_dcache(struct dentry *parent, struct nfs_entry *entry,
-		unsigned long dir_verifier)
+		      unsigned long dir_verifier, unsigned long removal_seq)
 {
 	struct qstr filename = QSTR_INIT(entry->name, entry->len);
 	struct dentry *dentry;
@@ -825,6 +827,15 @@ void nfs_prime_dcache(struct dentry *parent, struct nfs_entry *entry,
 		d_lookup_done(dentry);
 		goto out;
 	}
+	/*
+	 * Make no dentry for a name that a removal under a shared parent may
+	 * have taken away after the server built this listing; see
+	 * nfs_dir_shared_removal_since().
+	 */
+	if (nfs_dir_shared_removal_since(d_inode(parent), removal_seq)) {
+		d_lookup_done(dentry);
+		goto out;
+	}
 
 	nfs_set_verifier(dentry, dir_verifier);
 	inode = nfs_fhget(dentry->d_sb, entry->fh, entry->fattr);
@@ -853,7 +864,8 @@ static int nfs_readdir_entry_decode(struct nfs_readdir_descriptor *desc,
 	ret = xdr_decode(desc, entry, stream);
 	if (ret || !desc->plus)
 		return ret;
-	nfs_prime_dcache(file_dentry(desc->file), entry, desc->dir_verifier);
+	nfs_prime_dcache(file_dentry(desc->file), entry, desc->dir_verifier,
+			 desc->shared_removal_seq);
 	return 0;
 }
 
fs/nfs/inode.c +2 -0
index e0a2e92952..7885216a48 100644
@@ -426,6 +426,8 @@ static void nfs_inode_init_dir(struct nfs_inode *nfsi)
 	nfsi->cache_change_attribute = 0;
 	memset(nfsi->cookieverf, 0, sizeof(nfsi->cookieverf));
 	init_rwsem(&nfsi->rmdir_sem);
+	nfsi->shared_removal_seq = 0;
+	nfsi->shared_removals = 0;
 }
 
 /*
fs/nfs/internal.h +63 -0

69 lines not on this page · raw message

include/linux/nfs_fs.h +8 -0
index b45952727c..3e86449485 100644
@@ -205,6 +205,14 @@ struct nfs_inode {
 			/* Readers: in-flight sillydelete RPC calls */
 			/* Writers: rmdir */
 			struct rw_semaphore	rmdir_sem;
+			/*
+			 * Removals made with i_rwsem held shared: how many
+			 * have finished, and how many are waiting for the
+			 * reply to their REMOVE.  Both change under
+			 * ->i_lock; see fs/nfs/internal.h.
+			 */
+			unsigned long	shared_removal_seq;
+			unsigned int	shared_removals;
 		};
 		/* Regular file */
 		struct {
Signature · 1 line
2.43.0
#27 lore raw

RFC PATCH 10/12 nfs: add the removal method for a parent directory locked shared

In reply to Jonathan Flynn

Add the client's method for removing a file while its directory is locked shared. It handles one case: a cached name that nothing else is using. It marks the cached entry and sends the REMOVE, which the listing check of "nfs: do not cache a name from a listing that a removal overlapped" counts as waiting until the protocol's ->remove() returns, and as answered after. A second method, which the VFS calls after any delete event for the removal, clears the mark, so that a create of the same name that waited on it emits its create event after that delete event, not before. Everything else, such as an open file that would have to be renamed aside, or an entry that is no longer hashed or no longer names a file, is handed back untouched and done with the directory locked exclusive, as today. The VFS does not call the method on a server that reports itself case-insensitive or not case-preserving, and the method hands back any removal that reaches it there. A warning fires if the marked entry is found dropped from the cache when the removal succeeds.

Two new trace events record the attempts made this way and the hand-backs, so a trace shows whether removals took this path. Make block_revalidate() a wrapper around a new __block_revalidate(), which stores the mark it is given; the wrapper still stores NFS_FSDATA_BLOCKED, and now warns if it finds NFS_FSDATA_BLOCKED_SHARED. The existing removal method is otherwise unchanged, and no directory uses the new one yet, so nothing changes.

---
 fs/nfs/dir.c           | 183 +++++++++++++++++++++++++++++++++++++++--
 fs/nfs/internal.h      |  19 +++--
 fs/nfs/nfstrace.h      |   2 +
 include/linux/nfs_fs.h |  11 ++-
 4 files changed, 196 insertions(+), 19 deletions(-)
fs/nfs/dir.c +177 -6
index d9ba3cb1d7..0b6de87030 100644
@@ -1919,12 +1919,12 @@ static int nfs_lookup_revalidate(struct inode *dir, const struct qstr *name,
 	return nfs_do_lookup_revalidate(dir, name, dentry, flags);
 }
 
-static void block_revalidate(struct dentry *dentry)
+static void __block_revalidate(struct dentry *dentry, void *sentinel)
 {
 	/* old devname - just in case */
 	kfree(dentry->d_fsdata);
 
-	dentry->d_fsdata = NFS_FSDATA_BLOCKED;
+	dentry->d_fsdata = sentinel;
 
 	/* Any new reference that could lead to an open
 	 * will either:
@@ -1933,14 +1933,13 @@ static void block_revalidate(struct dentry *dentry)
 	 *    after taking the reference.
 	 *
 	 * Holding this lock and invalidating ->d_seq *after* recording
-	 * NFS_FSDATA_BLOCKED ensures we cannot race with
-	 * __nfs_lookup_revalidate().
-	 * If __nfs_lookup_revalidate() doesn't see NFS_FSDATA_BLOCKED then:
+	 * @sentinel ensures we cannot race with __nfs_lookup_revalidate().
+	 * If __nfs_lookup_revalidate() doesn't see @sentinel then:
 	 * In the ref-walk case - d_lookup() will have incremented
 	 * d_count() before we check it.
 	 * In the RCU-walk case - ->d_seq must have been sampled before
 	 * we call write_seqcount_invalidate() below (because it was sampled
-	 * before we set NFS_FSDATA_BLOCKED) so d_count() will have been
+	 * before we set @sentinel) so d_count() will have been
 	 * incremented or the d_seq check will fail in legitimize_path()
 	 * (or both).
 	 */
@@ -1949,6 +1948,16 @@ static void block_revalidate(struct dentry *dentry)
 
 }
 
+static void block_revalidate(struct dentry *dentry)
+{
+	/*
+	 * The caller holds the parent's i_rwsem exclusive, and a shared
+	 * remover's sentinel does not outlive its shared hold of that lock.
+	 */
+	WARN_ON_ONCE(nfs_fsdata_blocked_shared(dentry->d_fsdata));
+	__block_revalidate(dentry, NFS_FSDATA_BLOCKED);
+}
+
 static void unblock_revalidate(struct dentry *dentry)
 {
 	store_release_wake_up(&dentry->d_fsdata, NULL);
@@ -2689,6 +2698,168 @@ int nfs_unlink(struct inode *dir, struct dentry *dentry)
 }
 EXPORT_SYMBOL_GPL(nfs_unlink);
 
+/*
+ * ->unlink_shared(): remove a file with the parent's i_rwsem held shared.
+ *
+ * The lock then excludes no lookup of this name, and no open of it but
+ * one that takes the parent exclusive.  What orders those behind the
+ * REMOVE is the dentry.  While it is hashed it is what every resolver of
+ * the name is handed, and NFS_FSDATA_BLOCKED_SHARED in ->d_fsdata makes
+ * each one that consults ->d_revalidate() after it is stored wait there
+ * until the removal is over: the REMOVE, and the VFS's report of it (see
+ * nfs_unlink_shared_done()).  That works only for a dentry in the one
+ * clean state tested below.  Anything else is handed back with
+ * UNLINK_NEED_EXCL and is done by nfs_unlink() with the parent held
+ * exclusive, as it always has been.  Nothing here silly-renames, and
+ * nothing here waits for another removal.
+ *
+ * An RCU-walk that consulted ->d_revalidate() before the store does not
+ * get past it: __block_revalidate() invalidates ->d_seq after the store,
+ * in the same ->d_lock section, so the walk fails its recheck and waits
+ * in ref-walk.  The one resolver that does get past, as it gets past the
+ * exclusive lock, is set out below.
+ *
+ * NFSv4 sets IOPF_ATOMIC_OPEN_CREATE_SHARED, so an O_CREAT open of the
+ * name takes the parent shared too, and the lock does not exclude it
+ * either.  While the dentry is hashed, such an open is handed it like any
+ * other resolver, and waits as they do.
+ *
+ * The sentinel is not cleared here.  nfs_unlink_shared_done() clears it, and
+ * the VFS calls that after any event for the removal is out, so that an open
+ * released by the clear cannot create the name and have its create event out
+ * before the delete event of the removal it waited for.
+ */
+int nfs_unlink_shared(struct inode *dir, struct dentry *dentry)
+{
+	int error;
+
+	dfprintk(VFS, "NFS: unlink_shared(%s/%llu, %pd)\n", dir->i_sb->s_id,
+		 dir->i_ino, dentry);
+
+	lockdep_assert_held_read(&dir->i_rwsem);
+	trace_nfs_unlink_shared_enter(dir, dentry);
+
+	/*
+	 * The anchor is keyed on the dcache name, and NFS installs no
+	 * ->d_hash or ->d_compare, so names are compared byte for byte: the
+	 * anchor assumes that the server keeps one object per byte string.
+	 * On a server for which "FOO" and "foo" are one object the client
+	 * can hold two independent hashed dentries, and blocking one of them
+	 * makes no resolver of the other wait.  A server that reports itself
+	 * case-insensitive, or as not preserving case, has SB_I_NAMES_COLLIDE
+	 * on its superblock (nfs_server_publish_name_caps()), and the VFS does
+	 * not call this method there; the test here hands back a removal whose
+	 * caller read the bit before it was set.  A server that makes one
+	 * object of other names that differ as byte strings, as Unicode
+	 * normalization does, is not detected, and a removal there is not
+	 * ordered against an open of another spelling; that is a limitation
+	 * of this method.
+	 */
+	if (READ_ONCE(dir->i_sb->s_iflags) & SB_I_NAMES_COLLIDE)
+		goto need_excl;
+
+	spin_lock(&dentry->d_lock);
+	/*
+	 * The clean state, read in the ->d_lock section the sentinel is
+	 * stored in, so that nothing can come between the two.
+	 *
+	 * A count of one is the interlock everything else rests on.  A second
+	 * reference either calls for a silly-rename, which ends in d_move()
+	 * and needs the parent exclusive, or belongs to a resolver that may
+	 * be past its ->d_revalidate() consult and would then unhash the
+	 * dentry without having seen the sentinel.  Every resolver that can
+	 * do that takes its reference before it consults, so with a count of
+	 * one here every resolver that consults from now on finds the
+	 * sentinel and waits.  The readdir guard in nfs_prime_dcache()
+	 * depends on this test and the store staying in one ->d_lock
+	 * section.
+	 *
+	 * One resolver escapes, as it escapes the exclusive lock: an open by
+	 * file handle, whose reference comes from d_obtain_alias() with no
+	 * ->d_revalidate().  It may go on to fail its open, reaching
+	 * nfs_d_drop_unless_anchored(), to open the file that the REMOVE then
+	 * deletes, or to get -ESTALE from the server.  An RCU-walk that
+	 * consulted ->d_revalidate() before the store does not escape; see
+	 * above.
+	 *
+	 * A victim that is no longer hashed and positive is no anchor.
+	 * Nothing between the lookup and here re-tests either, and with the
+	 * parent shared a failed ->d_revalidate() in another lookup, or
+	 * another remover's d_delete(), may have unhashed it since.  That is
+	 * not -ENOENT: a name invalidated locally may still exist on the
+	 * server.  A pending silly-delete on the dentry, or a block already
+	 * present, is for the exclusive pass to answer as well, and both
+	 * tests have to stay ahead of the store: __block_revalidate()
+	 * kfree()s ->d_fsdata, which while DCACHE_NFSFS_RENAMED is set is
+	 * the queued struct nfs_unlinkdata, and a store over another
+	 * sentinel would end that block early.
+	 */
+	if (d_count(dentry) > 1 ||
+	    (dentry->d_flags & DCACHE_NFSFS_RENAMED) ||
+	    nfs_dentry_is_blocked(dentry) ||
+	    d_unhashed(dentry) || d_really_is_negative(dentry)) {
+		spin_unlock(&dentry->d_lock);
+		goto need_excl;
+	}
+	__block_revalidate(dentry, NFS_FSDATA_BLOCKED_SHARED);
+	spin_unlock(&dentry->d_lock);
+
+	trace_nfs_unlink_enter(dir, dentry);
+	/*
+	 * The REMOVE of nfs_safe_remove(), less its silly-renamed case, which
+	 * the tests above hand back; the protocol's ->remove() drops the link
+	 * count itself.  It is copied and not called so that the directory's
+	 * removal sequence moves as soon as the server has answered, whatever
+	 * the answer, and before anything here can unhash the anchor: on
+	 * -ENOENT, nfs_dentry_handle_enoent() does.  See
+	 * nfs_dir_shared_removal_since().
+	 */
+	trace_nfs_remove_enter(dir, dentry);
+	nfs_dir_start_shared_removal(dir);
+	error = NFS_PROTO(dir)->remove(dir, dentry);
+	nfs_dir_end_shared_removal(dir);
+	/* Nothing may unhash an anchor while its REMOVE is in flight */
+	WARN_ON_ONCE(!error && d_unhashed(dentry));
+	if (error == -ENOENT)
+		nfs_dentry_handle_enoent(dentry);
+	trace_nfs_remove_exit(dir, dentry, error);
+
+	nfs_dentry_remove_handle_error(dir, dentry, error);
+	trace_nfs_unlink_exit(dir, dentry, error);
+	return error;
+
+need_excl:
+	trace_nfs_unlink_need_excl(dir, dentry);
+	return UNLINK_NEED_EXCL;
+}
+EXPORT_SYMBOL_GPL(nfs_unlink_shared);
+
+/*
+ * ->unlink_shared_done(): end the exclusion nfs_unlink_shared() installed.
+ *
+ * The VFS calls this for a call of nfs_unlink_shared() that did not hand the
+ * removal back, with the parent still held shared and the event for the
+ * removal, if there was one, already out.  Clearing the sentinel here rather
+ * than at the end of nfs_unlink_shared() is what keeps the notifications for
+ * the name in order: an O_CREAT open released by the clear would otherwise be
+ * able to create the name and have its create event out first.
+ *
+ * Every such call stored the sentinel, both of the tests that hand a removal
+ * back being made before the store, so there is nothing to test for here.
+ * Nor can anything have replaced it: nfs_unlink_shared() anchors only on a
+ * dentry with no reference but the caller's, which the caller still holds, so
+ * no second remover can anchor on it and nfs_d_release() cannot run;
+ * nfs_call_unlink() skips a dentry that is blocked; and every other writer of
+ * the field needs either the parent held exclusive or DCACHE_NFSFS_RENAMED,
+ * which is one of the cases handed back above.
+ */
+void nfs_unlink_shared_done(struct inode *dir, struct dentry *dentry)
+{
+	lockdep_assert_held_read(&dir->i_rwsem);
+	unblock_revalidate(dentry);
+}
+EXPORT_SYMBOL_GPL(nfs_unlink_shared_done);
+
 /*
  * To create a symbolic link, most file systems instantiate a new inode,
  * add a page to it containing the path, then write it out to the disk
fs/nfs/internal.h +12 -7
index 9cd8e5e808..2600ae7865 100644
@@ -49,7 +49,7 @@ static inline bool nfs_lookup_is_soft_revalidate(const struct dentry *dentry)
  * removal of the dentry's name is in flight: the first when the remover
  * holds the parent's i_rwsem exclusive, the second when it holds it shared,
  * and the second until the VFS ends the removal, after any delete event for
- * it (see the client's ->unlink_shared_done()).
+ * it (see nfs_unlink_shared_done()).
  * ->d_revalidate() waits for either to clear.  The two differ in what the
  * dentry is to the removal.
  *
@@ -73,12 +73,15 @@ static inline bool nfs_lookup_is_soft_revalidate(const struct dentry *dentry)
  * ->d_revalidate(), has to leave an anchor hashed or wait for its sentinel
  * to clear.
  *
- * The shared sentinel is stored and cleared within one shared hold of the
- * parent, so it is never present while the parent is held exclusive.  That
- * is why the two tests made with the parent exclusive, the WARN_ON()s in
- * nfs_unlink() and nfs_rename(), still compare against NFS_FSDATA_BLOCKED
- * alone.  They are the only bare compares against a sentinel; every other
- * test uses the helpers below.
+ * The shared sentinel is stored in nfs_unlink_shared() and cleared in
+ * nfs_unlink_shared_done(), which the VFS calls while it still holds the
+ * parent shared, so it is stored and cleared within one shared hold of the
+ * parent and is never present while the parent is held exclusive.  That
+ * is why the WARN_ON()s in nfs_unlink() and nfs_rename(), made with the
+ * parent exclusive, still compare against NFS_FSDATA_BLOCKED alone, and
+ * why block_revalidate(), which both call, warns if it finds
+ * NFS_FSDATA_BLOCKED_SHARED.  Those WARN_ON()s are the only bare compares
+ * against a sentinel; every other test uses the helpers below.
  */
 static inline bool nfs_fsdata_blocked(const void *fsdata)
 {
@@ -611,6 +614,8 @@ struct dentry *nfs_mkdir(const struct mnt_idmap *, struct inode *, struct dentry
 			 umode_t);
 int nfs_rmdir(struct inode *, struct dentry *);
 int nfs_unlink(struct inode *, struct dentry *);
+int nfs_unlink_shared(struct inode *dir, struct dentry *dentry);
+void nfs_unlink_shared_done(struct inode *dir, struct dentry *dentry);
 int nfs_symlink(const struct mnt_idmap *, struct inode *, struct dentry *,
 		const char *);
 int nfs_link(struct dentry *, struct inode *, struct dentry *);
fs/nfs/nfstrace.h +2 -0
index a32c76df72..99393ebc7e 100644
@@ -748,6 +748,8 @@ DEFINE_NFS_DIRECTORY_EVENT(nfs_remove_enter);
 DEFINE_NFS_DIRECTORY_EVENT_DONE(nfs_remove_exit);
 DEFINE_NFS_DIRECTORY_EVENT(nfs_unlink_enter);
 DEFINE_NFS_DIRECTORY_EVENT_DONE(nfs_unlink_exit);
+DEFINE_NFS_DIRECTORY_EVENT(nfs_unlink_shared_enter);
+DEFINE_NFS_DIRECTORY_EVENT(nfs_unlink_need_excl);
 DEFINE_NFS_DIRECTORY_EVENT(nfs_symlink_enter);
 DEFINE_NFS_DIRECTORY_EVENT_DONE(nfs_symlink_exit);
 
include/linux/nfs_fs.h +5 -6
index 3e86449485..7ccdc5b867 100644
@@ -697,12 +697,11 @@ static inline bool nfs_ooo_test(struct nfs_inode *nfsi)
  *  - NFS_FSDATA_BLOCKED, while a REMOVE of the name, or a RENAME onto it,
  *    is in flight with the parent's i_rwsem held exclusive.  It outlives
  *    that hold only when a rename is killed, until its RENAME completes;
- *  - NFS_FSDATA_BLOCKED_SHARED, from the store in the client's
- *    ->unlink_shared(), with the parent's i_rwsem held shared, until its
- *    ->unlink_shared_done(), which the VFS calls after any delete event
- *    for the removal, whether or not it succeeded, and before it drops
- *    that hold.  The dentry may be negative, or positive and unhashed,
- *    by then.
+ *  - NFS_FSDATA_BLOCKED_SHARED, from the store in nfs_unlink_shared(),
+ *    with the parent's i_rwsem held shared, until nfs_unlink_shared_done(),
+ *    which the VFS calls after any delete event for the removal, whether
+ *    or not it succeeded, and before it drops that hold.  The dentry may
+ *    be negative, or positive and unhashed, by then.
  * Both sentinels are stored under ->d_lock and cleared by
  * unblock_revalidate(), and ->d_revalidate() waits while either is set.
  * fs/nfs/internal.h says what else has to respect them.
Signature · 1 line
2.43.0
#28 lore raw

RFC PATCH 11/12 nfs: look a name up again once its removal has unhashed it

In reply to Jonathan Flynn

An open or lookup of a name can wait for a removal of the same name made with the directory locked shared, and is then ordered after it. When that removal succeeds while the waiter still holds the name's cache entry, the entry is only taken out of the cache, not emptied, so the waiter is left holding an entry for a name that no longer exists. Revalidation can then accept it: an open without O_EXCL is sent to the server for the removed file, and if the client holds a delegation for the directory, an exclusive create of the name fails with "file exists".

When NFSv4's revalidation has waited for such a removal and finds the entry out of the cache once the wait ends, have it answer that the entry is invalid, so that the name is looked up again; __nfs_lookup_revalidate() now reports whether the mark it waited for was the shared one. Without such a wait, an entry out of the cache goes through the usual checks, as before. Its holder may be unable to look the name up again: overlayfs revalidates the entries of its lower layers itself, and an answer of "invalid" for one that a transient error took out of the cache would leave the overlay reporting it stale until it dropped its own entry. A lookup that took the entry while the removal was in flight but finds the mark already clear is not covered either; it overlapped the removal, so the old entry is still an answer it may be given.

This relies on the VFS taking the entry out of the cache before it calls ->unlink_shared_done(), which clears the mark, and on the wait reading the mark with acquire ordering, which pairs with the release in the
clear: a lookup that finds the mark clear, whether it slept or not, then also sees the entry out of the cache. A removal made with the directory locked exclusive, and a rename onto the name, can clear the mark before the entry is taken out of the cache; say so at the wait.

---
 fs/nfs/dir.c | 50 +++++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 43 insertions(+), 7 deletions(-)
fs/nfs/dir.c +43 -7
index 0b6de87030..1f255001a1 100644
@@ -1889,6 +1889,11 @@ nfs_do_lookup_revalidate(struct inode *dir, const struct qstr *name,
 	return nfs_lookup_revalidate_done(dir, dentry, inode, error);
 }
 
+/*
+ * Answers -ECHILD under LOOKUP_RCU while a removal of the name is in
+ * flight.  Otherwise waits for any such removal to end, and answers 1 if
+ * the one it found was made with the parent held shared, else 0.
+ */
 static int
 __nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
 {
@@ -1898,15 +1903,28 @@ __nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
 			return -ECHILD;
 	} else {
 		void **fsdata = &dentry->d_fsdata;
+		void *mark;
 
-		/* Wait for unlink to complete - see unblock_revalidate().
-		 * smp_load_acquire() ensures ->d_fsdata is read after
-		 * ->d_seq was read, matching block_revalidate() which
-		 * sets ->d_fsdata before ->d_seq.
+		/*
+		 * Wait for unlink to complete - see unblock_revalidate().  One
+		 * load, as there are two values to test.  smp_load_acquire()
+		 * ensures ->d_fsdata is read after ->d_seq was read, matching
+		 * __block_revalidate(), which sets ->d_fsdata before ->d_seq.
+		 * The acquire in the wait pairs with the release in
+		 * unblock_revalidate(): a waiter that finds the mark clear
+		 * sees what the remover did before clearing it.  For a removal
+		 * made with the parent held shared, that includes the unhash of
+		 * a dentry it took away, as the VFS calls d_delete() before
+		 * ->unlink_shared_done(); nfs_unlink() and nfs_rename() may
+		 * clear the mark first and unhash after.
 		 */
+		mark = smp_load_acquire(fsdata);
+		if (!nfs_fsdata_blocked(mark))
+			return 0;
 		wait_var_event(fsdata,
-			       /* one load: there are two values to test */
+			       /* acquire: pairs with unblock_revalidate() */
 			       !nfs_fsdata_blocked(smp_load_acquire(fsdata)));
+		return nfs_fsdata_blocked_shared(mark);
 	}
 	return 0;
 }
@@ -1914,7 +1932,7 @@ __nfs_lookup_revalidate(struct dentry *dentry, unsigned int flags)
 static int nfs_lookup_revalidate(struct inode *dir, const struct qstr *name,
 				 struct dentry *dentry, unsigned int flags)
 {
-	if (__nfs_lookup_revalidate(dentry, flags))
+	if (__nfs_lookup_revalidate(dentry, flags) < 0)
 		return -ECHILD;
 	return nfs_do_lookup_revalidate(dir, name, dentry, flags);
 }
@@ -2329,10 +2347,28 @@ nfs4_lookup_revalidate(struct inode *dir, const struct qstr *name,
 		       struct dentry *dentry, unsigned int flags)
 {
 	struct inode *inode;
+	int ret;
 
-	if (__nfs_lookup_revalidate(dentry, flags))
+	ret = __nfs_lookup_revalidate(dentry, flags);
+	if (ret < 0)
 		return -ECHILD;
 
+	/*
+	 * A removal made with the parent held shared that succeeded while
+	 * this lookup waited for it, holding the dentry, has left the dentry
+	 * positive but unhashed: d_delete() empties a dentry only for its last
+	 * user.  The dentry no longer stands for its name, so have the caller
+	 * look the name up again; the checks below could accept it, since
+	 * with a directory delegation the removal stamped it delegated.  Only
+	 * ref-walk waits, so this never answers 0 under LOOKUP_RCU.  A dentry
+	 * found unhashed without such a wait is left to the checks below, as
+	 * before: its holder may be unable to look the name up again, as
+	 * overlayfs is for the dentries of its lower layers, which it
+	 * revalidates itself.
+	 */
+	if (ret && d_unhashed(dentry))
+		return 0;
+
 	trace_nfs_lookup_revalidate_enter(dir, dentry, flags);
 
 	if (!(flags & LOOKUP_OPEN) || (flags & LOOKUP_DIRECTORY))
Signature · 1 line
2.43.0
#29 lore raw

RFC PATCH 12/12 nfs: remove files with the parent directory locked shared on NFSv4

In reply to Jonathan Flynn

Let removals of different files in one NFSv4 directory proceed at the same time, instead of queuing one behind another on the directory's lock. The server orders removals of different names. The client orders a removal against lookups and opens of the same name through its cached entry for that name, and against listings through that entry and a count of such removals kept per directory, as set out in the changes before this one. A removal it cannot order that way is done with the directory locked exclusive, as before. On a server that reports itself case-insensitive or not case-preserving, every removal is done that way from the start. A server that treats names differing in other ways as one, as Unicode normalization does, is not detected, and there a removal is not ordered against a lookup or open of another spelling.

This covers every NFSv4 minor version, NFSv4.0 included: nothing here depends on sessions. NFSv2 and NFSv3 are unchanged.

---
 fs/nfs/nfs4proc.c | 2 ++
 1 file changed, 2 insertions(+)
fs/nfs/nfs4proc.c +2 -0
index fbf9e97815..0acc03dfe6 100644
@@ -10860,6 +10860,8 @@ static const struct inode_operations nfs4_dir_inode_operations = {
 	.atomic_open	= nfs_atomic_open,
 	.link		= nfs_link,
 	.unlink		= nfs_unlink,
+	.unlink_shared	= nfs_unlink_shared,
+	.unlink_shared_done = nfs_unlink_shared_done,
 	.symlink	= nfs_symlink,
 	.mkdir		= nfs_mkdir,
 	.rmdir		= nfs_rmdir,
Signature · 1 line
2.43.0
author
#30 lore raw

Re: [PATCH RFC 00/12] vfs, nfs: concurrent create and unlink in one directory

In reply to Jonathan Flynn
Quoted 10 lines · Jonathan Flynn

Hi Neil,

Thank you for this series; it is what makes these patches possible. I had them on your v3 and have rebased them onto v4. They extend it so that processes on one NFSv4 client can create and remove files in one directory concurrently.

  operations per second   parent exclusive   parent shared   ratio
  creates                            2,616          29,939   11.4x
  removals                           2,157          32,360   15.0x

Thanks for the stats. This confirms that this a useful project to continue on :-)

But I think you are racing ahead and that we do this "properly" without per-fs flags etc.

Reflecting on me current plans, I see that rmdir and rename require the most work. It would make sense (I think) to delay those and focus on create/unlink which are relatively straight-forward.

Once all the current prep work lands I want to list d_alloc_parallel() out of i_rwsem and then add dentry locking. Then we can move i_rwsem locking into ->atomic_open and ->create and ->lookup and ->unlink, and then you can remove that locking for NFS.

I think trying to take a short cut would slow the whole process down. The 'create' changes you made aren't too bad, but the unlink work is too complex I think.

But I'm really happy that you've written this proof-of-concept.

Thanks,
NeilBrown

Quoted 140 lines

One client, 96 processes in one directory, each creating files (open O_CREAT, a small write, close) for a set time, then removing them all; NFSv4.2 to a pNFS metadata server that is not knfsd; your v4, the 7.4 VFS changes it builds on, the three silly-delete fixes and this series on a 7.3-based kernel, among other patches. Each row switched only its own path, by a test-only module parameter not in this series, with the other path on; one run each. The creates row comes from 300 s of creates. The removals row comes from 120 s of creates, and each of its runs removed about 3.7 million files; the removal rates vary with that number, so it is given. With the parent held exclusive, operations go one server round trip at a time. 2/12 quotes an earlier measurement, on a 7.1.13-based kernel.

How it works. 2/12 lets a filesystem have the parent locked shared for O_CREAT (a flag in a new ->iop_flags field), and 6/12 for unlink(2) (->unlink_shared() and ->unlink_shared_done()). The dentry then excludes the name: for a create, its in-lookup state, all nfs_atomic_open() needs since your 3/9; for a removal, an NFS mark that lookups, opens and creates of the name wait on until ->unlink_shared_done(), which the VFS calls after the fsnotify delete event, if any. What NFS cannot order that way, such as an open file, it hands back to ->unlink() under the exclusive lock; where the server reports itself case-insensitive or not case-preserving, NFS sets SB_I_NAMES_COLLIDE (3/12) and both keep the exclusive lock. Both paths call d_alloc_parallel() under the shared lock, as lookup does. When your directory-locking changes lift d_alloc_parallel() above i_rwsem, these calls have to move with lookup's; the exclusion does not change, and the opt-ins go once the VFS stops taking the parent lock (2/12, 6/12).

Patch flow:

  prereq   1  store re-read server capabilities in one step, for 3
  create   2  VFS opt-in to take the parent lock shared for O_CREAT
           3  NFS sets SB_I_NAMES_COLLIDE where names can collide
           4  NFSv4 directories opt in for O_CREAT
  remove   5  factor vfs_unlink() into a helper, no functional change
           6  VFS opt-in: ->unlink_shared(), ->unlink_shared_done()
           7  a second ->d_fsdata mark, for removals under a shared lock
           8  keep a dentry carrying that mark hashed
           9  no new dentries from a listing that a removal overlapped
          10  the removal method, handing back what it cannot order
          11  look a name up again once its removal has unhashed it
          12  NFSv4 directories opt in for unlink

Three fixes for the silly-delete hand-off, which your 2/9 makes reachable, are posted separately, in reply to 2/9.

Tested on the same kernel over NFSv4.2, with the new paths on and off:
removal races (with listings, and with tasks killed); O_EXCL creates racing unlink, with a kernel-side check that no revalidation trusted a removed entry; inotify event order; two clients; and an overlayfs mount whose lower file another client renamed away and back. All passed, with no kernel warning or hung task, except the two-client test's check that nothing was left behind: on this kernel and on one with an earlier revision of this series, it found one silly-renamed file in three of four runs, with the new paths off as well as on, so they are not the cause. Each time, the file left behind was not the one that had been
silly-renamed: the silly-rename's RENAME, which goes by name, had moved another file of that name onto the hidden name. A PROVE_LOCKING and KASAN build ran the removal, killed-task and O_EXCL tests with no report. A case-insensitive server, where two spellings of a name never made two files, was tested on that earlier revision only; that code has not changed since. Not run: fstests, knfsd as the server, NFSv4.0 or 4.1, directory delegations (the server grants none), CONFIG_DEBUG_VFS, a weakly ordered CPU.

One question: are the opt-ins in 2/12 and 6/12 acceptable as interim interfaces until the directory-locking changes land?

The series applies to 83f32c773255 in Linus's tree on top of your v4 and the three silly-delete fixes. fs/ compiles there without warnings at every commit, with and without CONFIG_DEBUG_VFS and lockdep; I have run it only on the 7.3-based kernel above.

Tools: these patches, their changelogs, the race tests and this letter were written with Claude Code, using Anthropic's Claude Opus 5 and Claude Opus 5.5 models, at my direction over many sessions: I chose among the designs it proposed and directed each revision. It found, by reading the code, the bug that 1/12 fixes: while the client reads a server's capabilities again, a capability the server still offers can look missing. The three silly-delete fixes, posted separately, say which of their problems it found and how they were tested.

Thanks,
Jonathan

Jonathan Flynn (12):
nfs: update a server's capabilities in one step
vfs: allow the parent lock to be shared for O_CREAT
nfs: tell the VFS when two names can be one entry on the server
nfs: concurrent O_CREAT in one NFSv4 directory
vfs: factor file removal into a helper, no functional change
vfs: let a filesystem remove files with the parent directory locked
shared
nfs: add a second mark for a removal made with the parent locked
shared
nfs: keep the dentry of a shared-parent removal hashed
nfs: do not cache a name from a listing that a removal overlapped
nfs: add the removal method for a parent directory locked shared
nfs: look a name up again once its removal has unhashed it
nfs: remove files with the parent directory locked shared on NFSv4

 .../filesystems/directory-locking.rst         |  60 +++
 Documentation/filesystems/locking.rst         | 259 ++++++++++++-
 Documentation/filesystems/porting.rst         |  35 ++
 Documentation/filesystems/vfs.rst             |  25 ++
 fs/namei.c                                    | 360 +++++++++++++++++-
 fs/nfs/client.c                               |   1 +
 fs/nfs/dir.c                                  | 300 ++++++++++++++-
 fs/nfs/inode.c                                |   2 +
 fs/nfs/internal.h                             | 211 ++++++++++
 fs/nfs/nfs4file.c                             |   9 +-
 fs/nfs/nfs4proc.c                             |  35 +-
 fs/nfs/nfstrace.h                             |   2 +
 fs/nfs/super.c                                |   2 +
 fs/nfs/unlink.c                               |  16 +-
 include/linux/fs.h                            |  72 ++++
 include/linux/fs/super_types.h                |   1 +
 include/linux/nfs_fs.h                        |  28 ++
 17 files changed, 1361 insertions(+), 57 deletions(-)

base-commit: 83f32c773255720a661aa45d83e36278135f23f5
prerequisite-patch-id: 3405b4d6ab8b0bf24ba63a898083d617deec4f24
prerequisite-patch-id: 096657d6d80d7ca533ccb574d2af65611ede4af2
prerequisite-patch-id: 1a2319c14739918aef86116647fea28ae85ad4df
prerequisite-patch-id: 725cb18c3936d50141ef27dafc159bf50b64a5bd
prerequisite-patch-id: b39cdd352b97e2cd247311fd5db620dbff227bd7
prerequisite-patch-id: f9f3f0e945cadf96113d4ac9ab8f7b0c207af4e5
prerequisite-patch-id: 4c09a15390bb556d79bea1ee733f52a58bec80ef
prerequisite-patch-id: 7c026717a97b2c86a169539822f5d14650f68f8a
prerequisite-patch-id: a702d54495d0f3d7f88b82411d884dcf5aacf9a0
prerequisite-patch-id: a7e7263e8916612f3e4b767946b5d9259029f50e
prerequisite-patch-id: a8e5414df9d9912dcdf9bb1dbb2811ce326a1e1f
prerequisite-patch-id: e8050b998d5790f3bb4311bc65011735ed7d8b2f

Signature · 1 line
2.43.0