Skip to contentSkip to conversation

smb/client: fix fallocate range operation issues

PATCH Applied Huiwen He 3 participants 18 messages Aug 23 – Aug 28

Subsystems (2)

v3 of 4 Applied Latest is v4 →

lore
Share & tools
lore
author
#1 lore raw

PATCH v3 1/7 smb/client: validate new EOF for insert range

In reply to Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() does not check if the new file size (i_size + len) is valid. This allows FALLOC_FL_INSERT_RANGE to bypass RLIMIT_FSIZE, exceed s_maxbytes, or produce a size outside the loff_t range.

Use check_add_overflow() to calculate the new EOF. Validate it with inode_newsize_ok() before modifying the file.

Reproducer, using a file on a CIFS mount:

bash -c '
FILE=/mnt/cifs/repro

trap "" SIGXFSZ
ulimit -f 3072 # RLIMIT_FSIZE = 3 MiB

# A regular write is stopped at 3 MiB.
dd if=/dev/zero of="$FILE" bs=1M count=4 status=none stat -c "size after write: %s" "$FILE"

# Insert 2 MiB into a 2 MiB file. truncate -s 2M "$FILE" fallocate -i -o 0 -l 2M "$FILE" stat -c "size after insert: %s" "$FILE"
'

Before this change, the regular write stops at the 3 MiB limit, but insert range grows the file to 4 MiB:

	dd: error writing '/mnt/cifs/repro': File too large
	size after write: 3145728
	size after insert: 4194304

After this change, insert range also fails at the limit and leaves the 2 MiB file unchanged:

	dd: error writing '/mnt/cifs/repro': File too large
	size after write: 3145728
	fallocate: fallocate failed: File too large
	size after insert: 2097152
Fixes 7fe6fe95b936 ("cifs: add FALLOC_FL_INSERT_RANGE support")
---
 fs/smb/client/smb2ops.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
fs/smb/client/smb2ops.c +10 -2
index 192649fec25d..bc7dda6d825a 100644
@@ -3985,7 +3985,8 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 	struct cifsFileInfo *cfile = file->private_data;
 	struct inode *inode = file_inode(file);
 	struct cifsInodeInfo *cifsi = CIFS_I(inode);
-	__u64 count, old_eof, new_eof;
+	u64 count;
+	loff_t old_eof, new_eof;
 
 	xid = get_xid();
 
@@ -3995,8 +3996,15 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 		goto out;
 	}
 
+	if (check_add_overflow(old_eof, len, &new_eof)) {
+		rc = -EFBIG;
+		goto out;
+	}
+	rc = inode_newsize_ok(inode, new_eof);
+	if (rc)
+		goto out;
+
 	count = old_eof - off;
-	new_eof = old_eof + len;
 
 	filemap_invalidate_lock(inode->i_mapping);
 	rc = filemap_write_and_wait_range(inode->i_mapping, off, new_eof - 1);
Signature · 1 line
2.43.0

Huiwen He

author
#0 lore raw

v3 cover smb/client: fix fallocate range operation issues

From: Huiwen He <[email protected]>

This series fixes several issues in SMB3 fallocate range operations, including insert range, collapse range, zero range, and punch hole.

Changes in v3:

- Update patch 6 to use page-aligned truncate_pagecache_range() instead of invalidate_inode_pages2_range(), avoiding possible -EBUSY failures.
- Add patch 7 to invalidate FS-Cache for zero range, punch hole, insert range, and collapse range.

Link to v2:
https://lore.kernel.org/linux-cifs/[email protected]

Thanks,
Huiwen

Huiwen He (7):
smb/client: validate new EOF for insert range smb/client: validate new EOF for zero range smb/client: mark file sparse before emulating insert range smb/client: fix data corruption in emulated insert range smb/client: fix integer truncation in collapse range smb/client: fix stale page cache in insert/collapse range smb/client: invalidate fscache for fallocate range operations

 fs/smb/client/smb2ops.c | 201 +++++++++++++++++++++++++++++++++-------
 1 file changed, 167 insertions(+), 34 deletions(-)
Signature · 1 line
2.43.0
author
#3 lore raw

PATCH v3 2/7 smb/client: validate new EOF for zero range

From: Huiwen He <[email protected]>

When FALLOC_FL_ZERO_RANGE is used without FALLOC_FL_KEEP_SIZE, smb3_zero_range() may extend EOF without checking RLIMIT_FSIZE, allowing the file to grow beyond the caller's file-size limit.

Fix this by calling inode_newsize_ok() before sending the zero-range request when the operation would extend EOF.

Reproducer, using a file on a CIFS mount:

	bash -c '
	        FILE=/mnt/cifs/repro

	        trap "" SIGXFSZ
	        ulimit -f 3072

	        truncate -s 2M "$FILE"
	        fallocate --zero-range -o 0 -l 4M "$FILE"
	        echo "fallocate rc=$?"
	        stat -c "file size=%s" "$FILE"
	'

Before this change, the operation succeeds despite the 3 MiB limit:

	fallocate rc=0
	file size=4194304

After this change, fallocate fails and leaves the file at 2 MiB.

Fixes 72c419d9b073 ("cifs: fix smb3_zero_range so it can expand the file-size when required")
---
 fs/smb/client/smb2ops.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
fs/smb/client/smb2ops.c +8 -1
index bc7dda6d825a..f823f9bc90eb 100644
@@ -3442,6 +3442,13 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
 	trace_smb3_zero_enter(xid, cfile->fid.persistent_fid, tcon->tid,
 			      ses->Suid, offset, len);
 
+	new_size = offset + len;
+	if (!keep_size && i_size_read(inode) < new_size) {
+		rc = inode_newsize_ok(inode, new_size);
+		if (rc)
+			goto out;
+	}
+
 	filemap_invalidate_lock(inode->i_mapping);
 
 	netfs_read_sizes(inode, &i_size, &remote_i_size, &zero_point);
@@ -3472,7 +3479,6 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
 	/*
 	 * do we also need to change the size of the file?
 	 */
-	new_size = offset + len;
 	if (keep_size == false && (unsigned long long)i_size_read(inode) < new_size) {
 		rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
 				  cfile->fid.volatile_fid, cfile->pid, new_size);
@@ -3489,6 +3495,7 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
 
  zero_range_exit:
 	filemap_invalidate_unlock(inode->i_mapping);
+ out:
 	free_xid(xid);
 	if (rc)
 		trace_smb3_zero_err(xid, cfile->fid.persistent_fid, tcon->tid,
Signature · 1 line
2.43.0
author
#5 lore raw

PATCH v3 3/7 smb/client: mark file sparse before emulating insert range

In reply to Huiwen He

From: Huiwen He <[email protected]>

The SMB client emulates FALLOC_FL_INSERT_RANGE with SET_EOF, COPYCHUNK and SET_ZERO_DATA.

SET_ZERO_DATA creates a hole only when the file is sparse. On a non-sparse file, it clears the inserted range but leaves its blocks allocated, causing the extent count check in xfstests generic/064 to fail.

Fix this by marking the file sparse before modifying it.

Tested with xfstests generic/064 against Samba and ksmbd.

Fixes 7fe6fe95b936 ("cifs: add FALLOC_FL_INSERT_RANGE support")
---
 fs/smb/client/smb2ops.c | 5 +++++
 1 file changed, 5 insertions(+)
fs/smb/client/smb2ops.c +5 -0
index f823f9bc90eb..1eff607a1e74 100644
@@ -4013,6 +4013,11 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 
 	count = old_eof - off;
 
+	/* SET_ZERO_DATA creates a hole only in a sparse file. */
+	rc = smb2_set_sparse(xid, tcon, cfile, inode, true);
+	if (rc)
+		goto out;
+
 	filemap_invalidate_lock(inode->i_mapping);
 	rc = filemap_write_and_wait_range(inode->i_mapping, off, new_eof - 1);
 	if (rc < 0)
Signature · 1 line
2.43.0
author
#8 lore raw

PATCH v3 4/7 smb/client: fix data corruption in emulated insert range

In reply to Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() shifts [off, EOF) right with COPYCHUNK, copying from low to high offsets. When the ranges overlap, the copy can overwrite source data that has not yet been copied. For a 1 MiB insert at offset 0:

offset: 0 1M 2M 3M 4M 5M

  before:   |   A   |   B   |   C   |   D   |
  expected: | hole  |   A   |   B   |   C   |   D   |
  current:  | hole  |   A   |   A   |   A   |   A   | (corrupted)

Let x be the insertion offset, L the total length to move, delta the insert length, and C the normal chunk size allowed by the server. Insert range maps

[x, x + L) -> [x + delta, x + delta + L).

When delta >= L, the complete source and target ranges are disjoint, so the normal copy order and chunk size are safe:

offset: 0 4 8 12 16 20 24 28 32
source: [--S0--][--S1--][--S2--][--S3--]
target: [--T0--][--T1--][--T2--][--T3--]

When delta < L, the complete source and target ranges overlap, so the copy must proceed from EOF backwards. There are two subcases.

If C <= delta, each corresponding source and target chunk is disjoint. The 1 MiB example has L = 4 MiB and delta = C = 1 MiB:

offset: 0 1M 2M 3M 4M 5M
source: [--S0--][--S1--][--S2--][--S3--]
target: [--T0--][--T1--][--T2--][--T3--]

Copying S0 from [0, 1M) to [1M, 2M) overwrites S1 before it is copied. Processing chunks from EOF backwards prevents this inter-chunk overwrite.

If delta < C, the source and target ranges of a normal chunk also overlap. For example, with L = 16, delta = 2 and C = 4:

offset: 0 2 4 6 8 10 12 14 16 18
source: [--S0--][--S1--][--S2--][--S3--]
target: [--T0--][--T1--][--T2--][--T3--]

Here S0 and T0 overlap over [2,4), S1 and T1 over [6,8), and so on. Backward ordering cannot control how the server copies bytes inside one descriptor, so the chunk size must be limited to delta.

Fix this by copying overlapping right shifts from EOF backwards. Limit the chunk size to delta when delta < C so that each chunk's source and target ranges do not overlap. Reject insert lengths below 4 KiB when this limit is needed to avoid excessive COPYCHUNK requests.

Therefore:

delta >= L:
keep the normal copy order and chunk size

delta < L:
delta >=C: copy backwards and keep the normal chunk size delta < C: copy backwards and limit the chunk size to delta

Only the delta < C subcase requires reducing the chunk size for data integrity.

Reproducer:

bash -c '
MNT=/mnt/scratch

# Generate four 1 MiB random blocks: [A][B][C][D]. dd if=/dev/urandom of=/tmp/src bs=1M count=4 status=none

# With C = 1 MiB, test delta = C and delta < C. for delta in 1M 4K; do
truncate -s 0 /tmp/expected truncate -s "$delta" /tmp/expected cat /tmp/src >> /tmp/expected

cp /tmp/src "$MNT/file"
fallocate --insert-range -o 0 -l "$delta" "$MNT/file"

if cmp -s /tmp/expected "$MNT/file"; then
echo "delta=$delta: OK"
else
echo "delta=$delta: CORRUPTED"
fi
done
'

The 1 MiB case tests delta >= C, while the 4 KiB case tests delta < C. Before this change, the reproducer reports:

delta=1M: CORRUPTED
delta=4K: CORRUPTED

After this change, it pass against both ksmbd and Samba:

delta=1M: OK
delta=4K: OK

Fixes 7fe6fe95b936 ("cifs: add FALLOC_FL_INSERT_RANGE support")
---
 fs/smb/client/smb2ops.c | 143 +++++++++++++++++++++++++++++++++-------
 1 file changed, 118 insertions(+), 25 deletions(-)
fs/smb/client/smb2ops.c +118 -25
index 1eff607a1e74..1a1ff0f33288 100644
@@ -11,6 +11,7 @@
 #include <linux/scatterlist.h>
 #include <linux/uuid.h>
 #include <linux/sort.h>
+#include <linux/sizes.h>
 #include <crypto/aead.h>
 #include <linux/fiemap.h>
 #include <linux/folio_queue.h>
@@ -1839,31 +1840,31 @@ smb2_ioctl_query_info(const unsigned int xid,
  *
  * @tcon: destination file tcon
  * @bytes_left: how many bytes are left to copy
+ * @chunk_size: maximum size of a single chunk
  *
  * Return: maximum number of chunks with which Chunks[] can be filled.
  */
 static inline u32
-calc_chunk_count(struct cifs_tcon *tcon, u64 bytes_left)
+calc_chunk_count(struct cifs_tcon *tcon, u64 bytes_left, u32 chunk_size)
 {
 	u32 max_chunks = READ_ONCE(tcon->max_chunks);
 	u32 max_bytes_copy = READ_ONCE(tcon->max_bytes_copy);
-	u32 max_bytes_chunk = READ_ONCE(tcon->max_bytes_chunk);
 	u64 need;
 	u32 allowed;
 
-	if (!max_bytes_chunk || !max_bytes_copy || !max_chunks)
+	if (!chunk_size || !max_bytes_copy || !max_chunks)
 		return 0;
 
 	/* chunks needed for the remaining bytes */
-	need = DIV_ROUND_UP_ULL(bytes_left, max_bytes_chunk);
+	need = DIV_ROUND_UP_ULL(bytes_left, chunk_size);
 	/* chunks allowed per cc request */
-	allowed = DIV_ROUND_UP(max_bytes_copy, max_bytes_chunk);
+	allowed = DIV_ROUND_UP(max_bytes_copy, chunk_size);
 
 	return (u32)umin(need, umin(max_chunks, allowed));
 }
 
 /**
- * smb2_copychunk_range - server-side copy of data range
+ * __smb2_copychunk_range - server-side copy of data range
  *
  * @xid: transaction id
  * @src_file: source file
@@ -1875,15 +1876,15 @@ calc_chunk_count(struct cifs_tcon *tcon, u64 bytes_left)
  * Obtains a resume key for @src_file and issues FSCTL_SRV_COPYCHUNK_WRITE
  * IOCTLs, splitting the request into chunks limited by tcon->max_*.
  *
- * Return: @len on success; negative errno on failure.
+ * Return: 0 on success; negative errno on failure.
  */
-static ssize_t
-smb2_copychunk_range(const unsigned int xid,
-		     struct cifsFileInfo *src_file,
-		     struct cifsFileInfo *dst_file,
-		     u64 src_off,
-		     u64 len,
-		     u64 dst_off)
+static int
+__smb2_copychunk_range(const unsigned int xid,
+		       struct cifsFileInfo *src_file,
+		       struct cifsFileInfo *dst_file,
+		       u64 src_off,
+		       u64 len,
+		       u64 dst_off)
 {
 	int rc = 0;
 	unsigned int ret_data_len = 0;
@@ -1891,12 +1892,14 @@ smb2_copychunk_range(const unsigned int xid,
 	struct copychunk_ioctl_rsp *cc_rsp = NULL;
 	struct cifs_tcon *tcon;
 	struct srv_copychunk *chunk;
-	u32 chunks, chunk_count, chunk_bytes;
+	u32 chunks, chunk_count, chunk_bytes, chunk_size;
 	u32 copy_bytes, copy_bytes_left;
 	u32 chunks_written, bytes_written;
 	u64 total_bytes_left = len;
 	u64 src_off_prev, dst_off_prev;
+	u64 max_chunk = 0;
 	u32 retries = 0;
+	bool reverse = false;
 
 	tcon = tlink_tcon(dst_file->tlink);
 
@@ -1904,8 +1907,48 @@ smb2_copychunk_range(const unsigned int xid,
 				   dst_file->fid.volatile_fid, tcon->tid,
 				   tcon->ses->Suid, src_off, dst_off, len);
 
+	/*
+	 * Same-file left shifts are safe in forward order. For a right shift,
+	 * let L be the copy length, delta the distance between the source and
+	 * destination, and C the normal chunk size:
+	 *
+	 *   delta >= L:      copy forwards using C
+	 *   delta < L:
+	 *     delta >= C:    copy backwards using C
+	 *     delta < C:     copy backwards with chunks limited to delta
+	 *
+	 * Copying backwards prevents one chunk from overwriting data needed by
+	 * a later chunk. Limiting the chunk size to delta prevents an individual
+	 * chunk from overlapping itself.
+	 *
+	 * A small right shift over a large range may therefore require many
+	 * chunks.
+	 */
+	if (src_file == dst_file && dst_off > src_off) {
+		u64 delta = dst_off - src_off;
+
+		if (delta < len) {
+			reverse = true;
+			max_chunk = delta;
+		}
+	}
+
+	/*
+	 * A backward copy walks the offsets down from the end of the range.
+	 * Do this once, outside the retry loop, so a retry does not move the
+	 * offsets again.
+	 */
+	if (reverse) {
+		src_off += len;
+		dst_off += len;
+	}
+
 retry:
-	chunk_count = calc_chunk_count(tcon, total_bytes_left);
+	chunk_size = READ_ONCE(tcon->max_bytes_chunk);
+	if (max_chunk && max_chunk < chunk_size)
+		chunk_size = (u32)max_chunk;
+
+	chunk_count = calc_chunk_count(tcon, total_bytes_left, chunk_size);
 	if (!chunk_count) {
 		rc = -EOPNOTSUPP;
 		goto out;
@@ -1946,16 +1989,21 @@ smb2_copychunk_range(const unsigned int xid,
 		while (copy_bytes_left > 0 && chunks < chunk_count) {
 			chunk = &cc_req->Chunks[chunks++];
 
+			chunk_bytes = umin(copy_bytes_left, chunk_size);
+			if (reverse) {
+				src_off -= chunk_bytes;
+				dst_off -= chunk_bytes;
+			}
+
 			chunk->SourceOffset = cpu_to_le64(src_off);
 			chunk->TargetOffset = cpu_to_le64(dst_off);
-
-			chunk_bytes = umin(copy_bytes_left, tcon->max_bytes_chunk);
-
 			chunk->Length = cpu_to_le32(chunk_bytes);
 			/* Buffer is zeroed, no need to set chunk->Reserved = 0 */
 
-			src_off += chunk_bytes;
-			dst_off += chunk_bytes;
+			if (!reverse) {
+				src_off += chunk_bytes;
+				dst_off += chunk_bytes;
+			}
 
 			copy_bytes_left -= chunk_bytes;
 			copy_bytes += chunk_bytes;
@@ -2003,6 +2051,18 @@ smb2_copychunk_range(const unsigned int xid,
 				goto out;
 			}
 
+			/*
+			 * A successful COPYCHUNK should copy every descriptor (MS-SMB2
+			 * 3.3.5.15.6). Reject a short backward copy because the rewind
+			 * below only supports forward copying.
+			 */
+			if (unlikely(reverse && bytes_written < copy_bytes)) {
+				cifs_tcon_dbg(VFS, "Copychunk short write %u/%u (reverse)\n",
+					      bytes_written, copy_bytes);
+				rc = -EIO;
+				goto out;
+			}
+
 			/* Partial write: rewind */
 			if (bytes_written < copy_bytes) {
 				u32 delta = copy_bytes - bytes_written;
@@ -2064,10 +2124,27 @@ smb2_copychunk_range(const unsigned int xid,
 		trace_smb3_copychunk_done(xid, src_file->fid.volatile_fid,
 					  dst_file->fid.volatile_fid, tcon->tid,
 					  tcon->ses->Suid, src_off, dst_off, len);
-		return len;
+		return 0;
 	}
 }
 
+static ssize_t
+smb2_copychunk_range(const unsigned int xid,
+		     struct cifsFileInfo *src_file,
+		     struct cifsFileInfo *dst_file,
+		     u64 src_off,
+		     u64 len,
+		     u64 dst_off)
+{
+	int rc;
+
+	rc = __smb2_copychunk_range(xid, src_file, dst_file, src_off, len,
+				    dst_off);
+	if (rc)
+		return rc;
+	return len;
+}
+
 static int
 smb2_flush_file(const unsigned int xid, struct cifs_tcon *tcon,
 		struct cifs_fid *fid)
@@ -3989,10 +4066,10 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 {
 	int rc;
 	unsigned int xid;
+	u32 chunk_size;
 	struct cifsFileInfo *cfile = file->private_data;
 	struct inode *inode = file_inode(file);
 	struct cifsInodeInfo *cifsi = CIFS_I(inode);
-	u64 count;
 	loff_t old_eof, new_eof;
 
 	xid = get_xid();
@@ -4011,7 +4088,18 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 	if (rc)
 		goto out;
 
-	count = old_eof - off;
+	chunk_size = umin(READ_ONCE(tcon->max_bytes_chunk),
+			  READ_ONCE(tcon->max_bytes_copy));
+	/*
+	 * When len is smaller than both the range to move and the normal chunk
+	 * size, limit each chunk to len so its source and target do not overlap
+	 * and corrupt uncopied data. Reject len below 4 KiB in this case to
+	 * avoid excessive COPYCHUNK requests.
+	 */
+	if (len < old_eof - off && len < chunk_size && len < SZ_4K) {
+		rc = -EINVAL;
+		goto out;
+	}
 
 	/* SET_ZERO_DATA creates a hole only in a sparse file. */
 	rc = smb2_set_sparse(xid, tcon, cfile, inode, true);
@@ -4036,7 +4124,12 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 	spin_unlock(&inode->i_lock);
 	fscache_resize_cookie(cifs_inode_cookie(inode), i_size_read(inode));
 
-	rc = smb2_copychunk_range(xid, cfile, cfile, off, count, off + len);
+	/*
+	 * Move [off, old_eof) right by len. The helper copies backwards if the
+	 * source and destination ranges overlap.
+	 */
+	rc = __smb2_copychunk_range(xid, cfile, cfile, off, old_eof - off,
+				    off + len);
 	if (rc < 0)
 		goto out_2;
 	spin_lock(&inode->i_lock);
Signature · 1 line
2.43.0
author
#12 lore raw

PATCH v3 5/7 smb/client: fix integer truncation in collapse range

In reply to Huiwen He

From: Huiwen He <[email protected]>

smb3_collapse_range() stores the ssize_t return value of smb2_copychunk_range() in an int. A successful copy larger than INT_MAX is truncated to a negative value and treated as an error.

Reproducer:

	MNT=/mnt/scratch

	truncate -s 2056M "$MNT/file"
	fallocate --collapse-range -o 1M -l 1M "$MNT/file"

Fix this by using __smb2_copychunk_range(), which reports success as zero instead of returning the copied byte count.

Before this change, the reproducer fails with:

fallocate: fallocate failed: Success

and the file size remains unchanged at 2056 MiB. After this change, the reproducer succeeds and the file size becomes the expected 2055 MiB.

Fixes 5476b5dd82c8 ("cifs: add support for FALLOC_FL_COLLAPSE_RANGE")
---
 fs/smb/client/smb2ops.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/smb/client/smb2ops.c +2 -2
index 1a1ff0f33288..ee0f646d1aa2 100644
@@ -4035,8 +4035,8 @@ static long smb3_collapse_range(struct file *file, struct cifs_tcon *tcon,
 	spin_unlock(&inode->i_lock);
 	netfs_wait_for_outstanding_io(inode);
 
-	rc = smb2_copychunk_range(xid, cfile, cfile, off + len,
-				  old_eof - off - len, off);
+	rc = __smb2_copychunk_range(xid, cfile, cfile, off + len,
+				    old_eof - off - len, off);
 	if (rc < 0)
 		goto out_2;
 
Signature · 1 line
2.43.0
author
#13 lore raw

PATCH v3 6/7 smb/client: fix stale page cache in insert/collapse range

In reply to Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() and smb3_collapse_range() use truncate_pagecache_range() to invalidate the affected page cache. However, if off or old_eof is not page-aligned, the boundary pages are only partially zeroed and remain uptodate. As a result, the client may return stale data after a successful insert/collapse range operation.

For example, with 4K pages:

    page 0          page 1          page 2
    0------4K       4K------8K      8K------12K

^ ^
off=2K old_eof=10K

Page 1 is removed from the page cache, while the boundary pages are only partially zeroed. After COPYCHUNK moves the data on the server, these cached pages may still return stale data.

This can be reproduced on a CIFS mount:

bash -c '
FILE=/mnt/scratch/repro

# Use a 6 KiB file so EOF is not page-aligned. dd if=/dev/urandom of=/tmp/src bs=1K count=6 status=none

# Expected: a 4 KiB hole followed by the original data. rm -f /tmp/expected
truncate -s 4K /tmp/expected
cat /tmp/src >> /tmp/expected

cp /tmp/src "$FILE"

# Prime the page cache before moving data on the server. cat "$FILE" > /dev/null

fallocate --insert-range -o 0 -l 4K "$FILE"

if cmp -s /tmp/expected "$FILE"; then
echo "readback: OK"
else
echo "readback: STALE DATA"
fi
'

Fix this by writing back dirty data and discarding the page cache from the start of the page containing off to EOF before moving data on the server.

Fixes 9c8b7a293f50 ("smb3: fix temporary data corruption in insert range")
Fixes fa30a81f255a ("smb3: fix temporary data corruption in collapse range")
---
 fs/smb/client/smb2ops.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)
fs/smb/client/smb2ops.c +18 -5
index ee0f646d1aa2..835bc342840d 100644
@@ -4025,15 +4025,22 @@ static long smb3_collapse_range(struct file *file, struct cifs_tcon *tcon,
 	}
 
 	filemap_invalidate_lock(inode->i_mapping);
-	rc = filemap_write_and_wait_range(inode->i_mapping, off, old_eof - 1);
+	rc = filemap_write_and_wait_range(inode->i_mapping,
+					  round_down(off, PAGE_SIZE),
+					  old_eof - 1);
 	if (rc < 0)
 		goto out_2;
 
-	truncate_pagecache_range(inode, off, old_eof);
+	netfs_wait_for_outstanding_io(inode);
+	/*
+	 * Invalidate cached folios from the page containing off to EOF before
+	 * moving data on the server, so subsequent reads do not see stale data.
+	 */
+	truncate_pagecache_range(inode, round_down(off, PAGE_SIZE), -1);
+
 	spin_lock(&inode->i_lock);
 	netfs_write_zero_point(inode, old_eof);
 	spin_unlock(&inode->i_lock);
-	netfs_wait_for_outstanding_io(inode);
 
 	rc = __smb2_copychunk_range(xid, cfile, cfile, off + len,
 				    old_eof - off - len, off);
@@ -4107,11 +4114,17 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 		goto out;
 
 	filemap_invalidate_lock(inode->i_mapping);
-	rc = filemap_write_and_wait_range(inode->i_mapping, off, new_eof - 1);
+	rc = filemap_write_and_wait_range(inode->i_mapping,
+					  round_down(off, PAGE_SIZE),
+					  old_eof - 1);
 	if (rc < 0)
 		goto out_2;
-	truncate_pagecache_range(inode, off, old_eof);
 	netfs_wait_for_outstanding_io(inode);
+	/*
+	 * Invalidate cached folios from the page containing off to EOF before
+	 * moving data on the server, so subsequent reads do not see stale data.
+	 */
+	truncate_pagecache_range(inode, round_down(off, PAGE_SIZE), -1);
 
 	rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
 			  cfile->fid.volatile_fid, cfile->pid, new_eof);
Signature · 1 line
2.43.0
author
#15 lore raw

PATCH v3 7/7 smb/client: invalidate fscache for fallocate range operations

In reply to Huiwen He

From: Huiwen He <[email protected]>

smb3_zero_range(), smb3_punch_hole(), smb3_insert_range(), and smb3_collapse_range() modify file contents through server-side range operations. These operations discard the affected page cache, but leave the FS-Cache cookie valid, so a later read may return data cached before the range operation.

Fix this by invalidating FS-Cache after outstanding I/O has completed and before modifying the file on the server.

Run the following as root on a CIFS mount with fsc enabled and an active CacheFiles backend:

bash -c '
MNT=/mnt/cifs
FILE="$MNT/repro"

# Generate four 1 MiB random blocks: [A][B][C][D]. dd if=/dev/urandom of=/tmp/src bs=1M count=4 status=none

# Expected contents after zeroing B: [A][zero][C][D]. cp /tmp/src /tmp/expected
dd if=/dev/zero of=/tmp/expected bs=1M seek=1 count=1 \
conv=notrunc status=none
cp /tmp/src "$FILE"

# Populate FS-Cache, then discard the page cache. sync
echo 1 > /proc/sys/vm/drop_caches
cat "$FILE" > /dev/null
sync
echo 1 > /proc/sys/vm/drop_caches

fallocate --zero-range -o 1M -l 1M "$FILE"

if cmp -s /tmp/expected "$FILE"; then
echo "readback: OK"
else
echo "readback: STALE DATA"
fi
'

Before this change, the readback differs from /tmp/expected:

readback: STALE DATA

After this change, it matches:

readback: OK

Fixes 30175628bf7f ("[SMB3] Enable fallocate -z support for SMB3 mounts")
Fixes 31742c5a3317 ("enable fallocate punch hole ("fallocate -p") for SMB3")
Fixes 5476b5dd82c8 ("cifs: add support for FALLOC_FL_COLLAPSE_RANGE")
Fixes 7fe6fe95b936 ("cifs: add FALLOC_FL_INSERT_RANGE support")
---
 fs/smb/client/smb2ops.c | 7 +++++++
 1 file changed, 7 insertions(+)
fs/smb/client/smb2ops.c +7 -0
index 835bc342840d..60a40d6b0da3 100644
@@ -3549,6 +3549,9 @@ static long smb3_zero_range(struct file *file, struct cifs_tcon *tcon,
 	if (keep_size == false && !CIFS_CACHE_READ(cifsi))
 		goto zero_range_exit;
 
+	fscache_invalidate(cifs_inode_cookie(inode), NULL,
+			   i_size_read(inode), 0);
+
 	rc = smb3_zero_data(file, tcon, offset, len, xid);
 	if (rc < 0)
 		goto zero_range_exit;
@@ -3618,6 +3621,8 @@ static long smb3_punch_hole(struct file *file, struct cifs_tcon *tcon,
 	 */
 	truncate_pagecache_range(inode, offset, offset + len - 1);
 	netfs_wait_for_outstanding_io(inode);
+	fscache_invalidate(cifs_inode_cookie(inode), NULL,
+			   i_size_read(inode), 0);
 
 	cifs_dbg(FYI, "Offset %lld len %lld\n", offset, len);
 
@@ -4037,6 +4042,7 @@ static long smb3_collapse_range(struct file *file, struct cifs_tcon *tcon,
 	 * moving data on the server, so subsequent reads do not see stale data.
 	 */
 	truncate_pagecache_range(inode, round_down(off, PAGE_SIZE), -1);
+	fscache_invalidate(cifs_inode_cookie(inode), NULL, old_eof, 0);
 
 	spin_lock(&inode->i_lock);
 	netfs_write_zero_point(inode, old_eof);
@@ -4125,6 +4131,7 @@ static long smb3_insert_range(struct file *file, struct cifs_tcon *tcon,
 	 * moving data on the server, so subsequent reads do not see stale data.
 	 */
 	truncate_pagecache_range(inode, round_down(off, PAGE_SIZE), -1);
+	fscache_invalidate(cifs_inode_cookie(inode), NULL, old_eof, 0);
 
 	rc = SMB2_set_eof(xid, tcon, cfile->fid.persistent_fid,
 			  cfile->fid.volatile_fid, cfile->pid, new_eof);
Signature · 1 line
2.43.0
maintainer Reviewed-by on the v3 series
#17 lore raw
In reply to Huiwen He
Quoted 19 lines · Huiwen He

From: Huiwen He <[email protected]>

This series fixes several issues in SMB3 fallocate range operations, including insert range, collapse range, zero range, and punch hole.

Changes in v3:

- Update patch 6 to use page-aligned truncate_pagecache_range() instead of invalidate_inode_pages2_range(), avoiding possible -EBUSY failures.
- Add patch 7 to invalidate FS-Cache for zero range, punch hole, insert range, and collapse range.

Link to v2:
https://lore.kernel.org/linux-cifs/[email protected]

Thanks,
Huiwen

Quoted 8 lines

Huiwen He (7):
smb/client: validate new EOF for insert range smb/client: validate new EOF for zero range smb/client: mark file sparse before emulating insert range smb/client: fix data corruption in emulated insert range smb/client: fix integer truncation in collapse range smb/client: fix stale page cache in insert/collapse range smb/client: invalidate fscache for fallocate range operations

For all patches in this patch-set,

Thanks.

maintainer Applied
#2 lore raw

Re: [PATCH v3 1/7] smb/client: validate new EOF for insert range

In reply to Huiwen He
Quoted 10 lines · Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() does not check if the new file size (i_size + len) is valid. This allows FALLOC_FL_INSERT_RANGE to bypass RLIMIT_FSIZE, exceed s_maxbytes, or produce a size outside the loff_t range.

Use check_add_overflow() to calculate the new EOF. Validate it with inode_newsize_ok() before modifying the file.
...

Applied.

maintainer Applied
#4 lore raw

Re: [PATCH v3 2/7] smb/client: validate new EOF for zero range

In reply to Huiwen He
Quoted 9 lines · Huiwen He

From: Huiwen He <[email protected]>

When FALLOC_FL_ZERO_RANGE is used without FALLOC_FL_KEEP_SIZE, smb3_zero_range() may extend EOF without checking RLIMIT_FSIZE, allowing the file to grow beyond the caller's file-size limit.

Fix this by calling inode_newsize_ok() before sending the zero-range request when the operation would extend EOF.
...

Applied.

maintainer
#6 lore raw

Re: [PATCH v3 3/7] smb/client: mark file sparse before emulating insert range

In reply to Huiwen He

Hi Huiwen,

Quoted 5 lines · Huiwen He

From: Huiwen He <[email protected]>

The SMB client emulates FALLOC_FL_INSERT_RANGE with SET_EOF, COPYCHUNK and SET_ZERO_DATA.

Quoted 8 lines

SET_ZERO_DATA creates a hole only when the file is sparse. On a non-sparse file, it clears the inserted range but leaves its blocks allocated, causing the extent count check in xfstests generic/064 to fail.

Fix this by marking the file sparse before modifying it.

Tested with xfstests generic/064 against Samba and ksmbd.

After applying this patch, generic/064 still fails for me against samba-4.24.5-1.fc44.x86_64. Tested it with both btrfs and xfs, and 'strict allocate = yes'. It also fails against Windows Server 2022.

SECTION       -- smb3
FSTYP         -- cifs
PLATFORM      -- Linux/x86_64 fed 7.2.0 #4 SMP PREEMPT_DYNAMIC Wed Aug 26 21:42:48 -03 2026
MKFS_OPTIONS  -- //192.168.124.43/scratch2

MOUNT_OPTIONS -- -ousername=testuser,password=foo-321,vers=3.1.1,mfsymlinks,noperm //192.168.124.43/scratch2 /mnt/scratch

generic/064 - output mismatch (see /root/g/xfstests/results//smb3/generic/064.out.bad)
--- tests/generic/064.out 2024-02-15 10:35:04.361833706 -0300
+++ /root/g/xfstests/results//smb3/generic/064.out.bad 2026-08-26 21:58:54.469813041 -0300
@@ -1,2 +1,3 @@
QA output created by 064
-Extent count after inserts is in range
+Extent count after inserts has value of 1
+Extent count after inserts is NOT in range 50 .. 53
...
(Run 'diff -u /root/g/xfstests/tests/generic/064.out /root/g/xfstests/results//smb3/generic/064.out.bad' to see the entire diff)
Ran: generic/064
Failures: generic/064
Failed 1 of 1 tests

What am I missing?

Could you please provide details of your server version and settings?

Thanks.

maintainer
#9 lore raw

Re: [PATCH v3 4/7] smb/client: fix data corruption in emulated insert range

In reply to Huiwen He

Hi Huiwen,

Quoted 83 lines · Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() shifts [off, EOF) right with COPYCHUNK, copying from low to high offsets. When the ranges overlap, the copy can overwrite source data that has not yet been copied. For a 1 MiB insert at offset 0:

offset: 0 1M 2M 3M 4M 5M

  before:   |   A   |   B   |   C   |   D   |
  expected: | hole  |   A   |   B   |   C   |   D   |
  current:  | hole  |   A   |   A   |   A   |   A   | (corrupted)

Let x be the insertion offset, L the total length to move, delta the insert length, and C the normal chunk size allowed by the server. Insert range maps

[x, x + L) -> [x + delta, x + delta + L).

When delta >= L, the complete source and target ranges are disjoint, so the normal copy order and chunk size are safe:

offset: 0 4 8 12 16 20 24 28 32
source: [--S0--][--S1--][--S2--][--S3--]
target: [--T0--][--T1--][--T2--][--T3--]

When delta < L, the complete source and target ranges overlap, so the copy must proceed from EOF backwards. There are two subcases.

If C <= delta, each corresponding source and target chunk is disjoint. The 1 MiB example has L = 4 MiB and delta = C = 1 MiB:

offset: 0 1M 2M 3M 4M 5M
source: [--S0--][--S1--][--S2--][--S3--]
target: [--T0--][--T1--][--T2--][--T3--]

Copying S0 from [0, 1M) to [1M, 2M) overwrites S1 before it is copied. Processing chunks from EOF backwards prevents this inter-chunk overwrite.

If delta < C, the source and target ranges of a normal chunk also overlap. For example, with L = 16, delta = 2 and C = 4:

offset: 0 2 4 6 8 10 12 14 16 18
source: [--S0--][--S1--][--S2--][--S3--]
target: [--T0--][--T1--][--T2--][--T3--]

Here S0 and T0 overlap over [2,4), S1 and T1 over [6,8), and so on. Backward ordering cannot control how the server copies bytes inside one descriptor, so the chunk size must be limited to delta.

Fix this by copying overlapping right shifts from EOF backwards. Limit the chunk size to delta when delta < C so that each chunk's source and target ranges do not overlap. Reject insert lengths below 4 KiB when this limit is needed to avoid excessive COPYCHUNK requests.

Therefore:

delta >= L:
keep the normal copy order and chunk size

delta < L:
delta >=C: copy backwards and keep the normal chunk size delta < C: copy backwards and limit the chunk size to delta

Only the delta < C subcase requires reducing the chunk size for data integrity.

Reproducer:

bash -c '
MNT=/mnt/scratch

# Generate four 1 MiB random blocks: [A][B][C][D]. dd if=/dev/urandom of=/tmp/src bs=1M count=4 status=none

# With C = 1 MiB, test delta = C and delta < C. for delta in 1M 4K; do
truncate -s 0 /tmp/expected truncate -s "$delta" /tmp/expected cat /tmp/src >> /tmp/expected

cp /tmp/src "$MNT/file"
fallocate --insert-range -o 0 -l "$delta" "$MNT/file"

Quoted 7 lines

if cmp -s /tmp/expected "$MNT/file"; then
echo "delta=$delta: OK"
else
echo "delta=$delta: CORRUPTED"
fi
done
'

Without this patch and running above reproducer against Windows Server 2022, I get no data corruption. Samba requires this patch to make it work, though.

Besides, after applying this patch, generic/064 fails differently when running against samba-4.24.5-1.fc44.x86_64

SECTION       -- smb3
FSTYP         -- cifs
PLATFORM      -- Linux/x86_64 fed 7.2.0 #4 SMP PREEMPT_DYNAMIC Wed Aug 26 21:42:48 -03 2026
MKFS_OPTIONS  -- //192.168.124.43/scratch

MOUNT_OPTIONS -- -ousername=testuser,password=foo-321,vers=3.1.1,mfsymlinks,noperm //192.168.124.43/scratch /mnt/scratch

generic/064 [not run] xfs_io finsert failed (old kernel/wrong fs/bad args?)
Ran: generic/064
Not run: generic/064
Passed all 1 tests

Could you please verify?

Thanks.

maintainer Applied
#14 lore raw

Re: [PATCH v3 6/7] smb/client: fix stale page cache in insert/collapse range

In reply to Huiwen He
Quoted 46 lines · Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() and smb3_collapse_range() use truncate_pagecache_range() to invalidate the affected page cache. However, if off or old_eof is not page-aligned, the boundary pages are only partially zeroed and remain uptodate. As a result, the client may return stale data after a successful insert/collapse range operation.

For example, with 4K pages:

    page 0          page 1          page 2
    0------4K       4K------8K      8K------12K

^ ^
off=2K old_eof=10K

Page 1 is removed from the page cache, while the boundary pages are only partially zeroed. After COPYCHUNK moves the data on the server, these cached pages may still return stale data.

This can be reproduced on a CIFS mount:

bash -c '
FILE=/mnt/scratch/repro

# Use a 6 KiB file so EOF is not page-aligned. dd if=/dev/urandom of=/tmp/src bs=1K count=6 status=none

# Expected: a 4 KiB hole followed by the original data. rm -f /tmp/expected
truncate -s 4K /tmp/expected
cat /tmp/src >> /tmp/expected

cp /tmp/src "$FILE"

# Prime the page cache before moving data on the server. cat "$FILE" > /dev/null

fallocate --insert-range -o 0 -l 4K "$FILE"

if cmp -s /tmp/expected "$FILE"; then
echo "readback: OK"
else
echo "readback: STALE DATA"
fi
'

Quoted 4 lines

Fix this by writing back dirty data and discarding the page cache from the start of the page containing off to EOF before moving data on the server.
...

Applied.

maintainer Applied
#16 lore raw

Re: [PATCH v3 7/7] smb/client: invalidate fscache for fallocate range operations

In reply to Huiwen He
Quoted 11 lines · Huiwen He

From: Huiwen He <[email protected]>

smb3_zero_range(), smb3_punch_hole(), smb3_insert_range(), and smb3_collapse_range() modify file contents through server-side range operations. These operations discard the affected page cache, but leave the FS-Cache cookie valid, so a later read may return data cached before the range operation.

Fix this by invalidating FS-Cache after outstanding I/O has completed and before modifying the file on the server.
...

Applied.

author
#7 lore raw

Re: [PATCH v3 3/7] smb/client: mark file sparse before emulating insert range

In reply to Paulo Alcantara

Thanks. I repeated a controlled A/B test with the same kernel tree, reverting/restoring only this patch.

Without the patch:

./check -d generic/064

FSTYP         -- cifs
PLATFORM      -- Linux/x86_64 localhost 7.2.0-rc6+ #71 SMP PREEMPT_DYNAMIC Tue Aug 25 15:38:06 CST 2026
MKFS_OPTIONS  -- //192.168.10.1/scratch_share

MOUNT_OPTIONS -- -o username=smbuser,password=Kylin123,vers=3.1.1,mfsymlinks,noperm //192.168.10.1/scratch_share /mnt/scratch

generic/064 2s ... QA output created by 064
Extent count after inserts has value of 1
Extent count after inserts is NOT in range 50 .. 53
- output mismatch (see /src/xfstests-dev/results//generic/064.out.bad)

    --- tests/generic/064.out	2026-05-08 16:46:07.377810776 +0800
    +++ /src/xfstests-dev/results//generic/064.out.bad	2026-08-27 

11:11:58.000000000 +0800
@@ -1,2 +1,3 @@
QA output created by 064
-Extent count after inserts is in range
+Extent count after inserts has value of 1
+Extent count after inserts is NOT in range 50 .. 53
...
(Run 'diff -u /src/xfstests-dev/tests/generic/064.out
/src/xfstests-dev/results//generic/064.out.bad' to see the entire diff)
Ran: generic/064
Failures: generic/064
Failed 1 of 1 tests
---------------------------------------------------------------

With the patch:

./check -d generic/064

FSTYP         -- cifs
PLATFORM      -- Linux/x86_64 localhost 7.2.0-rc6+ #71 SMP PREEMPT_DYNAMIC Tue Aug 25 15:38:06 CST 2026
MKFS_OPTIONS  -- //192.168.10.1/scratch_share

MOUNT_OPTIONS -- -o username=smbuser,password=Kylin123,vers=3.1.1,mfsymlinks,noperm //192.168.10.1/scratch_share /mnt/scratch

generic/064 2s ... QA output created by 064
Extent count after inserts is in range
2s
Ran: generic/064
Passed all 1 tests

--------------------------------------------------------------
Server configuration:

Fedora 43
Samba 4.23.7-2.fc43
btrfs backing filesystem
strict allocate = yes

As noted in the v1 cover letter, the Windows Server result is expected: aligned 64 KiB and 128 KiB insert ranges are reported as holes, while generic/064 uses 4 KiB inserts, which are below the observed sparse deallocation granularity on Windows.

Thanks,
Huiwen

Quoted 47 lines · Paulo Alcantara

Hi Huiwen,

Quoted 5 lines · Huiwen He

From: Huiwen He <[email protected]>

The SMB client emulates FALLOC_FL_INSERT_RANGE with SET_EOF, COPYCHUNK and SET_ZERO_DATA.

Quoted 8 lines

SET_ZERO_DATA creates a hole only when the file is sparse. On a non-sparse file, it clears the inserted range but leaves its blocks allocated, causing the extent count check in xfstests generic/064 to fail.

Fix this by marking the file sparse before modifying it.

Tested with xfstests generic/064 against Samba and ksmbd.

After applying this patch, generic/064 still fails for me against samba-4.24.5-1.fc44.x86_64. Tested it with both btrfs and xfs, and 'strict allocate = yes'. It also fails against Windows Server 2022.

SECTION       -- smb3
FSTYP         -- cifs
PLATFORM      -- Linux/x86_64 fed 7.2.0 #4 SMP PREEMPT_DYNAMIC Wed Aug 26 21:42:48 -03 2026
MKFS_OPTIONS  -- //192.168.124.43/scratch2

MOUNT_OPTIONS -- -ousername=testuser,password=foo-321,vers=3.1.1,mfsymlinks,noperm //192.168.124.43/scratch2 /mnt/scratch

generic/064 - output mismatch (see /root/g/xfstests/results//smb3/generic/064.out.bad)
--- tests/generic/064.out 2024-02-15 10:35:04.361833706 -0300
+++ /root/g/xfstests/results//smb3/generic/064.out.bad 2026-08-26 21:58:54.469813041 -0300
@@ -1,2 +1,3 @@
QA output created by 064
-Extent count after inserts is in range
+Extent count after inserts has value of 1
+Extent count after inserts is NOT in range 50 .. 53
...
(Run 'diff -u /root/g/xfstests/tests/generic/064.out /root/g/xfstests/results//smb3/generic/064.out.bad' to see the entire diff)
Ran: generic/064
Failures: generic/064
Failed 1 of 1 tests

What am I missing?

Could you please provide details of your server version and settings?

Thanks.

author
#10 lore raw

Re: [PATCH v3 4/7] smb/client: fix data corruption in emulated insert range

In reply to Paulo Alcantara

Hi Paulo,

Thanks for testing.

Windows Server 2022 handles overlapping same-file COPYCHUNK ranges internally, so the old forward copy does not cause corruption there. Samba and ksmbd do not handle such overlap safely.

The generic/064 result is caused by the 4 KiB minimum added by this patch.Samba reports a 1 KiB block size by default, so the test's finsert probe uses a range smaller than 4 KiB and gets -EINVAL,
resulting in [not run].

My Samba setup used "block size = 4096", so I did not see this locally.

I will reconsider how to handle this and address it in v4.

Thanks,
Huiwen

Quoted 116 lines · Paulo Alcantara

Hi Huiwen,

Quoted 83 lines · Huiwen He

From: Huiwen He <[email protected]>

smb3_insert_range() shifts [off, EOF) right with COPYCHUNK, copying from low to high offsets. When the ranges overlap, the copy can overwrite source data that has not yet been copied. For a 1 MiB insert at offset 0:

offset: 0 1M 2M 3M 4M 5M

   before:   |   A   |   B   |   C   |   D   |
   expected: | hole  |   A   |   B   |   C   |   D   |
   current:  | hole  |   A   |   A   |   A   |   A   | (corrupted)

Let x be the insertion offset, L the total length to move, delta the insert length, and C the normal chunk size allowed by the server. Insert range maps

   [x, x + L) -> [x + delta, x + delta + L).

When delta >= L, the complete source and target ranges are disjoint, so the normal copy order and chunk size are safe:

   offset: 0       4       8      12      16      20      24      28      32
   source: [--S0--][--S1--][--S2--][--S3--]
   target:                                 [--T0--][--T1--][--T2--][--T3--]

When delta < L, the complete source and target ranges overlap, so the copy must proceed from EOF backwards. There are two subcases.

If C <= delta, each corresponding source and target chunk is disjoint. The 1 MiB example has L = 4 MiB and delta = C = 1 MiB:

   offset: 0       1M      2M      3M      4M      5M
   source: [--S0--][--S1--][--S2--][--S3--]
   target:         [--T0--][--T1--][--T2--][--T3--]

Copying S0 from [0, 1M) to [1M, 2M) overwrites S1 before it is copied. Processing chunks from EOF backwards prevents this inter-chunk overwrite.

If delta < C, the source and target ranges of a normal chunk also overlap. For example, with L = 16, delta = 2 and C = 4:

   offset: 0   2   4   6   8  10  12  14  16  18
   source: [--S0--][--S1--][--S2--][--S3--]
   target:     [--T0--][--T1--][--T2--][--T3--]

Here S0 and T0 overlap over [2,4), S1 and T1 over [6,8), and so on. Backward ordering cannot control how the server copies bytes inside one descriptor, so the chunk size must be limited to delta.

Fix this by copying overlapping right shifts from EOF backwards. Limit the chunk size to delta when delta < C so that each chunk's source and target ranges do not overlap. Reject insert lengths below 4 KiB when this limit is needed to avoid excessive COPYCHUNK requests.

Therefore:

delta >= L:
keep the normal copy order and chunk size

delta < L:
delta >=C: copy backwards and keep the normal chunk size delta < C: copy backwards and limit the chunk size to delta

Only the delta < C subcase requires reducing the chunk size for data integrity.

Reproducer:

bash -c '
MNT=/mnt/scratch

# Generate four 1 MiB random blocks: [A][B][C][D]. dd if=/dev/urandom of=/tmp/src bs=1M count=4 status=none

# With C = 1 MiB, test delta = C and delta < C. for delta in 1M 4K; do
truncate -s 0 /tmp/expected truncate -s "$delta" /tmp/expected cat /tmp/src >> /tmp/expected

cp /tmp/src "$MNT/file"
fallocate --insert-range -o 0 -l "$delta" "$MNT/file"

Quoted 7 lines

if cmp -s /tmp/expected "$MNT/file"; then
echo "delta=$delta: OK"
else
echo "delta=$delta: CORRUPTED"
fi
done
'

Without this patch and running above reproducer against Windows Server 2022, I get no data corruption. Samba requires this patch to make it work, though.

Besides, after applying this patch, generic/064 fails differently when running against samba-4.24.5-1.fc44.x86_64

SECTION       -- smb3
FSTYP         -- cifs
PLATFORM      -- Linux/x86_64 fed 7.2.0 #4 SMP PREEMPT_DYNAMIC Wed Aug 26 21:42:48 -03 2026
MKFS_OPTIONS  -- //192.168.124.43/scratch

MOUNT_OPTIONS -- -ousername=testuser,password=foo-321,vers=3.1.1,mfsymlinks,noperm //192.168.124.43/scratch /mnt/scratch

generic/064 [not run] xfs_io finsert failed (old kernel/wrong fs/bad args?)
Ran: generic/064
Not run: generic/064
Passed all 1 tests

Could you please verify?

Thanks.

maintainer
#11 lore raw

Re: [PATCH v3 4/7] smb/client: fix data corruption in emulated insert range

Quoted 4 lines · hehuiwen

Windows Server 2022 handles overlapping same-file COPYCHUNK ranges internally, so the old forward copy does not cause corruption there. Samba and ksmbd do not handle such overlap safely.

Quoted 8 lines

The generic/064 result is caused by the 4 KiB minimum added by this patch.Samba reports a 1 KiB block size by default, so the test's finsert probe uses a range smaller than 4 KiB and gets -EINVAL, resulting in [not run].

My Samba setup used "block size = 4096", so I did not see this locally.

I will reconsider how to handle this and address it in v4.

Awesome! Thanks for looking into it.