Skip to contentSkip to conversation

smb: client: fix data loss in writeback

PATCH New Paulo Alcantara 1 participant 20 messages Nov 7

Subsystems (4)
lore
Share & tools
lore

Paulo Alcantara

author maintainer
#0 lore raw

v9 cover smb: client: fix data loss in writeback

Hi,

A task killed while close() flushes its dirty pages gets its writes refused by __smb_send_rqst() (fatal signal pending), and netfs then ends writeback with the folios clean. The data never reaches the server and no error reaches the application: stat() still reports the cached size while the file on the server is short. It was reported against a RHEL 9 kernel, where the same trigger makes stat() fail with -EIO after a rename(2), and it reproduces on mainline as this silent lost write.

Any other failure that is only transient hits the same wall: since the move to netfslib, a failed upload ends writeback with the folios clean, so a reconnect, a lost handle, an interrupted wait or an -ENOMEM silently drops the data.

This series makes writeback retry instead of giving up:

- a dying task's writeback is issued from a workqueue, and the close() and fsync() waits for it are killable
- writeback is retried with exponential backoff on replayable errors, interrupts, -ENOMEM and on losing the connection, share or handle, and handle reopens are retried the same way
- umount -f aborts the retries, reconnect waits and replay loops of the mount's requests, and writeback no longer blocks in the reconnect or credit waits so the unmount's own sync can't hang there

On hard mounts writeback is retried until the server comes back or umount -f. On soft mounts it gives up after max(3, retrans) * echo_interval from the first failure of each write (3 minutes, and about 6 minutes from the outage since that is when cifs declares the server dead), recording -EIO. Reads and direct writes still follow the hard and retrans mount options.

Patch 1 is independent: writeback could pick a handle opened with O_DIRECT, and Windows rejects unaligned writes on those with STATUS_INVALID_PARAMETER, dropping 1.2% of the writes in xfstests generic/051. It is first so it can be backported on its own.

Patches 2-4 are netfs fixes the cifs patches depend on: patch 2 is Ivan's ([email protected]), keeping the prepare_write() errno across a reissue; patch 3 does the same for prepare_read() when read retries are abandoned, and patch 4 keeps such a read from hanging.

Not covered by this series:

- after a umount -f that fails with -EBUSY, reads and writes retrying (e.g. across a reconnect) give up while a remount, freeze or new mount of the same superblock waits on s_umount
- if every writable handle of an inode is O_DIRECT (e.g. mmap of an O_DIRECT fd), its unaligned writeback still fails, with the error reported

Thanks,
Paulo

Changes since v8:
- don't let a multiuser tlink being built make umount -f treat a tcon another mount uses as unshared
- stop a handle reopen started before umount -f from entering a reconnect wait afterwards
- durable reopens: fall back to a fresh open with the original access, don't take the -EACCES and -ENOENT fallbacks while a create is still pending, and don't replay a create the server answered nor leak its error response
- writeback reopens: the other subrequests wait for the reopen and share its outcome, each backing off on its own, and fail right away once reopening failed for good

Changes since v7:
- count a mount's references on a tcon while its tlink is in the superblock's tree, and decide whether umount -f may abort a tcon under the tree lock, so pruning or building a tlink can't skew it; wake the waiters when a tcon loses its last mount
- durable reopens: keep the access fallbacks of the create being replayed, and treat only a server's answer as settling it
- writeback reopens: serialize them per request, sharing a permanent failure, never block on fh_mutex, and keep the retry state per span of re-sliced subrequests

Changes since v6:
- don't spend a mount's retries on direct writes cut short by a reconnect, which are retried regardless, and new patch doing the same for reads
- durable reopens: replay the last create, reconnects included, with its access, only if it got no answer, tracking that across SMB2_open()'s own retries and leaving it alone after an interrupted attempt
- split pieces of a retried write take the retry state of the whole pass, only one subrequest per request retries a reopen per pass, the flusher no longer takes fh_mutex, and a dropped connection is caught by the compound credit wait too
- keep a tcon dying when mounts sharing it are force-unmounted concurrently, and never reuse a tcon that no mount references
- point the close patch's Fixes: at the commit that made it wait

Changes since v5:
- new netfs patch so an abandoned read retry can't hang the read
- durable reopens: never fall back to a reconnect once the durable handle is gone, and replay the fresh open only if it was built and not interrupted
- back off once per retry pass instead of per subrequest, let pieces split off by a retry keep their retry state, and fail the remaining subrequests once a writeback reopen gives up
- check a write's credits for a reconnect before sending, as for reads
- make the writeback reopen's own credit wait fail fast too
- pin the mount's tlinks during umount -f so pruning can't race it, and treat tcons no mount references as dying, so their leftover closes and tree disconnect don't hang

Changes since v4:
- don't let the flusher block the unmount under s_umount in a writeback reopen or credit wait, nor a sync(2) racing umount -f
- keep the forced-unmount teardown from reconnecting and replaying until the tree disconnects are done, wake per-user sessions too, and keep doing so on tcons no mount uses any more
- replay a durable reopen only when its fresh open had an unknown outcome, tracked per open file, and stop retrying a failed durable reconnect as a fresh open with a stale GUID
- don't let umount -f abort reconnect waits on a tcon another mount uses
- retry reads that couldn't be sent due to a stale handle or credits
- resend direct writes cut short by a reconnect as replays, or fail them with -EIO under umount -f
- reopen writeback handles from the worker only once per retry, so a dead mount can't tie it up for the other mounts
- reopen persistent handles from the reconnect worker without waiting, rescheduling it only after transient failures

Changes since v3:
- new patch to stop a mount's tcons from reconnecting and replaying for the duration of the forced-unmount teardown, so a reconnect wait or a per-PDU replay loop (a close work item in particular) entered after the unmount began can't hang cifs_kill_sb(); it also covers tcons shared with another mount for those moments, and fails the reconnect worker fast so it can't pin and leak the tcon, session, server and cifsd thread

Changes since v2:
- stop writeback started after a forced unmount (e.g. the unmount's own sync) from retrying forever on a hard mount
- fail writeback sends and reopens fast at every point in smb2_reconnect(), not only the first, so a reconnect that starts midway can't still block the unmount
- abort a write's first retry under umount -f even before netfs bumps its retry count
- keep a dying task from looping in the reopen retry, and keep a read from looping on a forced -EAGAIN retry
- track the bad handle (-EBADF) across out-of-order subrequest failures, and recheck the handle after the backoff sleep

Changes since v1:
- new patch to not write back through O_DIRECT handles (data loss of its own, found by generic/051); put first for an independent backport
- dropped the netfs patch that deferred write retries until all subrequests were queued (could deadlock writeback under memory pressure); keep the prepare_read() errno on abandoned read retries instead
- issue writeback sends and handle reopens without waiting for a reconnect, and make umount -f also stop the credit wait, cover multiuser per-user tcons, and not be gated by tc_count, so the unmount's own sync can't hang
- make the reopen retry reconnect-aware and bounded, don't replay reopens inside SMB2_open(), track the bad handle (-EBADF) per request, and fix a retried read failing with -EAGAIN and a dying-task writeback looping on a reopen that gave up
- record -EIO (not a transient errno) when writeback finally gives up

Iván Ezequiel Rodriguez (1):
netfs: preserve prepare_write errno on reissue

Paulo Alcantara (18):
smb: client: don't write back through O_DIRECT handles
netfs: keep the prepare_read errno when abandoning read retries
netfs: don't hang a read whose retry is abandoned
smb: client: let umount -f abort retried reads and writes
smb: client: don't give up writeback on the first replayable error
smb: client: don't retry failed writes forever regardless of mount
options
smb: client: don't spend read retries on reads cut short by a
reconnect
smb: client: don't block dying tasks waiting for writeback on close
smb: client: issue writes from a worker if the task is dying
smb: client: don't fail writeback preparation if the task is dying
smb: client: retry writeback on interrupts and allocation failures
smb: client: don't block dying tasks waiting for writeback on fsync
smb: client: retry writes that couldn't be issued due to a reconnect
smb: client: retry writeback after losing the connection, share or
handle
smb: client: let umount -f stop waiting for reconnects on hard mounts
smb: client: don't replay handle reopens inside SMB2_open()
smb: client: fail writeback sends and reopens fast when the server is
gone
smb: client: stop reconnecting and replaying during a forced unmount

 fs/netfs/read_retry.c      |  17 +-
 fs/netfs/write_issue.c     |   4 +-
 fs/smb/client/cifs_fs_sb.h |   2 +
 fs/smb/client/cifsfs.c     | 183 +++++++++--
 fs/smb/client/cifsglob.h   |  50 ++-
 fs/smb/client/cifsproto.h  |  12 +-
 fs/smb/client/cifssmb.c    |  15 +-
 fs/smb/client/connect.c    |  75 ++++-
 fs/smb/client/file.c       | 649 ++++++++++++++++++++++++++++++++++---
 fs/smb/client/misc.c       |  22 +-
 fs/smb/client/smb2file.c   |  18 +-
 fs/smb/client/smb2ops.c    |  22 +-
 fs/smb/client/smb2pdu.c    | 155 ++++++---
 fs/smb/client/smb2proto.h  |   9 +
 fs/smb/client/transport.c  |  22 +-
 15 files changed, 1081 insertions(+), 174 deletions(-)
Signature · 1 line
2.56.0
author maintainer
#1 lore raw

PATCH v9 1/19 smb: client: don't write back through O_DIRECT handles

Writeback uses the first writable handle of the inode, which may have been opened with O_DIRECT. Such handles are opened with FILE_NO_INTERMEDIATE_BUFFERING, for which Windows rejects any unaligned I/O with STATUS_INVALID_PARAMETER. Writeback of partly dirty pages and of the unaligned tail of a file through one of them fails, so netfs ends it with the folios clean and the data never reaches the server.

xfstests generic/051, where fsstress mixes both kinds of opens, loses about 1% of its writes this way:

smb3_write_err: ... offset=0xde90d7 len=0xbd0b rc=-22

All the rejected writes in a network capture were unaligned writes on a no-buffering handle; none of the aligned ones, and none of the unaligned ones on regular handles, were.

Prefer a handle that was not opened with O_DIRECT, and use one that was only if there is no other.

Fixes 1013e760d10e ("SMB3: Don't ignore O_SYNC/O_DSYNC and O_DIRECT flags")
---
 fs/smb/client/cifsglob.h |  1 +
 fs/smb/client/file.c     | 15 ++++++++++++---
 2 files changed, 13 insertions(+), 3 deletions(-)
fs/smb/client/cifsglob.h +1 -0
index d3ca688b6aba..dbf980fcf05b 100644
@@ -1891,6 +1891,7 @@ enum cifs_find_flags {
 	FIND_WITH_DELETE	= (1U << 1),
 	FIND_NO_PENDING_DELETE	= (1U << 2),
 	FIND_OPEN_FLAGS		= (1U << 3),
+	FIND_NO_DIRECT		= (1U << 4),
 };
 
 #define   MID_FREE 0
fs/smb/client/file.c +12 -3
index 0767eb5f4687..aa2d09dac44c 100644
@@ -255,9 +255,15 @@ static void cifs_begin_writeback(struct netfs_io_request *wreq)
 	struct cifs_io_request *req = container_of(wreq, struct cifs_io_request, rreq);
 	int ret;
 
-	ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY, &req->cfile);
+	ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_NO_DIRECT,
+				     &req->cfile);
 	if (ret) {
-		cifs_dbg(VFS, "No writable handle in writepages ret=%d\n", ret);
+		ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY,
+					     &req->cfile);
+	}
+	if (ret) {
+		cifs_dbg(VFS, "%s: couldn't find writable handle: %d\n",
+			 __func__, ret);
 		return;
 	}
 
@@ -2722,7 +2728,7 @@ int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
 	}
 
 	if (test_bit(CIFS_INO_TMPFILE, &cifs_inode->flags))
-		find_flags = FIND_ANY;
+		find_flags &= FIND_NO_DIRECT;
 
 	cifs_sb = CIFS_SB(cifs_inode);
 
@@ -2752,6 +2758,9 @@ int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
 		    !open_flags_match(cifs_inode, open_flags,
 				      open_file->f_flags))
 			continue;
+		if ((find_flags & FIND_NO_DIRECT) &&
+		    (open_file->f_flags & O_DIRECT))
+			continue;
 		if (OPEN_FMODE(open_file->f_flags) & FMODE_WRITE) {
 			if (!open_file->invalidHandle) {
 				/* found a good writable file */
Signature · 1 line
2.56.0
author maintainer
#2 lore raw

PATCH v9 2/19 netfs: preserve prepare_write errno on reissue

In reply to Paulo Alcantara

From: Iván Ezequiel Rodriguez <[email protected]>

prepare_write() may call netfs_prepare_write_failed() (FAILED + errno) before write_retry calls netfs_reissue_write(). Clearing subreq->error to 0 for a clean I/O reissue (82e8885bd763) then makes netfs_do_issue_write() terminate with 0. The collector copies front->error into stream->error and mapping_set_error(), which ignores 0, so writeback failure is silent.

Skip clearing error when NETFS_SREQ_FAILED is already set; do_issue_write() already terminates FAILED subrequests.

Fixes 82e8885bd763 ("netfs: when subreq is marked for retry, do not check if it faced an error")
---
 fs/netfs/write_issue.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/netfs/write_issue.c +3 -1
index b8237e1314d8..f23364116421 100644
@@ -268,7 +268,9 @@ void netfs_reissue_write(struct netfs_io_stream *stream,
 	iov_iter_truncate(&subreq->io_iter, size);
 
 	subreq->retry_count++;
-	subreq->error = 0;
+	/* Keep prepare_write() errno; do_issue_write() terminates FAILED. */
+	if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags))
+		subreq->error = 0;
 	__clear_bit(NETFS_SREQ_MADE_PROGRESS, &subreq->flags);
 	__set_bit(NETFS_SREQ_IN_PROGRESS, &subreq->flags);
 	netfs_stat(&netfs_n_wh_retry_write_subreq);
Signature · 1 line
2.56.0
author maintainer
#3 lore raw

PATCH v9 3/19 netfs: keep the prepare_read errno when abandoning read retries

In reply to Paulo Alcantara

When ->prepare_read() fails while retrying a read, netfs_retry_read_subrequests() marks the subrequest failed and abandons the rest, which overwrites the error of every failed subrequest with -ENOMEM. The reader then gets -ENOMEM for e.g. a handle that couldn't be reopened (-EHOSTDOWN, -ENOENT), a credit wait interrupted by a signal (-ERESTARTSYS) or umount -f (-EIO). The first pass doesn't have this problem, as netfs_cancel_read() keeps the errno.

Record the errno of ->prepare_read() in the subrequest and keep the error of subrequests that already failed, using -ENOMEM only for those abandoned while still waiting for a retry.

Fixes ee4cdf7ba857 ("netfs: Speed up buffered reading")
---
 fs/netfs/read_retry.c | 16 ++++++++++++----
 1 file changed, 12 insertions(+), 4 deletions(-)
fs/netfs/read_retry.c +12 -4
index 5bd8dee5a834..8a722995fa9d 100644
@@ -28,6 +28,7 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq)
 	struct netfs_io_subrequest *subreq;
 	struct netfs_io_stream *stream = &rreq->io_streams[0];
 	struct list_head *next;
+	int ret;
 
 	_enter("R=%x", rreq->debug_id);
 
@@ -140,8 +141,11 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq)
 
 			/* Renegotiate max_len (rsize) */
 			stream->sreq_max_len = subreq->len;
-			if (rreq->netfs_ops->prepare_read &&
-			    rreq->netfs_ops->prepare_read(subreq) < 0) {
+			ret = 0;
+			if (rreq->netfs_ops->prepare_read)
+				ret = rreq->netfs_ops->prepare_read(subreq);
+			if (ret < 0) {
+				subreq->error = ret;
 				trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed);
 				__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 				goto abandon;
@@ -221,7 +225,9 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq)
 				part = netfs_limit_iter(&source, 0, part, stream->sreq_max_segs);
 
 			netfs_stat(&netfs_n_rh_download);
-			if (rreq->netfs_ops->prepare_read(subreq) < 0) {
+			ret = rreq->netfs_ops->prepare_read(subreq);
+			if (ret < 0) {
+				subreq->error = ret;
 				trace_netfs_sreq(subreq, netfs_sreq_trace_reprep_failed);
 				__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 				goto abandon;
@@ -257,7 +263,9 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq)
 		if (!test_bit(NETFS_SREQ_FAILED, &subreq->flags) &&
 		    !test_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags))
 			continue;
-		subreq->error = -ENOMEM;
+		if (!subreq->error ||
+		    !test_bit(NETFS_SREQ_FAILED, &subreq->flags))
+			subreq->error = -ENOMEM;
 		__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 		__clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags);
 	}
Signature · 1 line
2.56.0
author maintainer
#4 lore raw

PATCH v9 4/19 netfs: don't hang a read whose retry is abandoned

In reply to Paulo Alcantara

When ->prepare_read() fails while retrying a read, or a subrequest can't be allocated, netfs_retry_read_subrequests() marks the remaining subrequests failed without reissuing them. If none was reissued in that pass, nothing is in progress any more to wake the collector, which returned after the retry, so an offloaded read (readahead, async direct I/O) never completes and its folios stay locked.

Wake the collector after abandoning, so it collects the failed subrequests and completes the request.

Fixes e2d46f2ec332 ("netfs: Change the read result collector to only use one work item")
---
 fs/netfs/read_retry.c | 1 +
 1 file changed, 1 insertion(+)
fs/netfs/read_retry.c +1 -0
index 8a722995fa9d..bfaaebea12df 100644
@@ -269,6 +269,7 @@ static void netfs_retry_read_subrequests(struct netfs_io_request *rreq)
 		__set_bit(NETFS_SREQ_FAILED, &subreq->flags);
 		__clear_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags);
 	}
+	netfs_wake_collector(rreq);
 }
 
 /*
Signature · 1 line
2.56.0
author maintainer
#5 lore raw

PATCH v9 5/19 smb: client: let umount -f abort retried reads and writes

In reply to Paulo Alcantara

umount -f only wakes up tasks waiting on the server's queues. Reads and writes being retried - forever on hard mounts - keep going, so with the server gone the unmount still hangs in sync_filesystem() waiting for their writeback. NFS kills outstanding RPCs on umount -f instead.

Count umount -f attempts per superblock and have each read and write request remember the count it started with. Fail with -EIO, rather than retry, reissue, issue or wait for credits, any subrequest of a request that predates a umount -f once it is a retry or the server or share is disconnected; a kworker doing writeback can't be signalled out of the credit wait otherwise. First attempts on a connected server still go ahead, and requests started later aren't aborted (but see below), so I/O on a healthy server keeps working if the unmount then fails with -EBUSY or only detaches one of several mounts.

retry_count is not bumped yet when netfs_retry_write_stream() calls prepare_write() for the first retry, so don't rely on it alone to tell a reissue from a first attempt: treat a subrequest as a retry when it already carries an xid (it has been prepared before) in prepare_write()/prepare_read(), or when its replay flag is set in cifs_io_aborted(), and abort it when the mount is going away even if the connection still looks healthy.

Requests created after umount -f - writeback kicked off by the background flusher, an oplock break or sync_filesystem() during the final teardown - snapshot the already bumped count and would otherwise retry forever on a hard mount, hanging cifs_kill_sb(). Once a superblock that saw a umount -f reaches cifs_kill_sb() the mount is going away for good, so flag it and stop retrying I/O on it too; one that never saw a umount -f still flushes as before.

A sync(2) or syncfs() waiting under s_umount for writeback started after umount -f would still keep the unmount from reaching cifs_kill_sb(), so also stop retrying such I/O while s_umount is contended. After a failed umount -f, that also stops reads and writes retrying while a remount, freeze or new mount of the same superblock waits on s_umount.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/cifs_fs_sb.h |  2 ++
 fs/smb/client/cifsfs.c     | 10 +++++++
 fs/smb/client/cifsglob.h   |  1 +
 fs/smb/client/cifsproto.h  |  2 ++
 fs/smb/client/file.c       | 55 ++++++++++++++++++++++++++++++++++++++
 fs/smb/client/smb2pdu.c    | 16 +++--------
 6 files changed, 74 insertions(+), 12 deletions(-)
fs/smb/client/cifs_fs_sb.h +2 -0
index d6494e1d93cc..b322718d9199 100644
@@ -57,6 +57,7 @@ struct cifs_sb_info {
 	atomic_t active;
 	atomic_t mnt_cifs_flags;
 	atomic_t outstanding_rreq;	/* nr of rreqs not yet fully deinitialized */
+	atomic_t umount_aborts;		/* nr of umount -f attempts */
 	struct delayed_work prune_tlinks;
 	struct rcu_head rcu;
 
@@ -68,6 +69,7 @@ struct cifs_sb_info {
 	 * (cifs_autodisable_serverino) in order to match new mounts.
 	 */
 	bool mnt_cifs_serverino_autodisabled;
+	bool exiting;			/* umount -f committed: stop retries */
 	/*
 	 * Available once the mount has completed.
 	 */
fs/smb/client/cifsfs.c +10 -0
index bf199a5ca084..b3735c98bfc3 100644
@@ -297,6 +297,15 @@ static void cifs_kill_sb(struct super_block *sb)
 {
 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
 
+	/*
+	 * Reaching here after a umount -f means the mount is going away for
+	 * good, so stop retrying I/O that can no longer complete (e.g.
+	 * writeback to a server that is gone) rather than looping forever on
+	 * a hard mount and hanging the teardown below.
+	 */
+	if (atomic_read(&cifs_sb->umount_aborts))
+		WRITE_ONCE(cifs_sb->exiting, true);
+
 	/*
 	 * We need to release all dentries for the cached directories
 	 * and close all deferred file handles before we kill the sb.
@@ -835,6 +844,7 @@ static void cifs_umount_begin(struct super_block *sb)
 	if (cifs_sb == NULL)
 		return;
 
+	atomic_inc(&cifs_sb->umount_aborts);
 	tcon = cifs_sb_master_tcon(cifs_sb);
 
 	spin_lock(&cifs_tcp_ses_lock);
fs/smb/client/cifsglob.h +1 -0
index dbf980fcf05b..fb732c178e76 100644
@@ -1482,6 +1482,7 @@ struct cifs_io_request {
 	struct netfs_io_request		rreq;
 	struct cifsFileInfo		*cfile;
 	pid_t				pid;
+	int				umount_aborts;
 };
 
 /* asynchronous read support */
fs/smb/client/cifsproto.h +2 -0
index f9ea35597bc2..a37eee2ca54b 100644
@@ -137,6 +137,8 @@ bool is_size_safe_to_change(struct cifsInodeInfo *cifsInode, __u64 end_of_file,
 			    bool from_readdir);
 void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata,
 				      ssize_t result);
+bool cifs_io_stopped(struct cifs_io_subrequest *subreq);
+bool cifs_io_should_replay(struct cifs_io_subrequest *subreq);
 struct cifsFileInfo *find_writable_file(struct cifsInodeInfo *cifs_inode,
 					int flags);
 int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
fs/smb/client/file.c +55 -0

103 lines not on this page · raw message

fs/smb/client/smb2pdu.c +4 -12
index f85595136ef8..ecc127d9f0af 100644
@@ -4815,9 +4815,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 
 	/* see if we need to retry */
 	if (is_replayable_error(rdata->result) &&
-	    smb2_should_replay(tcon,
-			       &rdata->retries,
-			       &rdata->cur_sleep))
+	    cifs_io_should_replay(rdata))
 		rdata->replay = true;
 
 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
@@ -4926,9 +4924,7 @@ smb2_async_readv(struct cifs_io_subrequest *rdata)
 out:
 	/* if the send error is retryable, let netfs know about it */
 	if (is_replayable_error(rc) &&
-	    smb2_should_replay(tcon,
-			       &rdata->retries,
-			       &rdata->cur_sleep)) {
+	    cifs_io_should_replay(rdata)) {
 		rdata->replay = true;
 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
@@ -5165,9 +5161,7 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 
 	/* see if we need to retry */
 	if (is_replayable_error(wdata->result) &&
-	    smb2_should_replay(tcon,
-			       &wdata->retries,
-			       &wdata->cur_sleep))
+	    cifs_io_should_replay(wdata))
 		wdata->replay = true;
 
 	cifs_write_subrequest_terminated(wdata, result ?: written);
@@ -5339,9 +5333,7 @@ smb2_async_writev(struct cifs_io_subrequest *wdata)
 out:
 	/* if the send error is retryable, let netfs know about it */
 	if (is_replayable_error(rc) &&
-	    smb2_should_replay(tcon,
-			       &wdata->retries,
-			       &wdata->cur_sleep)) {
+	    cifs_io_should_replay(wdata)) {
 		wdata->replay = true;
 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
 		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
Signature · 1 line
2.56.0
author maintainer
#6 lore raw

PATCH v9 6/19 smb: client: don't give up writeback on the first replayable error

In reply to Paulo Alcantara

Read and write retries follow the hard and retrans mount options, and mounts are soft with no retrans by default. For writeback this means that a single replayable error, e.g. a reconnect while sending, fails the subrequest and netfs ends writeback with its folios clean: the data is gone, possibly long after write(2) succeeded, with only fsync(2) left to notice. NFS soft mounts, by comparison, wait minutes for a server to answer before failing a request.

Keep retrying writeback on replayable errors, with exponential backoff:
forever on hard mounts, and on soft mounts for max(3, retrans) echo intervals from the first failure - 3 minutes by default, the time after which a silent server is considered unresponsive. The window applies to each write sent to the server, not to the whole writeback. umount -f or a shutdown still stops it right away. Direct and unbuffered writes, whose callers get the error, keep following the mount options.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/cifsglob.h  |  1 +
 fs/smb/client/file.c      | 21 +++++++++++++++++++++
 fs/smb/client/smb2ops.c   |  9 +--------
 fs/smb/client/smb2proto.h |  9 +++++++++
 4 files changed, 32 insertions(+), 8 deletions(-)
fs/smb/client/cifsglob.h +1 -0
index fb732c178e76..b6a993cc0245 100644
@@ -1499,6 +1499,7 @@ struct cifs_io_subrequest {
 	bool				replay;
 	unsigned int			retries;	/* number of retries so far */
 	unsigned int			cur_sleep;	/* time to sleep before replay */
+	unsigned long			retry_deadline;
 	struct kvec			iov[2];
 	struct TCP_Server_Info		*server;
 #ifdef CONFIG_CIFS_SMB_DIRECT
fs/smb/client/file.c +21 -0
index 270858e526f9..e8557c670dc3 100644
@@ -53,12 +53,33 @@ bool cifs_io_stopped(struct cifs_io_subrequest *subreq)
 	return aborts && rwsem_is_contended(&sb->s_umount);
 }
 
+static bool cifs_writeback_retry_expired(struct cifs_io_subrequest *subreq,
+					 struct cifs_tcon *tcon)
+{
+	struct TCP_Server_Info *server = tcon->ses->server;
+	unsigned long window;
+
+	if (tcon->retry)
+		return false;
+	if (!subreq->retry_deadline) {
+		window = max(3U, server->retrans) * server->echo_interval;
+		subreq->retry_deadline = (jiffies + window) | 1;
+	}
+	return time_after(jiffies, subreq->retry_deadline);
+}
+
 bool cifs_io_should_replay(struct cifs_io_subrequest *subreq)
 {
 	struct cifs_tcon *tcon = tlink_tcon(subreq->req->cfile->tlink);
 
 	if (cifs_io_stopped(subreq))
 		return false;
+	if (subreq->rreq->origin == NETFS_WRITEBACK) {
+		if (cifs_writeback_retry_expired(subreq, tcon))
+			return false;
+		smb2_replay_backoff(&subreq->cur_sleep);
+		return true;
+	}
 	return smb2_should_replay(tcon, &subreq->retries, &subreq->cur_sleep);
 }
 
fs/smb/client/smb2ops.c +1 -8
index dc55cd512616..457f18ce3245 100644
@@ -2934,14 +2934,7 @@ bool smb2_should_replay(struct cifs_tcon *tcon,
 		return false;
 
 	if (tcon->retry || (*pretries)++ < tcon->ses->server->retrans) {
-		/* Update sleep time for exponential backoff */
-		if (!(*pcur_sleep))
-			(*pcur_sleep) = 1;
-		else {
-			(*pcur_sleep) = ((*pcur_sleep) << 1);
-			if ((*pcur_sleep) > CIFS_MAX_SLEEP)
-				(*pcur_sleep) = CIFS_MAX_SLEEP;
-		}
+		smb2_replay_backoff(pcur_sleep);
 		return true;
 	}
 
fs/smb/client/smb2proto.h +9 -0
index c79e5cb2ce26..b2acff8938f3 100644
@@ -121,6 +121,15 @@ unsigned long smb_rqst_len(struct TCP_Server_Info *server,
 void smb2_set_next_command(struct cifs_tcon *tcon, struct smb_rqst *rqst);
 void smb2_set_related(struct smb_rqst *rqst);
 void smb2_set_replay(struct TCP_Server_Info *server, struct smb_rqst *rqst);
+
+static inline void smb2_replay_backoff(int *pcur_sleep)
+{
+	if (!*pcur_sleep)
+		*pcur_sleep = 1;
+	else
+		*pcur_sleep = min(*pcur_sleep << 1, CIFS_MAX_SLEEP);
+}
+
 bool smb2_should_replay(struct cifs_tcon *tcon, int *pretries,
 			int *pcur_sleep);
 
Signature · 1 line
2.56.0
author maintainer
#7 lore raw

PATCH v9 7/19 smb: client: don't retry failed writes forever regardless of mount options

In reply to Paulo Alcantara

smb2_writev_callback() marks a write for retry whenever the server fails it with a replayable status, ignoring smb2_should_replay() and so the hard and retrans mount options. The latter is only used to decide on a backoff, so on a soft mount with no retrans, a server that keeps failing a write with e.g. STATUS_INSUFFICIENT_RESOURCES gets it resent forever, thousands of times per second, hanging anything waiting on its writeback:

smb3_write_err: R=005c359e[2] ... offset=0x27000 len=0xfdf0 rc=-11 (569410 times in 255 seconds, same subrequest, no growing delay)

Only retry such writes when cifs_io_should_replay() allows it, as already done for send errors in smb2_async_writev(), otherwise let them fail. Writeback thus keeps retrying them with backoff, within its retry window. Base the decision on the result of this attempt rather than on wdata->result, which is never reset on success and may hold the error of a previous attempt.

Writes cut short by a reconnect get retried regardless too. Have writeback ones go through cifs_io_should_replay() as well, so that they back off and soft mounts give up on them after the retry window, as on other replayable errors. Other writes cut short keep being retried, without spending the mount's retries, but as replays, since they may have reached the server, unless umount -f stopped them, which fails them with -EIO.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/smb2pdu.c | 25 ++++++++++++++-----------
 1 file changed, 14 insertions(+), 11 deletions(-)
fs/smb/client/smb2pdu.c +14 -11
index ecc127d9f0af..736c5c693c79 100644
@@ -5056,6 +5056,7 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 	};
 	unsigned int rreq_debug_id = wdata->rreq->debug_id;
 	unsigned int subreq_debug_index = wdata->subreq.debug_index;
+	bool cut_short = false;
 	ssize_t result = 0;
 	size_t written = 0;
 
@@ -5069,10 +5070,7 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 		credits.instance = server->reconnect_instance;
 		result = smb2_check_receive(mid, server, 0);
 		if (result != 0) {
-			if (is_replayable_error(result)) {
-				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
-				__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
-			} else {
+			if (!is_replayable_error(result)) {
 				wdata->subreq.error = result;
 				trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_bad);
 			}
@@ -5101,12 +5099,9 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 		break;
 	case MID_REQUEST_SUBMITTED:
 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted);
-		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
-		result = -EAGAIN;
-		break;
+		fallthrough;
 	case MID_RETRY_NEEDED:
-		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
-		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+		cut_short = true;
 		result = -EAGAIN;
 		break;
 	case MID_RESPONSE_MALFORMED:
@@ -5160,9 +5155,17 @@ smb2_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 	wdata->credits.value = 0;
 
 	/* see if we need to retry */
-	if (is_replayable_error(wdata->result) &&
-	    cifs_io_should_replay(wdata))
+	if (is_replayable_error(result) &&
+	    ((cut_short && wdata->rreq->origin != NETFS_WRITEBACK &&
+	      !cifs_io_stopped(wdata)) ||
+	     cifs_io_should_replay(wdata))) {
 		wdata->replay = true;
+		trace_netfs_sreq(&wdata->subreq,
+				 netfs_sreq_trace_io_retry_needed);
+		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+	} else if (cut_short && cifs_io_stopped(wdata)) {
+		result = -EIO;
+	}
 
 	cifs_write_subrequest_terminated(wdata, result ?: written);
 	release_mid(server, mid);
Signature · 1 line
2.56.0
author maintainer
#8 lore raw

PATCH v9 8/19 smb: client: don't spend read retries on reads cut short by a reconnect

In reply to Paulo Alcantara

smb2_readv_callback() always retries a read cut short by a reconnect, but still asks cifs_io_should_replay() whether to mark it as a replay. On a soft mount that spends one of the mount's retransmissions and grows the backoff, so a later replayable error on the reissued read can fail it early.

Mark such reads as replays without consulting the mount's retries, as already done for writes.

Fixes 2c1238a7477a ("cifs: make retry logic in read/write path consistent with other paths")
---
 fs/smb/client/smb2pdu.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
fs/smb/client/smb2pdu.c +3 -1
index 736c5c693c79..be003200efa8 100644
@@ -4695,6 +4695,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 	struct smb_rqst rqst = { .rq_iov = &rdata->iov[0], .rq_nvec = 1 };
 	unsigned int rreq_debug_id = rdata->rreq->debug_id;
 	unsigned int subreq_debug_index = rdata->subreq.debug_index;
+	bool cut_short = false;
 
 	if (rdata->got_bytes) {
 		rqst.rq_iter	  = rdata->subreq.io_iter;
@@ -4743,6 +4744,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 		trace_netfs_sreq(&rdata->subreq, netfs_sreq_trace_io_retry_needed);
 do_retry:
 		__set_bit(NETFS_SREQ_NEED_RETRY, &rdata->subreq.flags);
+		cut_short = true;
 		rdata->result = -EAGAIN;
 		if (server->sign && rdata->got_bytes)
 			/* reset bytes number since we can not check a sign */
@@ -4815,7 +4817,7 @@ smb2_readv_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 
 	/* see if we need to retry */
 	if (is_replayable_error(rdata->result) &&
-	    cifs_io_should_replay(rdata))
+	    (cut_short || cifs_io_should_replay(rdata)))
 		rdata->replay = true;
 
 	trace_smb3_rw_credits(rreq_debug_id, subreq_debug_index, rdata->credits.value,
Signature · 1 line
2.56.0
author maintainer
#9 lore raw

PATCH v9 9/19 smb: client: don't block dying tasks waiting for writeback on close

In reply to Paulo Alcantara

cifs_flush() waits uninterruptibly for the writeback it starts. A task that gets killed while closing a file on a hard mount with an unresponsive server is stuck in D state until the server comes back. It also consumes any writeback error for a caller that is about to exit, hiding it from everyone else.

Wait killably instead. If the closer gets killed, stop waiting and leave the error bits in the mapping for others to see; writeback already in flight completes on its own.

This is also needed before letting dying tasks issue their writes from a worker, which would otherwise make them wait for every one of them.

Fixes d3f1322af8f8 ("cifs: wait for writeback to complete in cifs_flush")
---
 fs/smb/client/file.c | 32 +++++++++++++++++++++++++++++---
 1 file changed, 29 insertions(+), 3 deletions(-)
fs/smb/client/file.c +29 -3
index e8557c670dc3..0d2db0dd43f2 100644
@@ -3043,17 +3043,43 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
 	return rc;
 }
 
+static int cifs_wait_writeback_killable(struct address_space *mapping)
+{
+	struct folio_batch fbatch;
+	pgoff_t index = 0;
+	int rc = 0;
+
+	folio_batch_init(&fbatch);
+	while (!rc &&
+	       filemap_get_folios_tag(mapping, &index, (pgoff_t)-1,
+				      PAGECACHE_TAG_WRITEBACK, &fbatch)) {
+		for (unsigned int i = 0;
+		     !rc && i < folio_batch_count(&fbatch); i++)
+			rc = folio_wait_writeback_killable(fbatch.folios[i]);
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+	return rc;
+}
+
 /*
  * As file closes, flush all cached write data for this inode checking
  * for write behind errors.
  */
 int cifs_flush(struct file *file, fl_owner_t id)
 {
+	struct address_space *mapping = file->f_mapping;
 	struct inode *inode = file_inode(file);
-	int rc = 0;
+	int rc = 0, rc2;
 
-	if (file->f_mode & FMODE_WRITE)
-		rc = filemap_write_and_wait(inode->i_mapping);
+	if (file->f_mode & FMODE_WRITE) {
+		rc = filemap_fdatawrite(mapping);
+		if (cifs_wait_writeback_killable(mapping))
+			return 0;
+		rc2 = filemap_check_errors(mapping);
+		if (!rc)
+			rc = rc2;
+	}
 
 	cifs_dbg(FYI, "Flush inode %p file %p rc %d\n", inode, file, rc);
 	if (rc) {
Signature · 1 line
2.56.0
author maintainer
#10 lore raw

PATCH v9 10/19 smb: client: issue writes from a worker if the task is dying

In reply to Paulo Alcantara

A task with a fatal signal pending can't send on the socket:
__smb_send_rqst() refuses it upfront with -ERESTARTSYS, as SIGKILL can't be blocked and a send interrupted halfway forces a reconnect. Writeback, however, runs in the context of whoever starts it, so when a dying task flushes dirty pages - close() racing with SIGKILL, or fd teardown during exit_group() - every write subrequest gets refused:

smb3_write_err: ... offset=0x1400000 len=0x400000 rc=-512
cifs_flush_err: ino=... rc=-512

Since the switch to netfslib, a failed upload ends writeback with the folios clean, so the data is silently lost: the server ends up with 20MiB of a 64MiB file while stat(2) reports the full size.

Issue writeback subrequests of dying tasks from a new cifswritebackd workqueue instead, like afs does for all of its writes, so they get sent from a context with no signals. Leave direct and unbuffered writes alone, as their callers get the error. Use a dedicated WQ_UNBOUND workqueue as the writes may block for long on credits, sends or reopens, e.g. on hard mounts with an unresponsive server, and must not hold up other cifs work such as reconnects, nor starve the WQ_MEM_RECLAIM rescuer of cifsiod_wq.

Fixes 3ee1a1fc3981 ("cifs: Cut over to using netfslib")
---
 fs/smb/client/cifsfs.c   | 15 +++++++++++++--
 fs/smb/client/cifsglob.h |  1 +
 fs/smb/client/file.c     | 26 +++++++++++++++++++++++++-
 3 files changed, 39 insertions(+), 3 deletions(-)
fs/smb/client/cifsfs.c +13 -2
index b3735c98bfc3..7146bb22a69e 100644
@@ -164,6 +164,7 @@ struct workqueue_struct	*cifsoplockd_wq;
 struct workqueue_struct	*deferredclose_wq;
 struct workqueue_struct	*serverclose_wq;
 struct workqueue_struct	*cfid_put_wq;
+struct workqueue_struct	*cifs_writeback_wq;
 __u32 cifs_lock_secret;
 
 /*
@@ -2133,9 +2134,16 @@ init_cifs(void)
 		goto out_destroy_serverclose_wq;
 	}
 
-	rc = cifs_init_inodecache();
-	if (rc)
+	cifs_writeback_wq = alloc_workqueue("cifswritebackd",
+					    WQ_UNBOUND | WQ_MEM_RECLAIM, 0);
+	if (!cifs_writeback_wq) {
+		rc = -ENOMEM;
 		goto out_destroy_cfid_put_wq;
+	}
+
+	rc = cifs_init_inodecache();
+	if (rc)
+		goto out_destroy_writeback_wq;
 
 	rc = cifs_init_netfs();
 	if (rc)
@@ -2206,6 +2214,8 @@ init_cifs(void)
 	cifs_destroy_netfs();
 out_destroy_inodecache:
 	cifs_destroy_inodecache();
+out_destroy_writeback_wq:
+	destroy_workqueue(cifs_writeback_wq);
 out_destroy_cfid_put_wq:
 	destroy_workqueue(cfid_put_wq);
 out_destroy_serverclose_wq:
@@ -2251,6 +2261,7 @@ exit_cifs(void)
 	destroy_workqueue(fileinfo_put_wq);
 	destroy_workqueue(serverclose_wq);
 	destroy_workqueue(cfid_put_wq);
+	destroy_workqueue(cifs_writeback_wq);
 	destroy_workqueue(cifsiod_wq);
 }
 
fs/smb/client/cifsglob.h +1 -0
index b6a993cc0245..e211dea91e6e 100644
@@ -2144,6 +2144,7 @@ extern struct workqueue_struct *cifsoplockd_wq;
 extern struct workqueue_struct *deferredclose_wq;
 extern struct workqueue_struct *serverclose_wq;
 extern struct workqueue_struct *cfid_put_wq;
+extern struct workqueue_struct *cifs_writeback_wq;
 extern __u32 cifs_lock_secret;
 
 extern mempool_t *cifs_sm_req_poolp;
fs/smb/client/file.c +25 -1
index 0d2db0dd43f2..1bd8edbc8d7b 100644
@@ -94,6 +94,12 @@ static bool cifs_io_aborted(struct cifs_io_subrequest *subreq)
 	       tcon->need_reconnect;
 }
 
+static bool cifs_writeback_dying(struct netfs_io_subrequest *subreq)
+{
+	return subreq->rreq->origin == NETFS_WRITEBACK &&
+		fatal_signal_pending(current);
+}
+
 /*
  * Prepare a subrequest to upload to the server.  We need to allocate credits
  * so that we know the maximum amount of data that we can include in it.
@@ -170,7 +176,7 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq)
 /*
  * Issue a subrequest to upload to the server.
  */
-static void cifs_issue_write(struct netfs_io_subrequest *subreq)
+static void __cifs_issue_write(struct netfs_io_subrequest *subreq)
 {
 	struct cifs_io_subrequest *wdata =
 		container_of(subreq, struct cifs_io_subrequest, subreq);
@@ -208,6 +214,24 @@ static void cifs_issue_write(struct netfs_io_subrequest *subreq)
 	goto out;
 }
 
+static void cifs_issue_write_worker(struct work_struct *work)
+{
+	struct netfs_io_subrequest *subreq;
+
+	subreq = container_of(work, struct netfs_io_subrequest, work);
+	__cifs_issue_write(subreq);
+}
+
+static void cifs_issue_write(struct netfs_io_subrequest *subreq)
+{
+	if (unlikely(cifs_writeback_dying(subreq))) {
+		subreq->work.func = cifs_issue_write_worker;
+		WARN_ON_ONCE(!queue_work(cifs_writeback_wq, &subreq->work));
+		return;
+	}
+	__cifs_issue_write(subreq);
+}
+
 static void cifs_netfs_invalidate_cache(struct netfs_io_request *wreq)
 {
 	cifs_invalidate_cache(wreq->inode, 0);
Signature · 1 line
2.56.0
author maintainer
#11 lore raw

PATCH v9 11/19 smb: client: don't fail writeback preparation if the task is dying

In reply to Paulo Alcantara

cifs_prepare_write() may need to reopen an invalidated handle and to wait for credits, both from the context of the task doing writeback. A dying task gets the reopen refused at send time and the killable credit wait interrupted, so the subrequest is failed and, as with refused sends, its folios end writeback clean and the data is lost.

For writeback in a dying task, skip both and prepare a credit-less subrequest capped at SMB2_MAX_BUFFER_SIZE, as already done when the server is low on credits. It gets issued from cifswritebackd, which reopens the handle if needed and takes a single credit when sending, neither of which can be interrupted there. Do the same when the reopen or credit wait fails because a fatal signal arrived meanwhile.

cifs_begin_writeback() reopens the handle too when all the writable ones got invalidated, e.g. by a reconnect. If that fails, there is no upload stream, so netfs ends writeback of every folio clean with no error recorded. Take an invalidated handle as is there and leave reopening it to cifs_prepare_write(). If there is no writable handle at all, record -EIO for the mapping, so that the loss gets reported.

Fixes 3ee1a1fc3981 ("cifs: Cut over to using netfslib")
---
 fs/smb/client/cifsglob.h |  1 +
 fs/smb/client/file.c     | 37 ++++++++++++++++++++++++++++++-------
 2 files changed, 31 insertions(+), 7 deletions(-)
fs/smb/client/cifsglob.h +1 -0
index e211dea91e6e..064a2cdab4d9 100644
@@ -1894,6 +1894,7 @@ enum cifs_find_flags {
 	FIND_NO_PENDING_DELETE	= (1U << 2),
 	FIND_OPEN_FLAGS		= (1U << 3),
 	FIND_NO_DIRECT		= (1U << 4),
+	FIND_NO_REOPEN		= (1U << 5),
 };
 
 #define   MID_FREE 0
fs/smb/client/file.c +30 -7
index 1bd8edbc8d7b..396524c3f2b6 100644
@@ -135,12 +135,17 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq)
 		cifs_negotiate_wsize(server, cifs_sb->ctx,
 				     tlink_tcon(req->cfile->tlink));
 
+	if (cifs_writeback_dying(subreq))
+		goto defer;
+
 retry:
 	if (open_file->invalidHandle) {
 		rc = cifs_reopen_file(open_file, false);
 		if (rc < 0) {
 			if (rc == -EAGAIN)
 				goto retry;
+			if (cifs_writeback_dying(subreq))
+				goto defer;
 			subreq->error = rc;
 			return netfs_prepare_write_failed(subreq);
 		}
@@ -149,10 +154,17 @@ static void cifs_prepare_write(struct netfs_io_subrequest *subreq)
 	rc = server->ops->wait_mtu_credits(server, wsize, &stream->sreq_max_len,
 					   &wdata->credits);
 	if (rc < 0) {
+		if (cifs_writeback_dying(subreq))
+			goto defer;
 		subreq->error = rc;
 		return netfs_prepare_write_failed(subreq);
 	}
+	goto out;
 
+defer:
+	wdata->credits = (struct cifs_credits){};
+	stream->sreq_max_len = min_t(size_t, wsize, SMB2_MAX_BUFFER_SIZE);
+out:
 	wdata->credits.rreq_debug_id = subreq->rreq->debug_id;
 	wdata->credits.rreq_debug_index = subreq->debug_index;
 	wdata->credits.in_flight_check = 1;
@@ -216,10 +228,15 @@ static void __cifs_issue_write(struct netfs_io_subrequest *subreq)
 
 static void cifs_issue_write_worker(struct work_struct *work)
 {
-	struct netfs_io_subrequest *subreq;
+	struct cifs_io_subrequest *wdata;
+	struct cifsFileInfo *cfile;
 
-	subreq = container_of(work, struct netfs_io_subrequest, work);
-	__cifs_issue_write(subreq);
+	wdata = container_of(work, struct cifs_io_subrequest, subreq.work);
+	cfile = wdata->req->cfile;
+	while (cfile->invalidHandle &&
+	       cifs_reopen_file(cfile, false) == -EAGAIN)
+		;
+	__cifs_issue_write(&wdata->subreq);
 }
 
 static void cifs_issue_write(struct netfs_io_subrequest *subreq)
@@ -354,15 +371,17 @@ static void cifs_begin_writeback(struct netfs_io_request *wreq)
 	struct cifs_io_request *req = container_of(wreq, struct cifs_io_request, rreq);
 	int ret;
 
-	ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_NO_DIRECT,
+	ret = cifs_get_writable_file(CIFS_I(wreq->inode),
+				     FIND_NO_REOPEN | FIND_NO_DIRECT,
 				     &req->cfile);
 	if (ret) {
-		ret = cifs_get_writable_file(CIFS_I(wreq->inode), FIND_ANY,
-					     &req->cfile);
+		ret = cifs_get_writable_file(CIFS_I(wreq->inode),
+					     FIND_NO_REOPEN, &req->cfile);
 	}
 	if (ret) {
 		cifs_dbg(VFS, "%s: couldn't find writable handle: %d\n",
 			 __func__, ret);
+		mapping_set_error(wreq->mapping, -EIO);
 		return;
 	}
 
@@ -2828,7 +2847,7 @@ int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
 	}
 
 	if (test_bit(CIFS_INO_TMPFILE, &cifs_inode->flags))
-		find_flags &= FIND_NO_DIRECT;
+		find_flags &= FIND_NO_REOPEN | FIND_NO_DIRECT;
 
 	cifs_sb = CIFS_SB(cifs_inode);
 
@@ -2888,6 +2907,10 @@ int __cifs_get_writable_file(struct cifsInodeInfo *cifs_inode,
 	spin_unlock(&cifs_inode->open_file_lock);
 
 	if (inv_file) {
+		if (find_flags & FIND_NO_REOPEN) {
+			*ret_file = inv_file;
+			return 0;
+		}
 		rc = cifs_reopen_file(inv_file, false);
 		if (!rc) {
 			*ret_file = inv_file;
Signature · 1 line
2.56.0
author maintainer
#12 lore raw

PATCH v9 12/19 smb: client: retry writeback on interrupts and allocation failures

In reply to Paulo Alcantara

Issuing writes from a worker only helps when the task is already dying at issue time. A fatal signal can still arrive after that check and before __smb_send_rqst() checks again, or while waiting for a credit in cifs_call_async(), or in the middle of a send. The write then fails with -ERESTARTSYS, which isn't a replayable error, so netfs marks the subrequest failed and drops its folios clean:

netfs_sreq: R=000041f6[2] UPLD SUBMT ... s=400000 0/400000
smb3_write_err: R=000041f6[2] ... offset=0x400000 len=0x400000 rc=-512
netfs_failure: R=000041f6[2] UPLD ... upload e=-512

losing 4MiB of a 64MiB file closed by a task killed meanwhile. A failed memory allocation while building or sending a write drops its data the same way.

No server status maps to an interrupt error or to -ENOMEM, so for writeback such errors always mean the client gave up locally. Mark the subrequest for retry, with backoff and giving up on umount -f, as cifs did with is_retryable_error() before switching to netfslib and as NFS does for these errors. netfs collects writeback from a workqueue, so the retry gets prepared and issued with no signals pending.

Only the SMB2 read and write paths sleep before replaying, so SMB1 would resend such writes right away. Move the sleep to cifs_issue_read() and __cifs_issue_write().

Fixes 3ee1a1fc3981 ("cifs: Cut over to using netfslib")
---
 fs/smb/client/file.c    | 14 ++++++++++++++
 fs/smb/client/smb2pdu.c | 12 ++----------
 2 files changed, 16 insertions(+), 10 deletions(-)
fs/smb/client/file.c +14 -0
index 396524c3f2b6..abbf6a1be9e2 100644
@@ -212,6 +212,9 @@ static void __cifs_issue_write(struct netfs_io_subrequest *subreq)
 	if (wdata->req->cfile->invalidHandle)
 		goto fail;
 
+	if (wdata->replay && wdata->cur_sleep)
+		msleep(wdata->cur_sleep);
+
 	wdata->server->ops->async_writev(wdata);
 out:
 	return;
@@ -350,6 +353,9 @@ static void cifs_issue_read(struct netfs_io_subrequest *subreq)
 	    subreq->rreq->origin != NETFS_DIO_READ)
 		__set_bit(NETFS_SREQ_CLEAR_TAIL, &subreq->flags);
 
+	if (rdata->replay && rdata->cur_sleep)
+		msleep(rdata->cur_sleep);
+
 	trace_netfs_sreq(subreq, netfs_sreq_trace_submit);
 	rc = rdata->server->ops->async_readv(rdata);
 	if (rc)
@@ -2754,6 +2760,14 @@ void cifs_write_subrequest_terminated(struct cifs_io_subrequest *wdata, ssize_t
 		spin_unlock(&inode->i_lock);
 	}
 
+	if ((is_interrupt_error(result) || result == -ENOMEM) &&
+	    wreq->origin == NETFS_WRITEBACK && cifs_io_should_replay(wdata)) {
+		wdata->replay = true;
+		trace_netfs_sreq(&wdata->subreq,
+				 netfs_sreq_trace_io_retry_needed);
+		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+	}
+
 	netfs_write_subrequest_terminated(&wdata->subreq, result);
 }
 
fs/smb/client/smb2pdu.c +2 -10
index be003200efa8..bf22e7f6445d 100644
@@ -4880,12 +4880,8 @@ smb2_async_readv(struct cifs_io_subrequest *rdata)
 
 	shdr = (struct smb2_hdr *)buf;
 
-	if (rdata->replay) {
-		/* Back-off before retry */
-		if (rdata->cur_sleep)
-			msleep(rdata->cur_sleep);
+	if (rdata->replay)
 		smb2_set_replay(server, &rqst);
-	}
 
 	if (rdata->credits.value > 0) {
 		shdr->CreditCharge = cpu_to_le16(DIV_ROUND_UP(io_parms.length,
@@ -5285,12 +5281,8 @@ smb2_async_writev(struct cifs_io_subrequest *wdata)
 	}
 #endif
 
-	if (wdata->replay) {
-		/* Back-off before retry */
-		if (wdata->cur_sleep)
-			msleep(wdata->cur_sleep);
+	if (wdata->replay)
 		smb2_set_replay(server, &rqst);
-	}
 
 	cifs_dbg(FYI, "async write at %llu %u bytes iter=%zx\n",
 		 io_parms->offset, io_parms->length, iov_iter_count(&wdata->subreq.io_iter));
Signature · 1 line
2.56.0
author maintainer
#13 lore raw

PATCH v9 13/19 smb: client: don't block dying tasks waiting for writeback on fsync

In reply to Paulo Alcantara

cifs_fsync() and cifs_strict_fsync() wait uninterruptibly for writeback through file_write_and_wait_range(). As with close, a task killed in fsync(2) on a hard mount with an unresponsive server is stuck in D state until the server comes back.

Wait killably instead, using the same helper as cifs_flush(). The writeback keeps going and its errors stay in the mapping; only the dying caller stops waiting for it.

---
 fs/smb/client/file.c | 64 +++++++++++++++++++++++++++++---------------
 1 file changed, 42 insertions(+), 22 deletions(-)
fs/smb/client/file.c +42 -22
index abbf6a1be9e2..0fc1f74b55b6 100644
@@ -3026,6 +3026,45 @@ cifs_get_readable_path(struct cifs_tcon *tcon, const char *name,
 	return -ENOENT;
 }
 
+static int cifs_wait_writeback_killable(struct address_space *mapping,
+					loff_t start, loff_t end)
+{
+	pgoff_t end_index = end >> PAGE_SHIFT;
+	pgoff_t index = start >> PAGE_SHIFT;
+	struct folio_batch fbatch;
+	int rc = 0;
+
+	folio_batch_init(&fbatch);
+	while (!rc &&
+	       filemap_get_folios_tag(mapping, &index, end_index,
+				      PAGECACHE_TAG_WRITEBACK, &fbatch)) {
+		for (unsigned int i = 0;
+		     !rc && i < folio_batch_count(&fbatch); i++)
+			rc = folio_wait_writeback_killable(fbatch.folios[i]);
+		folio_batch_release(&fbatch);
+		cond_resched();
+	}
+	return rc;
+}
+
+static int cifs_file_write_and_wait_killable(struct file *file,
+					     loff_t start, loff_t end)
+{
+	struct address_space *mapping = file->f_mapping;
+	int rc, rc2;
+
+	if (end < start)
+		return 0;
+
+	rc = filemap_fdatawrite_range(mapping, start, end);
+	if (cifs_wait_writeback_killable(mapping, start, end))
+		return -EINTR;
+	rc2 = file_check_and_advance_wb_err(file);
+	if (!rc)
+		rc = rc2;
+	return rc;
+}
+
 /*
  * Flush data on a strict file.
  */
@@ -3037,7 +3076,7 @@ int cifs_strict_fsync(struct file *file, loff_t start, loff_t end,
 	unsigned int xid;
 	int rc;
 
-	rc = file_write_and_wait_range(file, start, end);
+	rc = cifs_file_write_and_wait_killable(file, start, end);
 	if (rc) {
 		trace_cifs_fsync_err(inode->i_ino, rc);
 		return rc;
@@ -3069,7 +3108,7 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
 	struct inode *inode = file_inode(file);
 	struct cifs_sb_info *cifs_sb = CIFS_SB(file);
 
-	rc = file_write_and_wait_range(file, start, end);
+	rc = cifs_file_write_and_wait_killable(file, start, end);
 	if (rc) {
 		trace_cifs_fsync_err(file_inode(file)->i_ino, rc);
 		return rc;
@@ -3104,25 +3143,6 @@ int cifs_fsync(struct file *file, loff_t start, loff_t end, int datasync)
 	return rc;
 }
 
-static int cifs_wait_writeback_killable(struct address_space *mapping)
-{
-	struct folio_batch fbatch;
-	pgoff_t index = 0;
-	int rc = 0;
-
-	folio_batch_init(&fbatch);
-	while (!rc &&
-	       filemap_get_folios_tag(mapping, &index, (pgoff_t)-1,
-				      PAGECACHE_TAG_WRITEBACK, &fbatch)) {
-		for (unsigned int i = 0;
-		     !rc && i < folio_batch_count(&fbatch); i++)
-			rc = folio_wait_writeback_killable(fbatch.folios[i]);
-		folio_batch_release(&fbatch);
-		cond_resched();
-	}
-	return rc;
-}
-
 /*
  * As file closes, flush all cached write data for this inode checking
  * for write behind errors.
@@ -3135,7 +3155,7 @@ int cifs_flush(struct file *file, fl_owner_t id)
 
 	if (file->f_mode & FMODE_WRITE) {
 		rc = filemap_fdatawrite(mapping);
-		if (cifs_wait_writeback_killable(mapping))
+		if (cifs_wait_writeback_killable(mapping, 0, LLONG_MAX))
 			return 0;
 		rc2 = filemap_check_errors(mapping);
 		if (!rc)
Signature · 1 line
2.56.0
author maintainer
#14 lore raw

PATCH v9 14/19 smb: client: retry writes that couldn't be issued due to a reconnect

In reply to Paulo Alcantara

__cifs_issue_write() fails a subrequest with -EAGAIN when its handle got invalidated or its credits belong to a session from before a reconnect, both before sending anything. netfs used to retry any -EAGAIN by itself, but now only retries subrequests marked for it, so these writes fail and their folios end writeback clean, losing the data.

Mark them for retry instead. The retry gets the handle reopened and fresh credits in cifs_prepare_write().

Fixes 82e8885bd763 ("netfs: when subreq is marked for retry, do not check if it faced an error")
---
 fs/smb/client/file.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
fs/smb/client/file.c +4 -2
index 0fc1f74b55b6..7e1e886dfedc 100644
@@ -220,10 +220,12 @@ static void __cifs_issue_write(struct netfs_io_subrequest *subreq)
 	return;
 
 fail:
-	if (rc == -EAGAIN)
+	if (rc == -EAGAIN) {
 		trace_netfs_sreq(subreq, netfs_sreq_trace_retry);
-	else
+		__set_bit(NETFS_SREQ_NEED_RETRY, &subreq->flags);
+	} else {
 		trace_netfs_sreq(subreq, netfs_sreq_trace_fail);
+	}
 	add_credits_and_wake_if(wdata->server, &wdata->credits, 0);
 	cifs_write_subrequest_terminated(wdata, rc);
 	goto out;
Signature · 1 line
2.56.0
author maintainer
#15 lore raw

PATCH v9 15/19 smb: client: retry writeback after losing the connection, share or handle

In reply to Paulo Alcantara

Writeback still fails, dropping its data, when a write gets back an error that only means the client lost track of the server for a while:

- -EHOSTDOWN from smb2_reconnect() when a soft mount's server stays unreachable for longer than the reconnect wait, or from STATUS_HOST_UNREACHABLE,
- -EREMCHG from STATUS_NETWORK_NAME_DELETED, for which the receive path already marks the tcon for reconnect,
- -EBADF from STATUS_FILE_CLOSED or STATUS_INVALID_HANDLE, e.g. after the server lost a durable handle,
- -ENETRESET and -ESHUTDOWN from STATUS_CONNECTION_RESET and STATUS_REMOTE_DISCONNECT,
- any replayable error on SMB1, whose async write never retries them, while it retries writes cut short by a reconnect forever, regardless of soft mounts.

Reopening the handle needed by a read or write is worse:
cifs_prepare_write() and cifs_issue_read() retry cifs_reopen_file() only on -EAGAIN, with no limit and no delay, and fail on anything else. A server failing the reopen with a status mapped to -EAGAIN, such as STATUS_INSUFFICIENT_RESOURCES, makes them spin forever, past umount -f and, when netfs retries from a worker, with no signal to stop them, while any of the errors above fails writeback right away.

Retry writeback failing with any of these, as already done for interrupts and allocation failures, with backoff and giving up on umount -f. On -EBADF, have the retry mark the handle invalid, so that it gets reopened, unless it got reopened since the write was issued: a late -EBADF would otherwise get the new handle replaced too, leaving it open on the server along with any byte-range locks pushed to it. Subrequests of the same request can fail -EBADF concurrently on different channels, so record the bad reopen generation atomically (keeping the newest), decide the invalidation under the handle lock, and have a reopen publish its new fid before its generation so a -EBADF is attributed to the fid that was actually sent.

When writeback finally gives up on any of these errors, record -EIO for it instead, so that fsync(2) and close(2) don't return transient or internal errors such as -EAGAIN or -ERESTARTSYS.

Retry reopens as the read or write needing them gets retried: as above for writeback, otherwise per the hard and retrans mount options on replayable errors, with backoff and giving up on umount -f. If any channel of the session got reconnected meanwhile, retry once regardless, as the reconnect may be what failed the reopen; the next attempt waits for the reconnect to finish. Never retry reopens on interrupts or once the task is dying, so that dying tasks don't spin there; for writeback, issue the subrequest without credits instead, as done for dying tasks, so that it gets retried from the netfs collector, where no signals are pending.

Don't reopen for requests that predate a umount -f either, unless it is a first attempt on a connected server, as with issuing them. Once a reopen for writeback gives up, fail the other subrequests of the request right away, rather than each waiting out a retry window of its own.

Reopen handles for reads in prepare, before acquiring credits, as already done for writes, so that reads don't hold credits across a reopen. A read whose handle or credits went stale before it could be sent is retried regardless of mount options, after the backoff, so that prepare reopens and takes fresh credits; check a write's credits the same way.

Fixes 69c3c023af25 ("cifs: Implement netfslib hooks")
---
 fs/smb/client/cifsglob.h |   4 +
 fs/smb/client/cifssmb.c  |   6 +-
 fs/smb/client/file.c     | 207 ++++++++++++++++++++++++++++++++++-----
 3 files changed, 188 insertions(+), 29 deletions(-)
fs/smb/client/cifsglob.h +4 -0
index 064a2cdab4d9..09bde6a08dd7 100644
@@ -1458,6 +1458,7 @@ struct cifsFileInfo {
 	int count;
 	spinlock_t file_info_lock; /* protects four flag/count fields above */
 	struct mutex fh_mutex; /* prevents reopen race after dead ses*/
+	unsigned int reopens;
 	struct cifs_search_info srch_inf;
 	struct work_struct oplock_break; /* work for oplock breaks */
 	struct work_struct put; /* work for the final part of _put */
@@ -1483,6 +1484,8 @@ struct cifs_io_request {
 	struct cifsFileInfo		*cfile;
 	pid_t				pid;
 	int				umount_aborts;
+	bool				reopen_gave_up;
+	atomic_t			bad_reopens;	/* 0 or bad gen + 1 */
 };
 
 /* asynchronous read support */
@@ -1497,6 +1500,7 @@ struct cifs_io_subrequest {
 	int				result;
 	bool				have_xid;
 	bool				replay;
+	unsigned int			reopens;
 	unsigned int			retries;	/* number of retries so far */
 	unsigned int			cur_sleep;	/* time to sleep before replay */
 	unsigned long			retry_deadline;
fs/smb/client/cifssmb.c +4 -2
index 2936b38de98f..fcf97b3d6bea 100644
@@ -1939,12 +1939,14 @@ cifs_writev_callback(struct TCP_Server_Info *server, struct mid_q_entry *mid)
 		break;
 	case MID_REQUEST_SUBMITTED:
 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_req_submitted);
-		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+		if (wdata->rreq->origin != NETFS_WRITEBACK)
+			__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
 		result = -EAGAIN;
 		break;
 	case MID_RETRY_NEEDED:
 		trace_netfs_sreq(&wdata->subreq, netfs_sreq_trace_io_retry_needed);
-		__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
+		if (wdata->rreq->origin != NETFS_WRITEBACK)
+			__set_bit(NETFS_SREQ_NEED_RETRY, &wdata->subreq.flags);
 		result = -EAGAIN;
 		break;
 	case MID_RESPONSE_MALFORMED:
fs/smb/client/file.c +180 -27

294 lines not on this page · raw message

Signature · 1 line
2.56.0
author maintainer
#16 lore raw

PATCH v9 16/19 smb: client: let umount -f stop waiting for reconnects on hard mounts

In reply to Paulo Alcantara

Requests waiting in smb2_reconnect() or cifs_reconnect_tcon() for a reconnect wait for as long as it takes on hard mounts. With the server gone, writeback stuck there keeps umount -f hanging in sync_filesystem() while it waits for that writeback, even though retries of reads and writes started before it now give up.

Count umount -f attempts per tcon and stop waiting for reconnects, as on soft mounts, once one is made after the request started waiting, waking up such requests on all channels right away. Do this for the master tcon and for the per-user tcons of a multiuser mount, skipping tcons another mount still uses. Count the references mounts hold on a tcon for that, rather than relying on tc_count, which internal references such as a reconnect worker also raise: one per tlink in a superblock's tree, dropped when the tlink leaves it, and decide under the tree lock so that pruning or building a tlink can't skew it. Have a handle reopen started before umount -f stop short of a reconnect it would otherwise wait for afterwards. Requests started after umount -f are unaffected.

---
 fs/smb/client/cifsfs.c    | 118 +++++++++++++++++++++++++++-----------
 fs/smb/client/cifsglob.h  |   8 +++
 fs/smb/client/cifsproto.h |   4 +-
 fs/smb/client/cifssmb.c   |   9 ++-
 fs/smb/client/connect.c   |  69 ++++++++++++++++++----
 fs/smb/client/file.c      |  29 +++++++++-
 fs/smb/client/misc.c      |  16 +++++-
 fs/smb/client/smb2pdu.c   |   9 ++-
 8 files changed, 206 insertions(+), 56 deletions(-)
fs/smb/client/cifsfs.c +86 -32
index 7146bb22a69e..6a15c6a4fed2 100644
@@ -294,6 +294,61 @@ cifs_read_super(struct super_block *sb)
 	return rc;
 }
 
+struct cifs_tcon_ref {
+	struct list_head list;
+	struct tcon_link *tlink;
+	struct cifs_tcon *tcon;
+	bool shared;
+};
+
+static bool used_by_other_mounts(struct cifs_tcon *tcon,
+				 struct list_head *tcons)
+{
+	struct cifs_tcon_ref *ref;
+	int n = 0;
+
+	list_for_each_entry(ref, tcons, list)
+		n += ref->tcon == tcon;
+	guard(spinlock)(&tcon->tc_lock);
+	return tcon->mnt_refs - tcon->mnt_unlinked > n;
+}
+
+static void get_sb_tcons(struct cifs_sb_info *cifs_sb, struct list_head *tcons)
+{
+	struct rb_root *root = &cifs_sb->tlink_tree;
+	struct cifs_tcon_ref *ref;
+	struct tcon_link *tlink;
+	struct cifs_tcon *tcon;
+	struct rb_node *node;
+
+	guard(spinlock)(&cifs_sb->tlink_tree_lock);
+	for (node = rb_first(root); node; node = rb_next(node)) {
+		tlink = rb_entry(node, struct tcon_link, tl_rbnode);
+		tcon = tlink_tcon(tlink);
+		if (IS_ERR_OR_NULL(tcon))
+			continue;
+		ref = kmalloc_obj(struct cifs_tcon_ref, GFP_ATOMIC);
+		if (!ref)
+			break;
+		ref->tlink = cifs_get_tlink(tlink);
+		ref->tcon = tcon;
+		list_add_tail(&ref->list, tcons);
+	}
+	list_for_each_entry(ref, tcons, list)
+		ref->shared = used_by_other_mounts(ref->tcon, tcons);
+}
+
+static void put_sb_tcons(struct list_head *tcons)
+{
+	struct cifs_tcon_ref *ref, *tmp;
+
+	list_for_each_entry_safe(ref, tmp, tcons, list) {
+		cifs_put_tlink(ref->tlink);
+		list_del(&ref->list);
+		kfree(ref);
+	}
+}
+
 static void cifs_kill_sb(struct super_block *sb)
 {
 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
@@ -837,47 +892,46 @@ cifs_show_options(struct seq_file *s, struct dentry *root)
 	return 0;
 }
 
-static void cifs_umount_begin(struct super_block *sb)
+static void abort_reconnect(struct cifs_tcon *tcon)
 {
-	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
-	struct cifs_tcon *tcon;
-
-	if (cifs_sb == NULL)
-		return;
-
-	atomic_inc(&cifs_sb->umount_aborts);
-	tcon = cifs_sb_master_tcon(cifs_sb);
-
-	spin_lock(&cifs_tcp_ses_lock);
-	spin_lock(&tcon->tc_lock);
-	trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
-			    netfs_trace_tcon_ref_see_umount);
-	if ((tcon->tc_count > 1) || (tcon->status == TID_EXITING)) {
-		/* we have other mounts to same share or we have
-		   already tried to umount this and woken up
-		   all waiting network requests, nothing to do */
-		spin_unlock(&tcon->tc_lock);
-		spin_unlock(&cifs_tcp_ses_lock);
-		return;
-	}
-	/*
-	 * can not set tcon->status to TID_EXITING yet since we don't know if umount -f will
-	 * fail later (e.g. due to open files).  TID_EXITING will be set just before tdis req sent
-	 */
-	spin_unlock(&tcon->tc_lock);
-	spin_unlock(&cifs_tcp_ses_lock);
+	scoped_guard(spinlock, &tcon->tc_lock)
+		trace_smb3_tcon_ref(tcon->debug_id, tcon->tc_count,
+				    netfs_trace_tcon_ref_see_umount);
 
+	atomic_inc(&tcon->umount_aborts);
 	if (tcon->ses && tcon->ses->server) {
 		cifs_dbg(FYI, "wake up tasks now - umount begin not complete\n");
-		wake_up_all(&tcon->ses->server->request_q);
-		wake_up_all(&tcon->ses->server->response_q);
+		cifs_wake_ses_waiters(tcon->ses);
 		msleep(1); /* yield */
 		/* we have to kick the requests once more */
-		wake_up_all(&tcon->ses->server->response_q);
+		cifs_wake_ses_waiters(tcon->ses);
 		msleep(1);
 	}
+}
 
-	return;
+static void cifs_umount_begin(struct super_block *sb)
+{
+	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
+	struct cifs_tcon_ref *ref;
+	LIST_HEAD(tcons);
+
+	if (cifs_sb == NULL)
+		return;
+
+	atomic_inc(&cifs_sb->umount_aborts);
+
+	/*
+	 * Abort the reconnect waits of the master tcon and of any per-user
+	 * tcons of a multiuser mount that no other mount uses, pinning their
+	 * tlinks so that they stay alive, and aren't pruned, while we abort and
+	 * sleep outside the tree lock.
+	 */
+	get_sb_tcons(cifs_sb, &tcons);
+	list_for_each_entry(ref, &tcons, list) {
+		if (!ref->shared)
+			abort_reconnect(ref->tcon);
+	}
+	put_sb_tcons(&tcons);
 }
 
 static int cifs_freeze(struct super_block *sb)
fs/smb/client/cifsglob.h +8 -0
index 09bde6a08dd7..78ab6abe5297 100644
@@ -1196,6 +1196,9 @@ struct cifs_tcon {
 	struct list_head tcon_list;
 	int debug_id;		/* Debugging for tracing */
 	int tc_count;
+	int mnt_refs;		/* refs held by mounts, under tc_lock */
+	int mnt_unlinked;	/* mnt_refs of tlinks being built */
+	atomic_t umount_aborts;	/* nr of umount -f attempts */
 	struct list_head rlist; /* reconnect list */
 	spinlock_t tc_lock;  /* protect anything here that is not protected */
 	atomic_t num_local_opens;  /* num of all opens including disconnected */
@@ -2382,6 +2385,11 @@ static inline void cifs_reset_oplock(struct cifsInodeInfo *cinode)
 		WRITE_ONCE(cinode->oplock, 0);
 }
 
+static inline bool cifs_tcon_retry(struct cifs_tcon *tcon, int aborts)
+{
+	return tcon->retry && atomic_read(&tcon->umount_aborts) == aborts;
+}
+
 static inline bool cifs_forced_shutdown(const struct cifs_sb_info *sbi)
 {
 	return cifs_sb_flags(sbi) & CIFS_MOUNT_SHUTDOWN;
fs/smb/client/cifsproto.h +3 -1
index a37eee2ca54b..1b735a1c5b3d 100644
@@ -442,7 +442,9 @@ static inline int cifs_create_options(struct cifs_sb_info *cifs_sb, int options)
 		return options;
 }
 
-int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry);
+void cifs_wake_ses_waiters(struct cifs_ses *ses);
+int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server,
+				   struct cifs_tcon *tcon, int aborts);
 
 static inline void cifs_put_smb_ses(struct cifs_ses *ses)
 {
fs/smb/client/cifssmb.c +6 -3
index fcf97b3d6bea..712086eb3d1f 100644
@@ -73,6 +73,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
 {
 	struct TCP_Server_Info *server;
 	struct cifs_ses *ses;
+	int aborts;
 	int rc;
 
 	/*
@@ -83,6 +84,8 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
 	if (!tcon)
 		return 0;
 
+	aborts = atomic_read(&tcon->umount_aborts);
+
 	ses = tcon->ses;
 	server = ses->server;
 
@@ -102,7 +105,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
 	spin_unlock(&tcon->tc_lock);
 
 again:
-	rc = cifs_wait_for_server_reconnect(server, tcon->retry);
+	rc = cifs_wait_for_server_reconnect(server, tcon, aborts);
 	if (rc)
 		return rc;
 
@@ -127,7 +130,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
 	case CifsNeedReconnect:
 		spin_unlock(&server->srv_lock);
 		mutex_unlock(&ses->session_mutex);
-		if (!tcon->retry)
+		if (!cifs_tcon_retry(tcon, aborts))
 			return -EHOSTDOWN;
 		goto again;
 	default:
@@ -159,7 +162,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
 	rc = cifs_negotiate_protocol(0, ses, server);
 	if (rc) {
 		mutex_unlock(&ses->session_mutex);
-		if (!tcon->retry)
+		if (!cifs_tcon_retry(tcon, aborts))
 			return -EHOSTDOWN;
 		goto again;
 	}
fs/smb/client/connect.c +58 -11

150 lines not on this page · raw message

fs/smb/client/file.c +26 -3
index 904df549a884..7b8e1abd9b92 100644
@@ -1552,6 +1552,16 @@ cifs_relock_file(struct cifsFileInfo *cfile)
 	return rc;
 }
 
+static bool reopen_aborted(struct cifs_tcon *tcon, int aborts)
+{
+	struct TCP_Server_Info *server;
+
+	if (atomic_read(&tcon->umount_aborts) == aborts)
+		return false;
+	server = cifs_pick_channel(tcon->ses);
+	return server && READ_ONCE(server->tcpStatus) == CifsNeedReconnect;
+}
+
 static int
 cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush)
 {
@@ -1570,7 +1580,10 @@ cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush)
 	int create_options = CREATE_NOT_DIR;
 	struct cifs_open_parms oparms;
 	int rdwr_for_fscache = 0;
+	int aborts;
 
+	tcon = tlink_tcon(cfile->tlink);
+	aborts = atomic_read(&tcon->umount_aborts);
 	xid = get_xid();
 	mutex_lock(&cfile->fh_mutex);
 	if (!cfile->invalidHandle) {
@@ -1578,10 +1591,14 @@ cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush)
 		free_xid(xid);
 		return 0;
 	}
+	if (reopen_aborted(tcon, aborts)) {
+		mutex_unlock(&cfile->fh_mutex);
+		free_xid(xid);
+		return -EHOSTDOWN;
+	}
 
 	inode = d_inode(cfile->dentry);
 	cifs_sb = CIFS_SB(inode->i_sb);
-	tcon = tlink_tcon(cfile->tlink);
 	server = tcon->ses->server;
 
 	/*
@@ -1663,10 +1680,16 @@ cifs_reopen_file(struct cifsFileInfo *cfile, bool can_flush)
 	 * version of file size can be stale. If we knew for sure that inode was
 	 * not dirty locally we could do this.
 	 */
-	rc = server->ops->open(xid, &oparms, &oplock, NULL);
+	if (reopen_aborted(tcon, aborts))
+		rc = -EHOSTDOWN;
+	else
+		rc = server->ops->open(xid, &oparms, &oplock, NULL);
 	if (rc == -ENOENT && oparms.reconnect == false) {
 		/* durable handle timeout is expired - open the file again */
-		rc = server->ops->open(xid, &oparms, &oplock, NULL);
+		if (reopen_aborted(tcon, aborts))
+			rc = -EHOSTDOWN;
+		else
+			rc = server->ops->open(xid, &oparms, &oplock, NULL);
 		/* indicate that we need to relock the file */
 		oparms.reconnect = true;
 	}
fs/smb/client/misc.c +13 -3
index ec28f102ea08..13eb067ad88a 100644
@@ -1073,7 +1073,15 @@ int cifs_inval_name_dfs_link_error(const unsigned int xid,
 }
 #endif
 
-int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
+static bool reco_wait_done(struct TCP_Server_Info *server,
+			   struct cifs_tcon *tcon, int aborts)
+{
+	return server->tcpStatus != CifsNeedReconnect ||
+		atomic_read(&tcon->umount_aborts) != aborts;
+}
+
+int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server,
+				   struct cifs_tcon *tcon, int aborts)
 {
 	int timeout = 10;
 	int rc;
@@ -1096,7 +1104,9 @@ int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
 	 */
 	do {
 		rc = wait_event_interruptible_timeout(server->response_q,
-						      (server->tcpStatus != CifsNeedReconnect),
+						      reco_wait_done(server,
+								     tcon,
+								     aborts),
 						      timeout * HZ);
 		if (rc < 0) {
 			cifs_dbg(FYI, "%s: aborting reconnect due to received signal\n",
@@ -1111,7 +1121,7 @@ int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server, bool retry)
 			return 0;
 		}
 		spin_unlock(&server->srv_lock);
-	} while (retry);
+	} while (cifs_tcon_retry(tcon, aborts));
 
 	cifs_dbg(FYI, "%s: gave up waiting on reconnect\n", __func__);
 	return -EHOSTDOWN;
fs/smb/client/smb2pdu.c +6 -3
index bf22e7f6445d..b603e937d1a8 100644
@@ -251,6 +251,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
 	       struct TCP_Server_Info *server, bool from_reconnect)
 {
 	struct cifs_ses *ses;
+	int aborts;
 	int xid;
 	int rc = 0;
 
@@ -262,6 +263,8 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
 	if (tcon == NULL)
 		return 0;
 
+	aborts = atomic_read(&tcon->umount_aborts);
+
 	if (smb2_command == SMB2_TREE_CONNECT)
 		return 0;
 
@@ -318,7 +321,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
 	spin_unlock(&server->srv_lock);
 
 again:
-	rc = cifs_wait_for_server_reconnect(server, tcon->retry);
+	rc = cifs_wait_for_server_reconnect(server, tcon, aborts);
 	if (rc)
 		return rc;
 
@@ -346,7 +349,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
 	case CifsNeedReconnect:
 		spin_unlock(&server->srv_lock);
 		mutex_unlock(&ses->session_mutex);
-		if (!tcon->retry)
+		if (!cifs_tcon_retry(tcon, aborts))
 			return -EHOSTDOWN;
 		goto again;
 	default:
@@ -377,7 +380,7 @@ smb2_reconnect(__le16 smb2_command, struct cifs_tcon *tcon,
 	rc = cifs_negotiate_protocol(0, ses, server);
 	if (rc) {
 		mutex_unlock(&ses->session_mutex);
-		if (!tcon->retry)
+		if (!cifs_tcon_retry(tcon, aborts))
 			return -EHOSTDOWN;
 		goto again;
 	}
Signature · 1 line
2.56.0
author maintainer
#17 lore raw

PATCH v9 17/19 smb: client: don't replay handle reopens inside SMB2_open()

In reply to Paulo Alcantara

cifs_reopen_file_retry() reopens a read's or write's handle with backoff, per the hard and retrans mount options, giving up on umount -f. It calls cifs_reopen_file() -> SMB2_open(), which replays replayable errors on its own, also per hard and retrans. So each reopen is retried at both
layers: up to (retrans + 1)^2 opens on a soft mount, and, on a hard mount, forever inside SMB2_open() without ever returning to cifs_reopen_file_retry() to notice umount -f - a worker doing writeback then can't be stopped.

Have cifs_reopen_file_retry() tell SMB2_open() not to replay, so these reopens are bounded and stopped only by cifs_reopen_file_retry(). Other callers of cifs_reopen_file() keep SMB2_open()'s replay; SMB1 opens are unchanged.

A reopen reconnects the durable handle or, if the server lost it, opens the file afresh. Without SMB2_open()'s loop, a retry must open afresh again rather than reconnect, which the server would reject, and replay its last create, with the same GUID and access and keeping its access fallbacks, if that create may have been processed, or it leaks or loses a handle. Track both on the open
file under fh_mutex, so concurrent reopens agree: replay only after a create that SMB2_open() built and that failed with no answer from the server, and leave the state alone after an attempt that was interrupted or never built.

SMB2_open()'s own loop retried a failed durable reconnect as a fresh open with a stale GUID, and smb2_open_file()'s retry without FILE_READ_ATTRIBUTES as a fresh open, skipping the relock; have both reissue the same create, only replay a create that was built, and don't leave SMB2_open()'s own replay state behind for the caller's next create.

Fixes 69c3c023af25 ("cifs: Implement netfslib hooks")
Fixes 4f1fffa23769 ("cifs: commands that are retried should have replay flag set")
Fixes 79520587fe42 ("cifs: update the same create_guid on replay")
Fixes e255612b5ed9 ("cifs: Add fallback for SMB2 CREATE without FILE_READ_ATTRIBUTES")
---
 fs/smb/client/cifsglob.h |  5 +++++
 fs/smb/client/file.c     | 45 ++++++++++++++++++++++++++++++----------
 fs/smb/client/smb2file.c | 18 +++++++++++-----
 fs/smb/client/smb2pdu.c  | 37 +++++++++++++++++++++++++++++----
 4 files changed, 85 insertions(+), 20 deletions(-)
fs/smb/client/cifsglob.h +5 -0
index 78ab6abe5297..00a75bba42b0 100644
@@ -1410,6 +1410,8 @@ struct cifs_open_parms {
 	umode_t mode;
 	bool reconnect:1;
 	bool replay:1; /* indicates that this open is for a replay */
+	bool no_replay:1; /* don't replay this open internally */
+	bool pending:1; /* in/out: last built create had no answer */
 	struct kvec *ea_cctx;
 	__le32 lease_flags;
 };
@@ -1462,6 +1464,9 @@ struct cifsFileInfo {
 	spinlock_t file_info_lock; /* protects four flag/count fields above */
 	struct mutex fh_mutex; /* prevents reopen race after dead ses*/
 	unsigned int reopens;
+	bool reopen_fresh; /* durable handle gone: reopen opens afresh */
+	bool reopen_replay; /* reopen replays its last create */
+	int reopen_access; /* desired access of that create */
 	struct cifs_search_info srch_inf;
 	struct work_struct oplock_break; /* work for oplock breaks */
 	struct work_struct put; /* work for the final part of _put */
fs/smb/client/file.c +34 -11

112 lines not on this page · raw message

fs/smb/client/smb2file.c +13 -5
index fb2fccbe8667..764cfd894ad0 100644
@@ -175,6 +175,7 @@ int smb2_open_file(const unsigned int xid, struct cifs_open_parms *oparms,
 	struct cifs_fid *fid = oparms->fid;
 	struct network_resiliency_req nr_ioctl_req;
 	bool retry_without_read_attributes = false;
+	bool reconnect = oparms->reconnect;
 
 	smb2_path = cifs_convert_path_to_utf16(oparms->path, oparms->cifs_sb);
 	if (smb2_path == NULL)
@@ -186,23 +187,30 @@ int smb2_open_file(const unsigned int xid, struct cifs_open_parms *oparms,
 	 * FILE_READ_ATTRIBUTES when not needed and prevent calling code path
 	 * for retry_without_read_attributes.
 	 */
-	if (!(oparms->desired_access & FILE_READ_ATTRIBUTES) &&
-	    !(oparms->desired_access & GENERIC_READ) &&
+	if (!(oparms->desired_access & GENERIC_READ) &&
 	    !(oparms->desired_access & GENERIC_EXECUTE) &&
 	    !(oparms->desired_access & GENERIC_ALL) &&
 	    !(oparms->desired_access & MAXIMUM_ALLOWED)) {
-		oparms->desired_access |= FILE_READ_ATTRIBUTES;
-		retry_without_read_attributes = true;
+		if (oparms->replay) {
+			retry_without_read_attributes =
+				oparms->desired_access & FILE_READ_ATTRIBUTES;
+		} else if (!(oparms->desired_access & FILE_READ_ATTRIBUTES)) {
+			oparms->desired_access |= FILE_READ_ATTRIBUTES;
+			retry_without_read_attributes = true;
+		}
 	}
 	smb2_oplock = SMB2_OPLOCK_LEVEL_BATCH;
 
 	rc = SMB2_open(xid, oparms, smb2_path, &smb2_oplock, data, NULL, &err_iov,
 		       &err_buftype);
-	if (rc == -EACCES && retry_without_read_attributes) {
+	if (rc == -EACCES && retry_without_read_attributes &&
+	    !oparms->pending) {
 		free_rsp_buf(err_buftype, err_iov.iov_base);
 		memset(&err_iov, 0, sizeof(err_iov));
 		err_buftype = CIFS_NO_BUFFER;
 		oparms->desired_access &= ~FILE_READ_ATTRIBUTES;
+		oparms->reconnect = reconnect;
+		oparms->replay = false;
 		rc = SMB2_open(xid, oparms, smb2_path, &smb2_oplock, data, NULL, &err_iov,
 			       &err_buftype);
 	}
fs/smb/client/smb2pdu.c +33 -4
index b603e937d1a8..d86ec1c75fbb 100644
@@ -3332,14 +3332,25 @@ SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
 	int flags = 0;
 	int retries = 0, cur_sleep = 0;
 	struct smb2_file_all_info *file_info = buf ? &buf->fi : NULL;
+	bool reconnect = oparms->reconnect;
+	bool replay = oparms->replay;
+	bool unanswered = replay;
+	bool answered;
+	bool sent;
 
 replay_again:
 	/* reinitialize for possible replay */
+	answered = false;
+	sent = false;
 	resp_buftype = CIFS_NO_BUFFER;
 	memset(&rsp_iov, 0, sizeof(rsp_iov));
 	flags = 0;
 	server = cifs_pick_channel(ses);
-	oparms->replay = !!(retries);
+	/* reissue the same create: a durable reconnect clears ->reconnect */
+	oparms->reconnect = reconnect;
+	/* with no_replay the caller owns oparms->replay */
+	if (!oparms->no_replay)
+		oparms->replay = unanswered;
 
 	cifs_dbg(FYI, "create/open\n");
 	if (!ses || !server)
@@ -3357,11 +3368,12 @@ SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
 			    &rqst, oplock, oparms, path);
 	if (rc)
 		goto creat_exit;
+	sent = true;
 
 	trace_smb3_open_enter(xid, tcon->tid, tcon->ses->Suid, oparms->path,
 		oparms->create_options, oparms->desired_access);
 
-	if (retries) {
+	if (oparms->replay) {
 		/* Back-off before retry */
 		if (cur_sleep)
 			msleep(cur_sleep);
@@ -3372,6 +3384,7 @@ SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
 			    &rqst, &resp_buftype, flags,
 			    &rsp_iov);
 	rsp = (struct smb2_create_rsp *)rsp_iov.iov_base;
+	answered = rsp;
 
 	if (rc != 0) {
 		cifs_stats_fail_inc(tcon, SMB2_CREATE_HE);
@@ -3428,10 +3441,26 @@ SMB2_open(const unsigned int xid, struct cifs_open_parms *oparms, __le16 *path,
 	SMB2_open_free(&rqst);
 	free_rsp_buf(resp_buftype, rsp);
 
-	if (is_replayable_error(rc) &&
-	    smb2_should_replay(tcon, &retries, &cur_sleep))
+	if (sent) {
+		if (!rc || answered)
+			unanswered = false;
+		else if (!is_interrupt_error(rc))
+			unanswered = true;
+		oparms->pending = unanswered;
+	}
+
+	if (!oparms->no_replay && is_replayable_error(rc) &&
+	    smb2_should_replay(tcon, &retries, &cur_sleep)) {
+		if (err_iov && answered && !rsp) {
+			free_rsp_buf(*buftype, err_iov->iov_base);
+			*err_iov = (struct kvec){};
+			*buftype = CIFS_NO_BUFFER;
+		}
 		goto replay_again;
+	}
 
+	if (!oparms->no_replay)
+		oparms->replay = replay;
 	return rc;
 }
 
Signature · 1 line
2.56.0
author maintainer
#18 lore raw

PATCH v9 18/19 smb: client: fail writeback sends and reopens fast when the server is gone

In reply to Paulo Alcantara

A writeback whose send or handle reopen finds the server needing reconnect waits in smb2_reconnect() -> cifs_wait_for_server_reconnect() for the reconnect to finish - on a hard mount until the server returns or umount -f. But umount -f only breaks that wait for a request that entered it before the abort count was bumped; a send or reopen that enters afterwards, including the writeback that generic_shutdown_super() -> sync_filesystem() starts during the unmount itself, snapshots the already-bumped count and waits forever, hanging the unmount.

Issue writeback sends and reopens without waiting for the reconnect: pass a nowait flag down to smb2_reconnect() and have it return -EAGAIN from every point it would otherwise wait in or loop back to cifs_wait_for_server_reconnect() - the initial need-reconnect check, the wait itself, a need-reconnect seen after taking the session mutex, and a failed renegotiation - not just the first. The subrequest is then retried from the netfs collector, which backs off and re-checks umount -f and the retry window before trying again. Reads, direct writes and every other command keep waiting as before.

Writeback started between umount_begin() and cifs_kill_sb() can also block the unmount from the flusher, which holds s_umount: in the reopen retry loop, or in a credit wait, as credits only come back with a reconnect. Defer writeback reopens to the worker, and fail writeback credit waits with -EAGAIN while the connection needs reconnecting, waking the waiters when it drops, so both get retried from the netfs collector. Have only one subrequest of a request reopen per pass, the others waiting for it and sharing its outcome, fail them right away once reopening failed for good, back off before queueing once per pass rather than per subrequest, and never block the flusher or the worker on fh_mutex, which a reader stuck reconnecting may hold, so that a dead mount can't tie up the shared worker for the other mounts, nor the collector or the flusher. Let the pieces a
retry re-slices keep the retry state of the span they come from, and make the reopen's own credit wait fail fast as well.

Fixes 3ee1a1fc3981 ("cifs: Cut over to using netfslib")
---
 fs/smb/client/cifsglob.h  |  20 +++-
 fs/smb/client/cifsproto.h |   6 +-
 fs/smb/client/cifssmb.c   |   2 +-
 fs/smb/client/connect.c   |   1 +
 fs/smb/client/file.c      | 245 +++++++++++++++++++++++++++++++-------
 fs/smb/client/misc.c      |   7 +-
 fs/smb/client/smb2ops.c   |   9 +-
 fs/smb/client/smb2pdu.c   |  55 +++++++--
 fs/smb/client/transport.c |  22 +++-
 9 files changed, 304 insertions(+), 63 deletions(-)
fs/smb/client/cifsglob.h +19 -1
index 00a75bba42b0..0b66f2c9c9a9 100644
@@ -585,7 +585,7 @@ struct smb_version_operations {
 	unsigned int (*wp_retry_size)(struct inode *);
 	/* get mtu credits */
 	int (*wait_mtu_credits)(struct TCP_Server_Info *, size_t,
-				size_t *, struct cifs_credits *);
+				size_t *, struct cifs_credits *, bool nowait);
 	/* adjust previously taken mtu credits to request size */
 	int (*adjust_credits)(struct TCP_Server_Info *server,
 			      struct cifs_io_subrequest *subreq,
@@ -887,6 +887,14 @@ has_credits(struct TCP_Server_Info *server, int *credits, int num_credits)
 	return num >= num_credits;
 }
 
+static inline bool
+credits_or_conn_down(struct TCP_Server_Info *server, int *credits,
+		     int num_credits, bool nowait)
+{
+	return has_credits(server, credits, num_credits) ||
+	       (nowait && READ_ONCE(server->tcpStatus) == CifsNeedReconnect);
+}
+
 static inline void
 add_credits(struct TCP_Server_Info *server, struct cifs_credits *credits,
 	    const int optype)
@@ -1412,6 +1420,7 @@ struct cifs_open_parms {
 	bool replay:1; /* indicates that this open is for a replay */
 	bool no_replay:1; /* don't replay this open internally */
 	bool pending:1; /* in/out: last built create had no answer */
+	bool no_reconnect_wait:1; /* fail fast, don't wait for reconnect */
 	struct kvec *ea_cctx;
 	__le32 lease_flags;
 };
@@ -1493,7 +1502,14 @@ struct cifs_io_request {
 	pid_t				pid;
 	int				umount_aborts;
 	bool				reopen_gave_up;
+	bool				replay;
 	atomic_t			bad_reopens;	/* 0 or bad gen + 1 */
+	int				reopen_err;
+	int				reopen_pass_err;
+	struct mutex			reopen_lock;	/* serializes reopens */
+	unsigned long			retry_deadline;
+	unsigned int			cur_sleep;
+	unsigned int			slept;
 };
 
 /* asynchronous read support */
@@ -1508,6 +1524,7 @@ struct cifs_io_subrequest {
 	int				result;
 	bool				have_xid;
 	bool				replay;
+	bool				deferred;	/* issue in a worker */
 	unsigned int			reopens;
 	unsigned int			retries;	/* number of retries so far */
 	unsigned int			cur_sleep;	/* time to sleep before replay */
@@ -1949,6 +1966,7 @@ enum cifs_find_flags {
 #define   CIFS_COMPRESS_REQ       0x4000 /* compress request before sending */
 #define   CIFS_INTERRUPTIBLE_WAIT 0x8000 /* Interruptible wait (e.g. lock request) */
 #define   CIFS_WINDOWS_LOCK       0x10000 /* We're trying to get a Windows lock */
+#define   CIFS_NO_RECONNECT_WAIT  0x20000 /* don't wait if conn is down */
 
 /* Security Flags: indicate type of session setup needed */
 #define   CIFSSEC_MAY_SIGN	0x00001
fs/smb/client/cifsproto.h +4 -2
index 1b735a1c5b3d..b7a7fe372d47 100644
@@ -112,7 +112,8 @@ int __smb_send_rqst(struct TCP_Server_Info *server, int num_rqst,
 int wait_for_free_request(struct TCP_Server_Info *server, const int flags,
 			  unsigned int *instance);
 int cifs_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
-			  size_t *num, struct cifs_credits *credits);
+			  size_t *num, struct cifs_credits *credits,
+			  bool nowait);
 
 static inline int
 send_cancel(struct cifs_ses *ses, struct TCP_Server_Info *server,
@@ -444,7 +445,8 @@ static inline int cifs_create_options(struct cifs_sb_info *cifs_sb, int options)
 
 void cifs_wake_ses_waiters(struct cifs_ses *ses);
 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server,
-				   struct cifs_tcon *tcon, int aborts);
+				   struct cifs_tcon *tcon, int aborts,
+				   bool nowait);
 
 static inline void cifs_put_smb_ses(struct cifs_ses *ses)
 {
fs/smb/client/cifssmb.c +1 -1
index 712086eb3d1f..68f05a52605f 100644
@@ -105,7 +105,7 @@ cifs_reconnect_tcon(struct cifs_tcon *tcon, int smb_command)
 	spin_unlock(&tcon->tc_lock);
 
 again:
-	rc = cifs_wait_for_server_reconnect(server, tcon, aborts);
+	rc = cifs_wait_for_server_reconnect(server, tcon, aborts, false);
 	if (rc)
 		return rc;
 
fs/smb/client/connect.c +1 -0
index 16cfe73acdd3..803cefc61194 100644
@@ -352,6 +352,7 @@ cifs_abort_connection(struct TCP_Server_Info *server)
 		mid_execute_callback(server, mid);
 		release_mid(server, mid);
 	}
+	wake_up_all(&server->request_q);
 }
 
 static bool cifs_tcp_ses_needs_reconnect(struct TCP_Server_Info *server, int num_targets)
fs/smb/client/file.c +202 -43

375 lines not on this page · raw message

fs/smb/client/misc.c +6 -1
index 13eb067ad88a..4a3ecf5c80f7 100644
@@ -1081,7 +1081,8 @@ static bool reco_wait_done(struct TCP_Server_Info *server,
 }
 
 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server,
-				   struct cifs_tcon *tcon, int aborts)
+				   struct cifs_tcon *tcon, int aborts,
+				   bool nowait)
 {
 	int timeout = 10;
 	int rc;
@@ -1091,6 +1092,10 @@ int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server,
 		spin_unlock(&server->srv_lock);
 		return 0;
 	}
+	if (nowait) {
+		spin_unlock(&server->srv_lock);
+		return -EAGAIN;
+	}
 	timeout *= server->nr_targets;
 	spin_unlock(&server->srv_lock);
 
fs/smb/client/smb2ops.c +7 -2
index 457f18ce3245..0a487b24f4e7 100644
@@ -244,7 +244,7 @@ smb2_get_credits(struct mid_q_entry *mid)
 
 static int
 smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
-		      size_t *num, struct cifs_credits *credits)
+		      size_t *num, struct cifs_credits *credits, bool nowait)
 {
 	int rc = 0;
 	unsigned int scredits, in_flight;
@@ -258,6 +258,10 @@ smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
 			spin_unlock(&server->srv_lock);
 			return -ENOENT;
 		}
+		if (nowait && server->tcpStatus == CifsNeedReconnect) {
+			spin_unlock(&server->srv_lock);
+			return -EAGAIN;
+		}
 		spin_unlock(&server->srv_lock);
 
 		spin_lock(&server->req_lock);
@@ -265,7 +269,8 @@ smb2_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
 			spin_unlock(&server->req_lock);
 			cifs_num_waiters_inc(server);
 			rc = wait_event_killable(server->request_q,
-				has_credits(server, &server->credits, 1));
+				credits_or_conn_down(server, &server->credits,
+						     1, nowait));
 			cifs_num_waiters_dec(server);
 			if (rc)
 				return rc;
fs/smb/client/smb2pdu.c +46 -9

121 lines not on this page · raw message

fs/smb/client/transport.c +18 -4
index d0d0159c1061..c51f99d7be4b 100644
@@ -430,6 +430,7 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits,
 		      const int timeout, const int flags,
 		      unsigned int *instance)
 {
+	bool nowait = flags & CIFS_NO_RECONNECT_WAIT;
 	long rc;
 	int *credits;
 	int optype;
@@ -478,6 +479,10 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits,
 			spin_unlock(&server->srv_lock);
 			return -ENOENT;
 		}
+		if (nowait && server->tcpStatus == CifsNeedReconnect) {
+			spin_unlock(&server->srv_lock);
+			return -EAGAIN;
+		}
 		spin_unlock(&server->srv_lock);
 
 		spin_lock(&server->req_lock);
@@ -487,7 +492,8 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits,
 
 			cifs_num_waiters_inc(server);
 			rc = wait_event_killable_timeout(server->request_q,
-				has_credits(server, credits, num_credits), t);
+				credits_or_conn_down(server, credits,
+						     num_credits, nowait), t);
 			cifs_num_waiters_dec(server);
 			if (!rc) {
 				spin_lock(&server->req_lock);
@@ -527,8 +533,9 @@ wait_for_free_credits(struct TCP_Server_Info *server, const int num_credits,
 				cifs_num_waiters_inc(server);
 				rc = wait_event_killable_timeout(
 					server->request_q,
-					has_credits(server, credits,
-						    MAX_COMPOUND + 1),
+					credits_or_conn_down(server, credits,
+							     MAX_COMPOUND + 1,
+							     nowait),
 					t);
 				cifs_num_waiters_dec(server);
 				if (!rc) {
@@ -595,6 +602,10 @@ wait_for_compound_request(struct TCP_Server_Info *server, int num,
 
 	credits = server->ops->get_credits_field(server, flags & CIFS_OP_MASK);
 
+	if ((flags & CIFS_NO_RECONNECT_WAIT) &&
+	    READ_ONCE(server->tcpStatus) == CifsNeedReconnect)
+		return -EAGAIN;
+
 	spin_lock(&server->req_lock);
 	scredits = *credits;
 	in_flight = server->in_flight;
@@ -618,6 +629,9 @@ wait_for_compound_request(struct TCP_Server_Info *server, int num,
 		 */
 		if (server->in_flight == 0) {
 			spin_unlock(&server->req_lock);
+			if ((flags & CIFS_NO_RECONNECT_WAIT) &&
+			    READ_ONCE(server->tcpStatus) == CifsNeedReconnect)
+				return -EAGAIN;
 			trace_smb3_insufficient_credits(server->current_mid,
 					server->conn_id, server->hostname, scredits,
 					num, in_flight);
@@ -634,7 +648,7 @@ wait_for_compound_request(struct TCP_Server_Info *server, int num,
 
 int
 cifs_wait_mtu_credits(struct TCP_Server_Info *server, size_t size,
-		      size_t *num, struct cifs_credits *credits)
+		      size_t *num, struct cifs_credits *credits, bool nowait)
 {
 	*num = size;
 	credits->value = 0;
Signature · 1 line
2.56.0
author maintainer
#19 lore raw

PATCH v9 19/19 smb: client: stop reconnecting and replaying during a forced unmount

In reply to Paulo Alcantara

umount -f of a gone server on a hard mount hangs the teardown. cifs_kill_sb() flushes the deferred-file, cached-dir and oplock-break work and then cifs_umount() sends a tree disconnect, but on a hard mount every reconnect wait in cifs_wait_for_server_reconnect() and every per-PDU replay loop (gated by smb2_should_replay()) retries forever, and the per-tcon abort count that umount -f bumps is only snapshotted on entry to smb2_reconnect(), so an operation that enters after the unmount began never observes it and waits or spins out the teardown (e.g. a close work item wedging flush_workqueue()).

Mark each of the mount's tcons dying, master and per-user alike, waking their sessions' waiters, and have cifs_wait_for_server_reconnect(), cifs_tcon_retry() and smb2_should_replay() give up while it is set, so both the reconnect waits and the replay loops stop at every site, however late the operation entered. Keep it set, with the mount's tlinks pinned, until cifs_umount() has dropped them, then drop it on those tcons that another superblock still holds, and hand no dying tcon to a new mount. Also treat a tcon that no mount references any more as dying, waking its waiters when that happens, so that whatever still holds it (e.g. the cached directory laundromat, a cancelled close, or its tree disconnect after cifs_prune_tlinks()) stops too, and never reuse it.

Also stop the reconnect worker from wedging: smb2_reconnect_server() holds a tcon or session reference across cifs_wait_for_server_reconnect(), so with the server gone it never returns, pinning the cifsiod worker and leaking the tcon, session, server and cifsd thread. It only needs to attempt the reconnect, so fail fast; it is retried once the transport is back. Reopen persistent handles from it once, without waiting, and reschedule it if one failed for a transient reason.

Reads, metadata and SMB1 reconnect waits outside teardown still follow the hard and retrans mount options, except on a tcon shared with another mount, whose waits and replays give up too while the teardown runs; a task blocked in one can be killed, and open files keep umount -f from reaching teardown (-EBUSY).

---
 fs/smb/client/cifsfs.c    | 44 ++++++++++++++++++++++++++++++++++++++-
 fs/smb/client/cifsglob.h  | 10 ++++++++-
 fs/smb/client/cifsproto.h |  2 +-
 fs/smb/client/connect.c   |  9 +++++---
 fs/smb/client/file.c      | 13 +++++++++---
 fs/smb/client/misc.c      |  3 ++-
 fs/smb/client/smb2ops.c   |  4 ++++
 fs/smb/client/smb2pdu.c   |  7 ++++---
 8 files changed, 79 insertions(+), 13 deletions(-)
fs/smb/client/cifsfs.c +43 -1
index 6a15c6a4fed2..7000fb4573c9 100644
@@ -349,9 +349,46 @@ static void put_sb_tcons(struct list_head *tcons)
 	}
 }
 
+/*
+ * While a forced unmount tears a superblock down, keep its tcons from
+ * reconnecting or replaying so the teardown (flushing close and oplock work,
+ * sending the tree disconnect) can't hang on a server that is gone.  It is a
+ * count, not a flag, so a tcon shared with another mount only has its retries
+ * suppressed for the duration of this teardown; one no mount uses any more
+ * stays dying until it is freed.
+ */
+static void set_tcons_dying(struct cifs_sb_info *cifs_sb,
+			    struct list_head *tcons)
+{
+	struct cifs_tcon_ref *ref;
+
+	get_sb_tcons(cifs_sb, tcons);
+	list_for_each_entry(ref, tcons, list) {
+		atomic_inc(&ref->tcon->dying);
+		cifs_wake_ses_waiters(ref->tcon->ses);
+	}
+}
+
+static void clear_tcons_dying(struct list_head *tcons)
+{
+	struct cifs_tcon_ref *ref;
+
+	flush_workqueue(serverclose_wq);
+	list_for_each_entry(ref, tcons, list) {
+		guard(spinlock)(&ref->tcon->tc_lock);
+		if (ref->tcon->mnt_refs)
+			atomic_dec(&ref->tcon->dying);
+	}
+	put_sb_tcons(tcons);
+}
+
 static void cifs_kill_sb(struct super_block *sb)
 {
 	struct cifs_sb_info *cifs_sb = CIFS_SB(sb);
+	LIST_HEAD(tcons);
+	bool force;
+
+	force = atomic_read(&cifs_sb->umount_aborts);
 
 	/*
 	 * Reaching here after a umount -f means the mount is going away for
@@ -359,8 +396,10 @@ static void cifs_kill_sb(struct super_block *sb)
 	 * writeback to a server that is gone) rather than looping forever on
 	 * a hard mount and hanging the teardown below.
 	 */
-	if (atomic_read(&cifs_sb->umount_aborts))
+	if (force) {
 		WRITE_ONCE(cifs_sb->exiting, true);
+		set_tcons_dying(cifs_sb, &tcons);
+	}
 
 	/*
 	 * We need to release all dentries for the cached directories
@@ -394,6 +433,9 @@ static void cifs_kill_sb(struct super_block *sb)
 
 	kill_anon_super(sb);
 	cifs_umount(cifs_sb);
+
+	if (force)
+		clear_tcons_dying(&tcons);
 }
 
 static int
fs/smb/client/cifsglob.h +9 -1
index 0b66f2c9c9a9..4e16347886ed 100644
@@ -1207,6 +1207,7 @@ struct cifs_tcon {
 	int mnt_refs;		/* refs held by mounts, under tc_lock */
 	int mnt_unlinked;	/* mnt_refs of tlinks being built */
 	atomic_t umount_aborts;	/* nr of umount -f attempts */
+	atomic_t dying;		/* umount -f: stop reconnects/replays */
 	struct list_head rlist; /* reconnect list */
 	spinlock_t tc_lock;  /* protect anything here that is not protected */
 	atomic_t num_local_opens;  /* num of all opens including disconnected */
@@ -2408,9 +2409,16 @@ static inline void cifs_reset_oplock(struct cifsInodeInfo *cinode)
 		WRITE_ONCE(cinode->oplock, 0);
 }
 
+static inline bool cifs_tcon_dying(struct cifs_tcon *tcon)
+{
+	return atomic_read(&tcon->dying) ||
+	       (!tcon->ipc && !tcon->dummy && !READ_ONCE(tcon->mnt_refs));
+}
+
 static inline bool cifs_tcon_retry(struct cifs_tcon *tcon, int aborts)
 {
-	return tcon->retry && atomic_read(&tcon->umount_aborts) == aborts;
+	return tcon->retry && atomic_read(&tcon->umount_aborts) == aborts &&
+	       !cifs_tcon_dying(tcon);
 }
 
 static inline bool cifs_forced_shutdown(const struct cifs_sb_info *sbi)
fs/smb/client/cifsproto.h +1 -1
index b7a7fe372d47..15123c7b9373 100644
@@ -244,7 +244,7 @@ int cifs_match_super(struct super_block *sb, struct fs_context *fc);
 int cifs_mount(struct cifs_sb_info *cifs_sb, struct smb3_fs_context *ctx);
 void cifs_umount(struct cifs_sb_info *cifs_sb);
 void cifs_mark_open_files_invalid(struct cifs_tcon *tcon);
-void cifs_reopen_persistent_handles(struct cifs_tcon *tcon);
+bool cifs_reopen_persistent_handles(struct cifs_tcon *tcon);
 
 bool cifs_find_lock_conflict(struct cifsFileInfo *cfile, __u64 offset,
 			     __u64 length, __u8 type, __u16 flags,
fs/smb/client/connect.c +6 -3
index 803cefc61194..900846533d48 100644
@@ -2619,7 +2619,7 @@ cifs_find_tcon(struct cifs_ses *ses, struct smb3_fs_context *ctx,
 	spin_lock(&cifs_tcp_ses_lock);
 	list_for_each_entry(tcon, &ses->tcon_list, tcon_list) {
 		spin_lock(&tcon->tc_lock);
-		if (!match_tcon(tcon, ctx)) {
+		if (!match_tcon(tcon, ctx) || cifs_tcon_dying(tcon)) {
 			spin_unlock(&tcon->tc_lock);
 			continue;
 		}
@@ -2714,8 +2714,11 @@ void cifs_wake_ses_waiters(struct cifs_ses *ses)
 
 static void drop_mnt_ref(struct cifs_tcon *tcon)
 {
-	guard(spinlock)(&tcon->tc_lock);
-	tcon->mnt_refs--;
+	scoped_guard(spinlock, &tcon->tc_lock) {
+		if (--tcon->mnt_refs)
+			return;
+	}
+	cifs_wake_ses_waiters(tcon->ses);
 }
 
 static void put_mnt_tcon(struct cifs_tcon *tcon, enum smb3_tcon_ref_trace trace)
fs/smb/client/file.c +10 -3
index 84125f9a43a4..d5b7d33a7a37 100644
@@ -2030,14 +2030,16 @@ int cifs_close(struct inode *inode, struct file *file)
 	return 0;
 }
 
-void
+bool
 cifs_reopen_persistent_handles(struct cifs_tcon *tcon)
 {
 	struct cifsFileInfo *open_file, *tmp;
 	LIST_HEAD(tmp_list);
+	bool retry = false;
+	int rc;
 
 	if (!tcon->use_persistent || !tcon->need_reopen_files)
-		return;
+		return false;
 
 	tcon->need_reopen_files = false;
 
@@ -2055,11 +2057,16 @@ cifs_reopen_persistent_handles(struct cifs_tcon *tcon)
 
 	list_for_each_entry_safe(open_file, tmp, &tmp_list, rlist) {
 		/* do not flush */
-		if (cifs_reopen_file(open_file, false, 0))
+		rc = cifs_reopen_file(open_file, false,
+				      CIFS_REOPEN_BOUND | CIFS_REOPEN_NOWAIT);
+		if (rc) {
 			tcon->need_reopen_files = true;
+			retry |= is_replayable_error(rc);
+		}
 		list_del_init(&open_file->rlist);
 		cifsFileInfo_put(open_file);
 	}
+	return retry;
 }
 
 int cifs_closedir(struct inode *inode, struct file *file)
fs/smb/client/misc.c +2 -1
index 4a3ecf5c80f7..4d0df73d15d7 100644
@@ -1077,7 +1077,8 @@ static bool reco_wait_done(struct TCP_Server_Info *server,
 			   struct cifs_tcon *tcon, int aborts)
 {
 	return server->tcpStatus != CifsNeedReconnect ||
-		atomic_read(&tcon->umount_aborts) != aborts;
+		atomic_read(&tcon->umount_aborts) != aborts ||
+		cifs_tcon_dying(tcon);
 }
 
 int cifs_wait_for_server_reconnect(struct TCP_Server_Info *server,
fs/smb/client/smb2ops.c +4 -0
index 0a487b24f4e7..298f549bd7ed 100644
@@ -2938,6 +2938,10 @@ bool smb2_should_replay(struct cifs_tcon *tcon,
 	if (!pretries || !pcur_sleep)
 		return false;
 
+	/* the tcon is being torn down; stop replaying */
+	if (cifs_tcon_dying(tcon))
+		return false;
+
 	if (tcon->retry || (*pretries)++ < tcon->ses->server->retrans) {
 		smb2_replay_backoff(pcur_sleep);
 		return true;
fs/smb/client/smb2pdu.c +4 -3
index 099fd94c58a4..20e6b948ba21 100644
@@ -4417,10 +4417,11 @@ void smb2_reconnect_server(struct work_struct *work)
 
 	list_for_each_entry_safe(tcon, tcon2, &tmp_list, rlist) {
 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true,
-				    false);
+				    true);
 		if (!rc) {
 			cifs_renegotiate_iosize(server, tcon);
-			cifs_reopen_persistent_handles(tcon);
+			if (cifs_reopen_persistent_handles(tcon))
+				resched = true;
 		} else
 			resched = true;
 		list_del_init(&tcon->rlist);
@@ -4450,7 +4451,7 @@ void smb2_reconnect_server(struct work_struct *work)
 	list_for_each_entry_safe(ses, ses2, &tmp_ses_list, rlist) {
 		tcon->ses = ses;
 		rc = smb2_reconnect(SMB2_INTERNAL_CMD, tcon, server, true,
-				    false);
+				    true);
 		if (rc)
 			resched = true;
 		list_del_init(&ses->rlist);
Signature · 1 line
2.56.0