Skip to contentSkip to conversation

exfat: fix valid_size update races

PATCH Applied Chi Zhiling 3 participants 9 messages Nov 16 – Nov 17

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

v4 cover exfat: fix valid_size update races

From: Chi Zhiling <[email protected]>

exFAT uses valid_size (ValidDataLength) as the on-disk boundary of initialised data, but the current code advances it too late and without proper serialisation. Buffered writes can silently lose data reclaimed before valid_size covers it, file expansion and page faults can initialise the same range concurrently, and a failed or short direct write can still grow the file on disk.

This series advances valid_size under the folio lock, keeps zeroed_size in sync with the block tails that were actually initialised, and revalidates cached iomaps for buffered writes. File expansion holds invalidate_lock across allocation, EOF cleanup and the i_size update. Direct writes are prepared and written back through their destination boundary folio before submission, publish i_size and valid_size only from ->end_io(), and hold invalidate_lock across completion, post-write invalidation, gap initialisation and rollback so that mmap faults cannot interfere.

V4:
- Fold the series into five patches and rebase onto current exfat/dev.
- Add a patch that serialises file expansion with mmap write faults.
- Rework direct writes: prepare and write back the invalid range through the destination boundary folio, initialise the gap after the post-write invalidation, and keep pure overwrites asynchronous.
- Track initialised block tails in zeroed_size instead of IOMAP_F_ZERO_TAIL, record the on-disk length in i_size, and finish short direct reads with filemap_read().
- Pick up the Reviewed-by on the iomap patch.

V3: https://lore.kernel.org/exfat/[email protected]/
V2: https://lore.kernel.org/exfat/[email protected]/
V1: https://lore.kernel.org/exfat/[email protected]/

Chi Zhiling (3):
iomap: export iomap_bio_read_folio_range_sync()
exfat: increase VDL before unlocking initialized folios
exfat: zero invalid VDL tails in buffered and direct reads

Namjae Jeon (2):
exfat: serialize file expansion with mmap write faults
exfat: coordinate direct writes with mmap faults

 fs/exfat/exfat_fs.h   |   2 +-
 fs/exfat/fatent.c     |   6 +-
 fs/exfat/file.c       | 427 ++++++++++++++++++++++++++++++++----------
 fs/exfat/inode.c      |  19 +-
 fs/exfat/iomap.c      | 368 ++++++++++++++++++++++++------------
 fs/exfat/iomap.h      |  10 +-
 fs/iomap/bio.c        |   1 +
 fs/iomap/internal.h   |  12 --
 include/linux/iomap.h |   9 +
 9 files changed, 599 insertions(+), 255 deletions(-)
Signature · 1 line
2.53.0
#1 lore raw

PATCH v4 1/5 iomap: export iomap_bio_read_folio_range_sync()

From: Chi Zhiling <[email protected]>

Filesystems that provide a buffered write ->read_folio_range handler need to perform the same synchronous bio read as the default handler. Move the declaration of iomap_bio_read_folio_range_sync() from the internal header to <linux/iomap.h>, together with the !CONFIG_BLOCK fallback, and export it so that modular filesystems can call it.

exfat will call it from its own ->read_folio_range handler to zero the stale bytes between valid_size and the end of the block under the folio lock during buffered writes.

---
 fs/iomap/bio.c        |  1 +
 fs/iomap/internal.h   | 12 ------------
 include/linux/iomap.h |  9 +++++++++
 3 files changed, 10 insertions(+), 12 deletions(-)
fs/iomap/bio.c +1 -0
index 153b779949e9..1dddb33c51b2 100644
@@ -147,3 +147,4 @@ int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter,
 	bio_uninit(&bio);
 	return error;
 }
+EXPORT_SYMBOL_GPL(iomap_bio_read_folio_range_sync);
fs/iomap/internal.h +0 -12
index 74e898b196dc..d13aff5e1e91 100644
@@ -20,16 +20,4 @@ static inline size_t iomap_max_bio_size(const struct iomap *iomap)
 u32 iomap_finish_ioend_buffered_read(struct iomap_ioend *ioend);
 u32 iomap_finish_ioend_direct(struct iomap_ioend *ioend);
 
-#ifdef CONFIG_BLOCK
-int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter,
-		struct folio *folio, loff_t pos, size_t len);
-#else
-static inline int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter,
-		struct folio *folio, loff_t pos, size_t len)
-{
-	WARN_ON_ONCE(1);
-	return -EIO;
-}
-#endif /* CONFIG_BLOCK */
-
 #endif /* _IOMAP_INTERNAL_H */
include/linux/iomap.h +9 -0
index 59718f73c15a..7b7ace3e1a35 100644
@@ -799,6 +799,8 @@ extern struct bio_set iomap_ioend_bioset;
 #ifdef CONFIG_BLOCK
 int iomap_bio_read_folio_range(const struct iomap_iter *iter,
 		struct iomap_read_folio_ctx *ctx, size_t plen);
+int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter,
+		struct folio *folio, loff_t pos, size_t len);
 void iomap_bio_submit_read_endio(const struct iomap_iter *iter,
 		struct iomap_read_folio_ctx *ctx, bio_end_io_t end_io);
 
@@ -825,6 +827,13 @@ static inline void iomap_bio_readahead(struct readahead_control *rac,
 
 	iomap_readahead(ops, &ctx, NULL);
 }
+#else /* !CONFIG_BLOCK */
+static inline int iomap_bio_read_folio_range_sync(const struct iomap_iter *iter,
+		struct folio *folio, loff_t pos, size_t len)
+{
+	WARN_ON_ONCE(1);
+	return -EIO;
+}
 #endif /* CONFIG_BLOCK */
 
 #endif /* LINUX_IOMAP_H */
Signature · 1 line
2.53.0
maintainer Reviewed-by on v4 1/5
#2 lore raw

Re: [PATCH v4 1/5] iomap: export iomap_bio_read_folio_range_sync()

Quoted 9 lines · Chi Zhiling

From: Chi Zhiling <[email protected]>

Filesystems that provide a buffered write ->read_folio_range handler need to perform the same synchronous bio read as the default handler. Move the declaration of iomap_bio_read_folio_range_sync() from the internal header to <linux/iomap.h>, together with the !CONFIG_BLOCK fallback, and export it so that modular filesystems can call it.

Quoted 6 lines

exfat will call it from its own ->read_folio_range handler to zero the stale bytes between valid_size and the end of the block under the folio lock during buffered writes.

Christian, if you apply this patch(1/5) to the iomap tree, I will apply the remaining patches (2-5) into the exFAT tree. Thanks!

#3 lore raw

PATCH v4 2/5 exfat: increase VDL before unlocking initialized folios

In reply to Chi Zhiling

From: Chi Zhiling <[email protected]>

Buffered writes and gap initialization can unlock initialized folios before increasing valid_size. Racing read can then treat their data as unwritten and cache zeroes instead.

Increase VDL and dirty the inode before unlocking each initialized folio. Use put_folio for ordinary buffered writes and direct-I/O buffered fallback, and increase VDL after initializing each gap folio.

Recheck the gap boundary after taking invalidate_lock and preserve the previous file size and completed initialization if a later folio fails. Increase VDL for the faulting folio only after iomap_page_mkwrite succeeds, using the current file size.

Fixes 82a81a7352bc ("exfat: add iomap buffered I/O support")
Fixes 90f4264e8b01 ("exfat: dirty all new pages when extending valid_size")
---
 fs/exfat/file.c  | 116 ++++++++++++++++++++++++++---------------------
 fs/exfat/iomap.c |  18 ++++++++
 fs/exfat/iomap.h |   1 +
 3 files changed, 83 insertions(+), 52 deletions(-)
fs/exfat/file.c +64 -52
index 5b67bbf81186..13778c72c978 100644
@@ -718,12 +718,14 @@ int exfat_file_fsync(struct file *filp, loff_t start, loff_t end, int datasync)
  * beyond the current valid_size and skips uptodate blocks.
  * Mark entire folios dirty so the newly valid range is written back.
  *
- * Call before advancing valid_size.
+ * Increase valid_size for each newly initialized range before unlocking
+ * its folio.
  */
 static int exfat_prepare_valid_range(struct inode *inode, loff_t start,
 				    loff_t end)
 {
 	struct address_space *mapping = inode->i_mapping;
+	struct exfat_inode_info *ei = EXFAT_I(inode);
 	loff_t next, pos = start;
 	struct folio *folio;
 	pgoff_t index;
@@ -733,8 +735,6 @@ static int exfat_prepare_valid_range(struct inode *inode, loff_t start,
 
 	while (pos < end) {
 		index = pos >> PAGE_SHIFT;
-		next = min(((loff_t)index + 1) << PAGE_SHIFT, end);
-
 		balance_dirty_pages_ratelimited(mapping);
 
 		folio = read_mapping_folio(mapping, index, NULL);
@@ -743,7 +743,14 @@ static int exfat_prepare_valid_range(struct inode *inode, loff_t start,
 
 		folio_lock(folio);
 		if (folio->mapping == mapping) {
-			folio_mark_dirty(folio);
+			next = min(folio_next_pos(folio), end);
+			if (next > exfat_get_valid_size(ei)) {
+				folio_mark_dirty(folio);
+				if (exfat_advance_valid_size(ei, next))
+					mark_inode_dirty(inode);
+			}
+			exfat_advance_zeroed_size(ei,
+						  round_up(next, i_blocksize(inode)));
 			pos = next;
 		}
 		folio_unlock(folio);
@@ -757,13 +764,12 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size)
 {
 	struct exfat_inode_info *ei = EXFAT_I(inode);
 	loff_t old_valid_size = exfat_get_valid_size(ei);
+	loff_t old_size, gap_start;
 	int ret = 0;
 
 	if (old_valid_size < new_valid_size) {
 		inode_dio_wait(inode);
-
-		/* Do not re-zero blocks already covered by zeroed_size. */
-		loff_t gap_start = max(old_valid_size, exfat_get_zeroed_size(ei));
+		old_size = i_size_read(inode);
 
 		if (i_size_read(inode) < new_valid_size) {
 			/*
@@ -782,23 +788,31 @@ static int exfat_extend_valid_size(struct inode *inode, loff_t new_valid_size)
 		 * is updated.
 		 */
 		filemap_invalidate_lock(inode->i_mapping);
+		/* Fault may have initialized more of the gap while we waited. */
+		gap_start = max(exfat_get_valid_size(ei),
+				exfat_get_zeroed_size(ei));
 		if (gap_start < new_valid_size)
 			unmap_mapping_range(inode->i_mapping, gap_start,
 					new_valid_size - gap_start, 0);
 		ret = exfat_prepare_valid_range(inode, gap_start, new_valid_size);
-		filemap_invalidate_unlock(inode->i_mapping);
 		if (ret) {
-			filemap_invalidate_lock(inode->i_mapping);
-			truncate_setsize(inode, old_valid_size);
-			exfat_truncate(inode);
+			/* Preserve initialized data, including stores through mmap. */
+			loff_t size = max(old_size, exfat_get_valid_size(ei));
+
+			if (size < i_size_read(inode)) {
+				truncate_setsize(inode, size);
+				exfat_truncate(inode);
+			}
 			filemap_invalidate_unlock(inode->i_mapping);
 			return ret;
 		}
 
-		exfat_set_valid_size(ei, new_valid_size);
+		/* The requested gap can already be covered by zeroed_size. */
+		if (exfat_advance_valid_size(ei, new_valid_size))
+			mark_inode_dirty(inode);
 		exfat_advance_zeroed_size(ei,
 				round_up(new_valid_size, i_blocksize(inode)));
-		mark_inode_dirty(inode);
+		filemap_invalidate_unlock(inode->i_mapping);
 	}
 
 	return ret;
@@ -829,7 +843,7 @@ static ssize_t exfat_fallback_buffered_write(struct kiocb *iocb,
 	inode_dio_wait(file_inode(iocb->ki_filp));
 
 	written = iomap_file_buffered_write(iocb, from, &exfat_write_iomap_ops,
-			NULL, NULL);
+			&exfat_iomap_write_ops, NULL);
 	if (written < 0)
 		return written;
 
@@ -921,7 +935,8 @@ static ssize_t exfat_file_write_iter(struct kiocb *iocb, struct iov_iter *iter)
 		 */
 		inode_dio_wait(inode);
 		ret = iomap_file_buffered_write(iocb, iter,
-				&exfat_write_iomap_ops, NULL, NULL);
+				&exfat_write_iomap_ops, &exfat_iomap_write_ops,
+				NULL);
 	}
 	if (ret != -EIOCBQUEUED && end > i_size_read(inode))
 		exfat_write_failed(inode);
@@ -971,56 +986,53 @@ static ssize_t exfat_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
 static vm_fault_t exfat_page_mkwrite(struct vm_fault *vmf)
 {
 	struct inode *inode = file_inode(vmf->vma->vm_file);
+	struct address_space *mapping = inode->i_mapping;
 	struct exfat_inode_info *ei = EXFAT_I(inode);
+	struct folio *folio = page_folio(vmf->page);
+	loff_t fault_start = folio_pos(folio);
+	loff_t new_valid_size, gap_start;
 	vm_fault_t ret;
-	loff_t new_valid_size, mmap_valid_size, fault_page_start;
+	int error;
 
-	if (exfat_forced_shutdown(inode->i_sb))
-		return vmf_fs_error(-EIO);
+	if (unlikely(exfat_forced_shutdown(inode->i_sb)))
+		return VM_FAULT_SIGBUS;
 
 	if (!inode_trylock(inode))
 		return VM_FAULT_RETRY;
 
-	mmap_valid_size = ((loff_t)vmf->pgoff + 1) << PAGE_SHIFT;
-	fault_page_start = ((loff_t)vmf->pgoff) << PAGE_SHIFT;
-	new_valid_size = min(mmap_valid_size, i_size_read(inode));
-
-	if (exfat_get_valid_size(ei) < new_valid_size) {
-		loff_t zeroed_size = exfat_get_zeroed_size(ei);
+	sb_start_pagefault(inode->i_sb);
+	error = file_update_time(vmf->vma->vm_file);
+	if (error) {
+		ret = vmf_fs_error(error);
+		goto out_pagefault;
+	}
+	filemap_invalidate_lock_shared(mapping);
 
-		if (zeroed_size < fault_page_start) {
-			int err;
+	if (folio->mapping != mapping || fault_start >= i_size_read(inode)) {
+		ret = VM_FAULT_NOPAGE;
+		goto out_unlock;
+	}
 
-			/*
-			 * Zero only the gap below the faulting page. The read
-			 * fault populated its folio and iomap_page_mkwrite()
-			 * will dirty it.
-			 */
-			err = exfat_prepare_valid_range(inode, zeroed_size,
-					fault_page_start);
-			if (err < 0) {
-				inode_unlock(inode);
-				return vmf_fs_error(err);
-			}
-		}
+	/* The faulting folio is already populated; initialize only its gap. */
+	gap_start = max(exfat_get_valid_size(ei), exfat_get_zeroed_size(ei));
+	error = exfat_prepare_valid_range(inode, gap_start, fault_start);
+	if (error) {
+		ret = vmf_fs_error(error);
+		goto out_unlock;
+	}
 
-		/*
-		 * Track zeroed_size by block, not page, because writeback stops
-		 * at i_size recording blocks wholly beyond it could skip a
-		 * later required zeroing.
-		 */
+	ret = iomap_page_mkwrite(vmf, &exfat_iomap_ops, NULL);
+	if (ret == VM_FAULT_LOCKED) {
+		/* Buffered write may have grown EOF before we locked the folio. */
+		new_valid_size = min(folio_next_pos(folio), i_size_read(inode));
 		exfat_advance_zeroed_size(ei,
 				round_up(new_valid_size, i_blocksize(inode)));
-		exfat_set_valid_size(ei, new_valid_size);
-		mark_inode_dirty(inode);
+		if (exfat_advance_valid_size(ei, new_valid_size))
+			mark_inode_dirty(inode);
 	}
-
-	sb_start_pagefault(inode->i_sb);
-	file_update_time(vmf->vma->vm_file);
-
-	filemap_invalidate_lock_shared(inode->i_mapping);
-	ret = iomap_page_mkwrite(vmf, &exfat_iomap_ops, NULL);
-	filemap_invalidate_unlock_shared(inode->i_mapping);
+out_unlock:
+	filemap_invalidate_unlock_shared(mapping);
+out_pagefault:
 	sb_end_pagefault(inode->i_sb);
 	inode_unlock(inode);
 
fs/exfat/iomap.c +18 -0
index 2089da8439e4..0a37ed9b7330 100644
@@ -252,6 +252,24 @@ const struct iomap_ops exfat_write_iomap_ops = {
 	.iomap_next	= exfat_write_iomap_next,
 };
 
+static void exfat_iomap_put_folio(struct inode *inode, loff_t pos,
+				  unsigned int copied, struct folio *folio)
+{
+	if (copied) {
+		struct exfat_inode_info *ei = EXFAT_I(inode);
+
+		if (exfat_advance_valid_size(ei, pos + copied))
+			mark_inode_dirty(inode);
+	}
+
+	folio_unlock(folio);
+	folio_put(folio);
+}
+
+const struct iomap_write_ops exfat_iomap_write_ops = {
+	.put_folio	= exfat_iomap_put_folio,
+};
+
 /*
  * exfat_writeback_range - Map folio during writeback
  *
fs/exfat/iomap.h +1 -0
index fd8a913f7794..39c93f8cd790 100644
@@ -9,6 +9,7 @@
 extern const struct iomap_dio_ops exfat_write_dio_ops;
 extern const struct iomap_ops exfat_iomap_ops;
 extern const struct iomap_ops exfat_write_iomap_ops;
+extern const struct iomap_write_ops exfat_iomap_write_ops;
 extern const struct iomap_writeback_ops exfat_writeback_ops;
 extern const struct iomap_read_ops exfat_iomap_bio_read_ops;
 
Signature · 1 line
2.53.0
#4 lore raw

PATCH v4 3/5 exfat: zero invalid VDL tails in buffered and direct reads

In reply to Chi Zhiling

From: Chi Zhiling <[email protected]>

Reading the block that contains VDL also reads bytes beyond that boundary. Zero those bytes before the range becomes uptodate, including when a short user copy leaves part of a write untouched.

Use the same VDL snapshot for mapping lookup and validity checks. After locking the folio, retry a stale mapping and zero invalid bytes from read_folio_range before iomap marks the range uptodate. Use iomap_bio_read_folio_range_sync() for the synchronous read and preserve the mapping snapshot until asynchronous reads complete as well.

Track initialized block tails under the folio lock and clamp that state on truncate. Remove the earlier zeroing from iomap_begin and stop using IOMAP_F_ZERO_TAIL.

Clip direct mappings to the exact VDL boundary. Return -ENOTBLK from the mapping callback for an unaligned VDL tail and finish a short direct read with filemap_read(), rather than prechecking VDL in read_iter. Use the same iomap operations for buffered and direct reads.

Fixes 9e5711b9cfe3 ("exfat: zero invalid tail on partial overwrites")
Fixes 867b9c96dc83 ("exfat: add iomap direct I/O support")
---
 fs/exfat/exfat_fs.h |   2 +-
 fs/exfat/file.c     |   7 +-
 fs/exfat/iomap.c    | 188 +++++++++++++++++++++++++++-----------------
 3 files changed, 120 insertions(+), 77 deletions(-)
fs/exfat/exfat_fs.h +1 -1
index eee573d1697c..9c43022743ed 100644
@@ -303,7 +303,7 @@ struct exfat_inode_info {
 	 * concurrent update can never regress the value or tear on 32-bit.
 	 */
 	atomic64_t valid_size;
-	/* block-aligned size zeroed in the page cache (>= valid_size) */
+	/* Initialized cache prefix, including block tails; may lag after DIO. */
 	atomic64_t zeroed_size;
 	/* hash by i_location */
 	struct hlist_node i_hash_fat;
fs/exfat/file.c +5 -2
index 13778c72c978..47e95b14d570 100644
@@ -301,10 +301,10 @@ int __exfat_truncate(struct inode *inode)
 		ei->start_clu = EXFAT_EOF_CLUSTER;
 	}
 
-	if (i_size_read(inode) < exfat_get_valid_size(ei)) {
+	if (i_size_read(inode) < exfat_get_valid_size(ei))
 		exfat_set_valid_size(ei, i_size_read(inode));
+	if (i_size_read(inode) < exfat_get_zeroed_size(ei))
 		exfat_set_zeroed_size(ei, i_size_read(inode));
-	}
 
 	if (ei->type == TYPE_FILE)
 		ei->attr |= EXFAT_ATTR_ARCHIVE;
@@ -974,6 +974,9 @@ static ssize_t exfat_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
 		file_accessed(iocb->ki_filp);
 		ret = iomap_dio_rw(iocb, iter, &exfat_iomap_ops, NULL, 0,
 				NULL, 0);
+		if (ret >= 0 && iov_iter_count(iter) &&
+		    iocb->ki_pos < i_size_read(inode))
+			ret = filemap_read(iocb, iter, ret);
 	} else {
 		ret = generic_file_read_iter(iocb, iter);
 	}
fs/exfat/iomap.c +114 -74

296 lines not on this page · raw message

Signature · 1 line
2.53.0
#5 lore raw

PATCH v4 4/5 exfat: serialize file expansion with mmap write faults

In reply to Chi Zhiling

From: Namjae Jeon <[email protected]>

File expansion changes allocation and i_size while mmap write faults can initialize the invalid range. Cleaning only the old EOF folio does not serialize the whole expansion with those faults.

Wait for direct I/O and hold invalidate_lock exclusively across cluster allocation, EOF cleanup and the i_size update. Apply this to the common expansion path used by ftruncate and fallocate.

Fixes 98431d2cd1eb ("exfat: mark straddling folio RO and zero the post-EOF range")
---
 fs/exfat/file.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)
fs/exfat/file.c +12 -1
index 47e95b14d570..0d1eeeeffa76 100644
@@ -81,7 +81,7 @@ static void exfat_pagecache_isize_extended(struct inode *inode, loff_t from,
 	folio_put(folio);
 }
 
-static int exfat_cont_expand(struct inode *inode, loff_t size)
+static int __exfat_cont_expand(struct inode *inode, loff_t size)
 {
 	int ret;
 	unsigned int num_clusters, new_num_clusters, last_clu;
@@ -158,6 +158,17 @@ static int exfat_cont_expand(struct inode *inode, loff_t size)
 	return -EIO;
 }
 
+static int exfat_cont_expand(struct inode *inode, loff_t size)
+{
+	int ret;
+
+	inode_dio_wait(inode);
+	filemap_invalidate_lock(inode->i_mapping);
+	ret = __exfat_cont_expand(inode, size);
+	filemap_invalidate_unlock(inode->i_mapping);
+	return ret;
+}
+
 /*
  * Preallocate space for a file. This implements exfat's fallocate file
  * operation, which gets called from sys_fallocate system call. User space
Signature · 1 line
2.53.0
#6 lore raw

PATCH v4 5/5 exfat: coordinate direct writes with mmap faults

In reply to Chi Zhiling

From: Namjae Jeon <[email protected]>

Direct writes can update valid_size before their data I/O completes. An mmap write fault can also initialize and dirty the invalid VDL gap while a direct write is in flight, writing zeroes over its data.

Prepare and write back the invalid range through the destination boundary folio before direct I/O, without advancing valid_size. Update i_size and valid_size after completed writes, and trim excess clusters after errors or short writes. Hold invalidate_lock through DIO completion, post-write invalidation, gap initialization, and rollback to coordinate with mmap faults. Allocate gap clusters through the normal exFAT bitmap and FAT paths, and account for short allocations and ENOSPC after partial progress.

Record the on-disk length in i_size and clamp valid_size to that length. Remove inode_trylock() from page_mkwrite, since VM_FAULT_RETRY from this callback can be ignored. Snapshot valid_size for direct reads so cache-only VDL changes cannot make disk-invalid data appear valid.

For writes entirely within a VDL snapshot, use the caller's kiocb and IOMAP_DIO_OVERWRITE_ONLY mappings. These non-allocating mappings allow native AIO overwrites to run concurrently. VDL-extending writes wait for earlier DIO and use synchronous completion. Mark overwrite mappings dirty for O_DSYNC when earlier cached writes may have advanced VDL without persisting the directory entry.

Return -EAGAIN for IOCB_NOWAIT writes, including buffered writes, because gap initialization can block. Check alignment before buffered fallback. Complete submitted BIOs after ENOSPC following partial progress, then report a short write or I/O error.

Fixes 867b9c96dc83 ("exfat: add iomap direct I/O support")
Fixes 6630ea49103c ("exfat: move extend valid_size into ->page_mkwrite()")
---
 fs/exfat/fatent.c |   6 +-
 fs/exfat/file.c   | 303 +++++++++++++++++++++++++++++++++++++---------
 fs/exfat/inode.c  |  19 +--
 fs/exfat/iomap.c  | 172 ++++++++++++++++++--------
 fs/exfat/iomap.h  |   9 +-
 5 files changed, 385 insertions(+), 124 deletions(-)
fs/exfat/fatent.c +4 -2
index 9f4607fced7f..ebeecbe45e61 100644
@@ -456,8 +456,10 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 	}
 
 	if (num_alloc > total_cnt - sbi->used_clusters) {
-		ret = -ENOSPC;
-		goto unlock;
+		/* A contiguous mapping can use a shorter allocation. */
+		if (!contig || sbi->used_clusters == total_cnt)
+			goto unlock;
+		num_alloc = total_cnt - sbi->used_clusters;
 	}
 
 	hint_clu = p_chain->dir;
fs/exfat/file.c +249 -54

443 lines not on this page · raw message

fs/exfat/inode.c +5 -14
index 4bea9e9deb94..7071f603b57b 100644
@@ -73,25 +73,16 @@ int __exfat_write_inode(struct inode *inode, int sync)
 			     &ep->dentry.file.access_date,
 			     NULL);
 
-	/*
-	 * During a DIO write, valid_size is updated eagerly in iomap_end (so
-	 * that concurrent buffered reads see IOMAP_MAPPED) while i_size is
-	 * updated asynchronously in end_io.  The FAT chain was already
-	 * extended to cover ceil(valid_size/cluster_size) clusters.  Use the
-	 * maximum so the on-disk size field always covers the FAT chain,
-	 * preventing fsck from reporting "more clusters are allocated".
-	 */
-	on_disk_size = max_t(unsigned long long, i_size_read(inode),
-			valid_size);
+	/* Direct writes publish the completed size in their end_io handler. */
+	on_disk_size = i_size_read(inode);
 
 	if (ei->start_clu == EXFAT_EOF_CLUSTER)
 		on_disk_size = 0;
 	/*
-	 * valid_size on disk must reflect only confirmed data (up to i_size)
-	 * and must not exceed on_disk_size.
+	 * Truncate can publish a smaller i_size before lowering valid_size.
+	 * Never record a valid_size greater than the recorded file size.
 	 */
-	on_disk_valid_size = min_t(unsigned long long, valid_size,
-			i_size_read(inode));
+	on_disk_valid_size = min_t(unsigned long long, valid_size, on_disk_size);
 	if (ei->start_clu == EXFAT_EOF_CLUSTER)
 		on_disk_valid_size = 0;
 
fs/exfat/iomap.c +119 -53

234 lines not on this page · raw message

fs/exfat/iomap.h +8 -1
index 39c93f8cd790..f8f018f87230 100644
@@ -6,10 +6,17 @@
 #ifndef _LINUX_EXFAT_IOMAP_H
 #define _LINUX_EXFAT_IOMAP_H
 
-extern const struct iomap_dio_ops exfat_write_dio_ops;
+/* One synchronous attempt for a direct write extending valid_size. */
+struct exfat_dio {
+	struct kiocb iocb;
+	loff_t start;
+	loff_t completed;
+};
+
 extern const struct iomap_ops exfat_iomap_ops;
 extern const struct iomap_ops exfat_write_iomap_ops;
 extern const struct iomap_write_ops exfat_iomap_write_ops;
+extern const struct iomap_write_ops exfat_dio_gap_write_ops;
 extern const struct iomap_writeback_ops exfat_writeback_ops;
 extern const struct iomap_read_ops exfat_iomap_bio_read_ops;
 
Signature · 1 line
2.53.0
maintainer Applied
#7 lore raw

Re: (subset) [PATCH v4 0/5] exfat: fix valid_size update races

In reply to Chi Zhiling
Quoted 10 lines · Chi Zhiling

From: Chi Zhiling <[email protected]>

exFAT uses valid_size (ValidDataLength) as the on-disk boundary of initialised data, but the current code advances it too late and without proper serialisation. Buffered writes can silently lose data reclaimed before valid_size covers it, file expansion and page faults can initialise the same range concurrently, and a failed or short direct write can still grow the file on disk.

[...]

Applied to the vfs-7.5.iomap branch of the vfs/vfs.git tree. Patches in the vfs-7.5.iomap branch should appear in linux-next soon.

Please report any outstanding bugs that were missed during review in a new review to the original patch series allowing us to drop it.

It's encouraged to provide Acked-bys and Reviewed-bys even though the patch has now been applied. If possible patch trailers will be updated.

Note that commit hashes shown below are subject to change due to rebase, trailer updates or similar. If in doubt, please check the listed branch.

tree:   https://git.kernel.org/pub/scm/linux/kernel/git/vfs/vfs.git
branch: vfs-7.5.iomap

[1/5] iomap: export iomap_bio_read_folio_range_sync()

      https://git.kernel.org/vfs/vfs/c/4c7bbc7f82ff
maintainer
#8 lore raw
In reply to Chi Zhiling
Quoted 36 lines · Chi Zhiling

From: Chi Zhiling <[email protected]>

exFAT uses valid_size (ValidDataLength) as the on-disk boundary of initialised data, but the current code advances it too late and without proper serialisation. Buffered writes can silently lose data reclaimed before valid_size covers it, file expansion and page faults can initialise the same range concurrently, and a failed or short direct write can still grow the file on disk.

This series advances valid_size under the folio lock, keeps zeroed_size in sync with the block tails that were actually initialised, and revalidates cached iomaps for buffered writes. File expansion holds invalidate_lock across allocation, EOF cleanup and the i_size update. Direct writes are prepared and written back through their destination boundary folio before submission, publish i_size and valid_size only from ->end_io(), and hold invalidate_lock across completion, post-write invalidation, gap initialisation and rollback so that mmap faults cannot interfere.

V4:
- Fold the series into five patches and rebase onto current exfat/dev.
- Add a patch that serialises file expansion with mmap write faults.
- Rework direct writes: prepare and write back the invalid range through the destination boundary folio, initialise the gap after the post-write invalidation, and keep pure overwrites asynchronous.
- Track initialised block tails in zeroed_size instead of IOMAP_F_ZERO_TAIL, record the on-disk length in i_size, and finish short direct reads with filemap_read().
- Pick up the Reviewed-by on the iomap patch.

V3: https://lore.kernel.org/exfat/[email protected]/
V2: https://lore.kernel.org/exfat/[email protected]/
V1: https://lore.kernel.org/exfat/[email protected]/

Quoted 8 lines

Chi Zhiling (3):
iomap: export iomap_bio_read_folio_range_sync()
exfat: increase VDL before unlocking initialized folios
exfat: zero invalid VDL tails in buffered and direct reads

Namjae Jeon (2):
exfat: serialize file expansion with mmap write faults
exfat: coordinate direct writes with mmap faults

Applied 2/5 ~ 5/5 patches to #dev.
Thanks!