Skip to contentSkip to conversation

fs/iomap/xfs: generation-based DIO range draining

RFC PATCH New Vitali Lovich 1 participant 7 messages Oct 19

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

cover fs/iomap/xfs: generation-based DIO range draining

The core problem this patch series tries to address is how to keep read IOPS up and read latency down in the face of concurrent (but non-overlapping) hole punching or writes past the EOF with gaps.

Previous ideas have explored the idea of using range tracking for operations. The downside is that it has a small but measurable overhead for IOPs throughput, increased CPU usage, and more memory usage. Range tracking also enables more concurrency of certain write operations of unrelated ranges.

The core idea of this patch series is instead to ignore trying to support hole punches of unrelated regions. Instead, hole punching (and writes past the end with gaps) remain exclusive of each other and update a read-optimized data structure to contain the range they're operating on. Reads then check against this range on submission to know if they need to defer themselves against a pending hole punch. This flips the problem and side-steps the need for interval tracking, resulting in no overhead for pure-read scenarios.

As the data at the end shows, this patch series solves a good chunk of the read IOPs and latency performance under concurrent hole punches while showing no impact on pure read workloads. There remain two additional sources of contention that show up; the exclusive metadata lock (extent mapping + modified timestamps when not using lazytime) and the ili_lock which is unnecessarily checked for reads. I have prototyped optimizing the extent metadata mapping and it shows read IOPs and read latency approach the uncontended case even with a large number of concurrent hole punches. It also significantly improves the "reduced" hole punching performance the numbers below show (I explain below why it's a phantom reduction and not a bug in the patch set). Fixing the ili_lock contention on top of this should largely eliminate the remaining contention bottleneck between readers and hole punching.

I'll also note that even in the uncontended read cases, this performs slightly better in pure reads and, combined with the metadata mapping contention improvement, results in a ~2-6% speedup for read-only workloads; this patchset by itself is more modest for pure read workload wins.

The specific mechanism this patch series implements is:
* Introduces a new draining lock that hole punching and writes past end need to acquire. This ensures that concurrent hole punching, as currently, can only happen one at a time. This restriction is not lifted by this patchset.
* Once the lock is acquired, the drainer updates a seqcount_latch_t protected exclusion range and reading counter with the number of currently outstanding DIOs acts as the natural barrier. We use a single bit generation counter to dilineate DIO cohorts that may have not observed the installed latch and those that definitely did. The former on completion will notice the writer is waiting for draining and they count off and know when to wake the writer that the OPs it's waiting to drain have completed.
* The read path checks the seqcount_latch_t state cheaply and safely so that it knows upon start which drain generation it's part of and which range to potentially check on. Conflicting rights take the slow path and will wait for the already started draining - the head of line blocking that occurs here is no different than the current status quo, except only overlapping reads are impacted.

The i_dio_counter acts as the barrier mechanism for the latch snapshot protocol. This upgrades the relaxed increment of the counter on registration into fully ordered. While I confirmed this has no observable impact on pure read workloads, I don't have access to a weakly ordered machine with huge concurrency to confirm it doesn't have an impact on less concurrency. The SeqCst consistency in this patch set could be optimized to use Acquire/Release instead, but I decided to be a bit more conservative here.

Patches 1-3 add VFS accounting, iomap ownership, documentation, a focused LKMM litmus test, and KUnit coverage. Patches 4-6 integrate admission and the two consumers in XFS. The ext4 change only adapts the iomap helper signature.

KUnit, two CPUs: 5 passed, 0 failed, 0 skipped LKMM, herd7 7.58: Forbidden outcome Never
XFS debug + lockdep fstests: 16 passed, 0 failed, 0 skipped

Performance measurements gathered as requested in:
https://lore.kernel.org/linux-xfs/atF7xJlbck-xA1G3@dread/T/#m203f6ae3899e7061afc847a45f72abd9d257dfef

Workload is number of concurrent readers + writers. Hole punches column is the workers attempting to hit 1000/s and the effective number actually reached. All IOPs are hitting the same inode. Read IOPs are in millions and P99.9 is in milliseconds.

kernel | readers/workers | punches/s | read IOPS | read P99.9 (ms)
----------+-----------------+-----------+-----------+----------------

baseline  |       1/0       |      0.00 |   592,088 |           0.214
latch     |       1/0       |      0.00 |   584,266 |           0.189
baseline  |       1/1       |    989.44 |   400,052 |           0.758
latch     |       1/1       |    790.79 |   522,255 |           0.436
baseline  |       1/8       |    879.33 |    32,103 |           5.603
latch     |       1/8       |    768.11 |   261,712 |           1.221
baseline  |       1/32      |    998.67 |    15,721 |          16.318
latch     |       1/32      |    704.56 |   256,991 |           1.237
baseline  |       1/64      |    999.81 |    25,364 |          12.517
latch     |       1/64      |    711.11 |   256,288 |           1.221
----------+-----------------+-----------+-----------+----------------
baseline  |       8/0       |      0.00 | 2,159,746 |           0.416
latch     |       8/0       |      0.00 | 2,142,864 |           0.387
baseline  |       8/1       |    300.72 |   715,545 |           2.867
latch     |       8/1       |    131.08 | 1,302,691 |           4.047
baseline  |       8/8       |    744.09 |   185,504 |           6.193
latch     |       8/8       |    204.85 |   594,782 |           4.014
baseline  |       8/32      |    999.41 |    66,411 |          15.663
latch     |       8/32      |    205.75 |   594,228 |           4.014
baseline  |       8/64      |    940.88 |    22,154 |          43.778
latch     |       8/64      |    203.97 |   593,788 |           4.014
----------+-----------------+-----------+-----------+----------------
baseline  |      32/0       |      0.00 | 2,467,761 |           1.221
latch     |      32/0       |      0.00 | 2,497,401 |           0.913
baseline  |      32/1       |    129.01 |   653,812 |           6.914
latch     |      32/1       |     65.50 | 1,112,291 |           6.783
baseline  |      32/8       |    507.07 |   347,173 |          10.289
latch     |      32/8       |     89.23 |   750,753 |           9.765
baseline  |      32/32      |    617.12 |   112,667 |          25.559
latch     |      32/32      |     88.54 |   751,453 |           9.765
baseline  |      32/64      |    821.00 |    70,012 |          42.205
latch     |      32/64      |     88.81 |   750,884 |           9.765
----------+-----------------+-----------+-----------+----------------
baseline  |      64/0       |      0.00 | 2,511,819 |           1.761
latch     |      64/0       |      0.00 | 2,520,544 |           1.761
latch+fix |      64/0       |      0.00 | 2,682,546 |           2.245
baseline  |      64/1       |     65.46 |   677,507 |          13.042
latch     |      64/1       |     39.78 | 1,036,213 |          10.682
latch+fix |      64/1       |    690.05 | 2,619,882 |           2.277
baseline  |      64/8       |    326.80 |   383,964 |          18.481
latch     |      64/8       |     48.12 |   801,694 |          18.481
latch+fix |      64/8       |    539.84 | 2,506,797 |           3.785
baseline  |      64/32      |    472.71 |   142,776 |          39.059
latch     |      64/32      |     48.04 |   800,569 |          18.481
latch+fix |      64/32      |    526.69 | 2,505,012 |           3.785
baseline  |      64/64      |    659.57 |    86,426 |          63.701
latch     |      64/64      |     47.92 |   800,364 |          18.481
latch+fix |      64/64      |    541.89 | 2,508,080 |           3.752
----------+-----------------+-----------+-----------+----------------
baseline  |     128/0       |      0.00 | 2,703,411 |           3.195
latch     |     128/0       |      0.00 | 2,738,430 |           3.129
latch+fix |     128/0       |      0.00 | 2,780,706 |           3.097
baseline  |     128/1       |     35.24 |   698,842 |          25.035
latch     |     128/1       |     21.83 | 1,003,072 |          18.743
latch+fix |     128/1       |    349.77 | 2,612,422 |          47.972
baseline  |     128/8       |    233.86 |   525,114 |          25.559
latch     |     128/8       |     26.26 |   857,379 |          33.817
latch+fix |     128/8       |    324.93 | 2,549,251 |          52.167
baseline  |     128/32      |    468.56 |   279,933 |          42.729
latch     |     128/32      |     26.04 |   855,151 |          34.341
latch+fix |     128/32      |    396.54 | 2,557,483 |           5.341
baseline  |     128/64      |    500.56 |   140,166 |          80.216
latch     |     128/64      |     26.13 |   853,051 |          34.341
latch+fix |     128/64      |    363.48 | 2,561,624 |          35.914

As I call out above, punch throughput seems to crash / not scale as well as it does today. This isn't some bug in the patch set. Instead, what happens is that the increased read IOPs that don't block on the I/O lock causes more contention on the metadata lock and in this case the writer loses. If you kept read IOPs artificially lower at the throughput we could manage before, then hole punch IOPs would rise. So this patch set on its own could result in regression of hole punch IOPs performance in the face of a lot of concurrent readers on the same inode. This is only intended as a temporary state of affairs though. Once this approach is approved, I'll present how the metadata extent mapping contention could be lifted. When that is done, hole punching performance under concurrent read IOPs largely restores, read IOPs are almost identical with and without hole punching, and read P99.9 latency is similarly reduced further to the uncontended read case. Perf profiles and tracing point to the ili_lock contention as the final area to cut this gap further.

Tradeoffs this patch series introduces:
* xfs inode struct grows by 1 cache line because there's no padding available to absorb the pointer we add. The callbacks used in the FS layer ensure only filesystems opting into this new codepath pay for that pointer.
* Hole punch throughput can suffer under heavier concurrent read contention that is now possible. This is fixable.

Vitali Lovich (6):
fs: implement range-based generation-coordinated DIO draining
iomap: support generation accounting and caller-registered DIO
fs: add KUnit coverage for generation-based DIO draining
xfs: add range-drain state and latch-based DIO admission
xfs: use range-based DIO draining for aligned hole punches
xfs: use range-based DIO draining for post-EOF zeroing

 Documentation/filesystems/locking.rst         |  89 ++--
 Documentation/filesystems/vfs.rst             |  41 ++
 fs/Kconfig                                    |  13 +
 fs/Makefile                                   |   1 +
 fs/ext4/file.c                                |   2 +-
 fs/inode.c                                    | 120 +++++-
 fs/iomap/direct-io.c                          |  36 +-
 fs/tests/dio_drain_kunit.c                    | 393 ++++++++++++++++++
 fs/xfs/xfs_bmap_util.c                        |   9 +-
 fs/xfs/xfs_file.c                             | 343 +++++++++++++--
 fs/xfs/xfs_icache.c                           |   2 +
 fs/xfs/xfs_inode.c                            |  10 +
 fs/xfs/xfs_inode.h                            |   1 +
 fs/xfs/xfs_iops.c                             |   9 +
 fs/xfs/xfs_reflink.h                          |   2 +-
 include/linux/fs.h                            |  97 ++++-
 include/linux/iomap.h                         |  56 ++-
 .../litmus-tests/DIO-register-first.litmus    |  36 ++
 18 files changed, 1172 insertions(+), 88 deletions(-)
 create mode 100644 fs/tests/dio_drain_kunit.c
 create mode 100644 tools/memory-model/litmus-tests/DIO-register-first.litmus

base-commit: 0fcb05b72344f40806cbe810de8872f1698bf053

Signature · 1 line
2.56.0
#1 lore raw

RFC PATCH 1/6 fs: implement range-based generation-coordinated DIO draining

Whole-inode direct I/O (DIO) draining currently requires filesystems to exclude all new submission requests, even those completely disjoint from the range being modified.

Add generation accounting and range admission to allow filesystems to drain a finite cohort of in-flight DIO while concurrently admitting new, disjoint DIO under a shared i_rwsem.

This reserves the top two bits of i_inode->i_dio_count for generation and draining state, utilizes seqcount_latch_t for lockless range snapshot validation, and introduces a new ->dio_drain_complete VFS operation to resolve private drain state lazily without bloating struct inode or per-request storage.

---
 Documentation/filesystems/locking.rst         |  89 ++++++++++-----
 Documentation/filesystems/vfs.rst             |  41 +++++++
 fs/inode.c                                    | 107 +++++++++++++++++-
 fs/xfs/xfs_reflink.h                          |   2 +-
 include/linux/fs.h                            |  92 ++++++++++++++-
 .../litmus-tests/DIO-register-first.litmus    |  36 ++++++
 6 files changed, 334 insertions(+), 33 deletions(-)
 create mode 100644 tools/memory-model/litmus-tests/DIO-register-first.litmus
Documentation/filesystems/locking.rst +59 -30
index 844d65eb47a5..7ae93f04dc69 100644
@@ -93,40 +93,44 @@ prototypes::
 	int (*fileattr_get)(struct dentry *dentry, struct file_kattr *fa);
 	struct posix_acl * (*get_acl)(struct mnt_idmap *, struct dentry *, int);
 	struct offset_ctx *(*get_offset_ctx)(struct inode *inode);
+	void (*dio_drain_complete)(struct inode *inode);
 
 locking rules:
-	all may block
+	all may block except dio_drain_complete
 
-==============	==================================================
-ops		i_rwsem(inode)
-==============	==================================================
-lookup:		shared
-create:		exclusive
-link:		exclusive (both)
-mknod:		exclusive
-symlink:	exclusive
-mkdir:		exclusive
-unlink:		exclusive (both)
-rmdir:		exclusive (both)(see below)
-rename:		exclusive (both parents, some children)	(see below)
-readlink:	no
-get_link:	no
-setattr:	exclusive
-permission:	no (may not block if called in rcu-walk mode)
-get_inode_acl:	no
-get_acl:	no
-getattr:	no
-listxattr:	no
-fiemap:		no
-update_time:	no
-sync_lazytime:	no
-atomic_open:	shared (exclusive if O_CREAT is set in open flags)
-tmpfile:	no
-fileattr_get:	no or exclusive
-fileattr_set:	exclusive
-get_offset_ctx  no
-==============	==================================================
+==================  ==================================================
+ops                 i_rwsem(inode)
+==================  ==================================================
+lookup:             shared
+create:             exclusive
+link:               exclusive (both)
+mknod:              exclusive
+symlink:            exclusive
+mkdir:              exclusive
+unlink:             exclusive (both)
+rmdir:              exclusive (both)(see below)
+rename:             exclusive (both parents, some children) (see below)
+readlink:           no
+get_link:           no
+setattr:            exclusive
+permission:         no (may not block if called in rcu-walk mode)
+get_inode_acl:      no
+get_acl:            no
+getattr:            no
+listxattr:          no
+fiemap:             no
+update_time:        no
+sync_lazytime:      no
+atomic_open:        shared (exclusive if O_CREAT is set in open flags)
+tmpfile:            no
+fileattr_get:       no or exclusive
+fileattr_set:       exclusive
+get_offset_ctx      no
+dio_drain_complete  no
+==================  ==================================================
 
+->dio_drain_complete() does not require i_rwsem and must not block. It may
+run in interrupt context.
 
 	Additionally, ->rmdir(), ->unlink() and ->rename() have ->i_rwsem
 	exclusive on victim.
@@ -138,6 +142,31 @@ get_offset_ctx  no
 See Documentation/filesystems/directory-locking.rst for more detailed discussion
 of the locking scheme for directory operations.
 
+Direct I/O range draining
+=========================
+
+Range drainers acquire ``drain->lock`` before ``inode->i_rwsem`` and any
+filesystem locks needed by the protected operation. Hold the drain mutex
+through inode_dio_drain_finish(): it serializes range publication, cohort
+draining, the protected operation, and exclusion removal. Never wait for
+this mutex while holding i_rwsem, even shared.
+
+A drainer can drop i_rwsem and reacquire it exclusively during write
+checks, for example to strip privileges. Acquiring the mutex inside shared
+i_rwsem would permit this deadlock:
+
+1. Drainer A holds the drain mutex and shared i_rwsem.
+2. Drainer B holds shared i_rwsem and waits for A's drain mutex.
+3. A drops shared i_rwsem and tries to acquire it exclusively. B's shared
+   lock prevents A from proceeding, while B cannot release it until A
+   releases the mutex.
+
+Callers that already hold i_rwsem must drop it before waiting for the drain
+mutex, then reacquire i_rwsem and repeat their checks. DIO admission and
+completion do not acquire the drain mutex, so the old cohort can complete
+while a drainer holds it. Drain the old cohort before taking any filesystem
+lock that its I/O preparation or completion might need.
+
 xattr_handler operations
 ========================
 
Documentation/filesystems/vfs.rst +41 -0

53 lines not on this page · raw message

fs/inode.c +106 -1

122 lines not on this page · raw message

fs/xfs/xfs_reflink.h +1 -1
index 683c1841e640..c862b9a01c78 100644
@@ -20,7 +20,7 @@ xfs_can_free_cowblocks(struct xfs_inode *ip)
 	if ((inode_state_read_once(inode) & I_DIRTY_PAGES) ||
 	    mapping_tagged(inode->i_mapping, PAGECACHE_TAG_DIRTY) ||
 	    mapping_tagged(inode->i_mapping, PAGECACHE_TAG_WRITEBACK) ||
-	    atomic_read(&inode->i_dio_count))
+	    !inode_dio_finished(inode))
 		return false;
 	return true;
 }
include/linux/fs.h +91 -1

116 lines not on this page · raw message

tools/memory-model/litmus-tests/DIO-register-first.litmus new file +36 -0
new file mode 100644
index 000000000000..a7bca403bdfa
@@ -0,0 +1,36 @@
+C DIO-register-first
+
+(*
+ * Result: Never
+ *
+ * Model one drain cutover, with count bit 0 and generation bit 1.
+ * Publishing both latch copies (or the first initialized drain pointer)
+ * precedes the fully ordered generation RMW. An admission increment which
+ * follows the cutover must see the exclusion. A pre-cutover registration is
+ * instead accounted in the finite old cohort. Completion and subsequent
+ * latch reuse are deliberately outside this single-cutover ordering model.
+ *)
+
+{
+	atomic_t count = 0;
+	int active = 0;
+}
+
+P0(atomic_t *count, int *active)
+{
+	int r0;
+
+	WRITE_ONCE(*active, 1);
+	r0 = atomic_fetch_add(2, count);
+}
+
+P1(atomic_t *count, int *active)
+{
+	int r0;
+	int r1;
+
+	r0 = atomic_fetch_add(1, count);
+	r1 = READ_ONCE(*active);
+}
+
+exists (1:r0=2 /\ 1:r1=0)

base-commit: 0fcb05b72344f40806cbe810de8872f1698bf053

Signature · 1 line
2.56.0
#2 lore raw

RFC PATCH 2/6 iomap: support generation accounting and caller-registered DIO

In reply to Vitali Lovich

Generation draining requires every DIO request on an opted-in inode to preserve its admission generation until completion. Convert both generic iomap DIO and the simple-read path to generation-aware accounting, reusing their existing internal flag fields.

Allow callers to register DIO before entering iomap with IOMAP_DIO_ACCOUNTED and pass the saved token in IOMAP_DIO_GENERATION. Iomap owns that registration and releases it on completion or any early return, including allocation failures, empty requests and -ENOTBLK. Callers retrying through the generic path must acquire a fresh admission. Callers without a registration retain internal iomap accounting.

Pass the flags into iomap_dio_read_simple() and update existing XFS and ext4 callers to pass zero. Preserve the token through mapping and submission errors, and read it before bio_put() frees the bio-backed simple-read struct. The completion lifetime still includes filesystem end_io work and post-write invalidation.

---
 fs/ext4/file.c        |  2 +-
 fs/iomap/direct-io.c  | 36 +++++++++++++++++++++-------
 fs/xfs/xfs_file.c     |  2 +-
 include/linux/iomap.h | 56 +++++++++++++++++++++++++++++--------------
 4 files changed, 67 insertions(+), 29 deletions(-)
fs/ext4/file.c +1 -1
index 374b4bc25bd5..b4e791b1c32d 100644
@@ -91,7 +91,7 @@ static ssize_t ext4_dio_read_iter(struct kiocb *iocb, struct iov_iter *to)
 		return generic_file_read_iter(iocb, to);
 	}
 
-	ret = iomap_dio_read_simple(iocb, to, ext4_iomap_begin);
+	ret = iomap_dio_read_simple(iocb, to, ext4_iomap_begin, 0);
 	if (ret == -ENOTBLK)
 		ret = iomap_dio_rw(iocb, to, &ext4_iomap_ops, NULL, 0, NULL, 0);
 	inode_unlock_shared(inode);
fs/iomap/direct-io.c +27 -9
index 8b4039d16ce8..25b8625b6175 100644
@@ -140,7 +140,8 @@ ssize_t iomap_dio_complete(struct iomap_dio *dio)
 	    !(dio->flags & IOMAP_DIO_NO_INVALIDATE))
 		kiocb_invalidate_post_direct_write(iocb, dio->size);
 
-	inode_dio_end(file_inode(iocb->ki_filp));
+	inode_dio_end_generation(file_inode(iocb->ki_filp),
+				dio->flags & IOMAP_DIO_GENERATION);
 
 	if (ret > 0) {
 		iocb->ki_pos += ret;
@@ -683,6 +684,12 @@ static int iomap_dio_iter(struct iomap_iter *iter, struct iomap_dio *dio)
  * the correct total number of bytes transferred; this is essential for
  * completing partial requests asynchronously.
  *
+ * When @dio_flags includes IOMAP_DIO_ACCOUNTED, iomap takes ownership of the
+ * caller's registration from inode_dio_try_begin() on entry, with its saved
+ * generation token supplied in IOMAP_DIO_GENERATION. Iomap releases the
+ * registration on completion or any early error or NULL return, including
+ * -ENOTBLK. Callers retrying the request must acquire a fresh registration.
+ *
  * Returns -ENOTBLK In case of a page invalidation invalidation failure for
  * writes.  The callers needs to fall back to buffered I/O in this case.
  */
@@ -701,6 +708,8 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
 	};
 	bool wait_for_completion =
 		is_sync_kiocb(iocb) || (dio_flags & IOMAP_DIO_FORCE_WAIT);
+	bool accounted = dio_flags & IOMAP_DIO_ACCOUNTED;
+	bool generation = dio_flags & IOMAP_DIO_GENERATION;
 	struct blk_plug plug;
 	struct iomap_dio *dio;
 	loff_t ret = 0;
@@ -708,11 +717,13 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
 	trace_iomap_dio_rw_begin(iocb, iter, dio_flags, done_before);
 
 	if (!iomi.len)
-		return NULL;
+		goto out_account;
 
 	dio = kmalloc_obj(*dio);
-	if (!dio)
-		return ERR_PTR(-ENOMEM);
+	if (!dio) {
+		ret = -ENOMEM;
+		goto out_account;
+	}
 
 	dio->iocb = iocb;
 	atomic_set(&dio->ref, 1);
@@ -809,7 +820,10 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
 			goto out_free_dio;
 	}
 
-	inode_dio_begin(inode);
+	if (!accounted)
+		generation = inode_dio_begin_generation(inode);
+	if (generation)
+		dio->flags |= IOMAP_DIO_GENERATION;
 
 	blk_start_plug(&plug);
 	while ((ret = iomap_iter(&iomi, ops)) > 0) {
@@ -894,6 +908,9 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,
 
 out_free_dio:
 	kfree(dio);
+out_account:
+	if (accounted)
+		inode_dio_end_generation(inode, generation);
 	if (ret)
 		return ERR_PTR(ret);
 	return NULL;
@@ -937,6 +954,7 @@ static ssize_t iomap_dio_simple_complete(struct iomap_dio_simple *sr)
 	struct bio *bio = &sr->bio;
 	struct kiocb *iocb = sr->iocb;
 	struct inode *inode = file_inode(iocb->ki_filp);
+	bool generation = sr->dio_flags & IOMAP_DIO_GENERATION;
 	ssize_t ret;
 
 	if (unlikely(bio->bi_status)) {
@@ -956,7 +974,7 @@ static ssize_t iomap_dio_simple_complete(struct iomap_dio_simple *sr)
 		bio_release_pages(bio, false);
 		bio_put(bio);
 	}
-	inode_dio_end(inode);
+	inode_dio_end_generation(inode, generation);
 	trace_iomap_dio_complete(iocb, ret < 0 ? ret : 0, ret);
 	return ret;
 }
@@ -990,7 +1008,7 @@ static void iomap_dio_simple_end_io(struct bio *bio)
 }
 
 ssize_t __iomap_dio_read_simple(struct kiocb *iocb, struct iov_iter *iter,
-		struct iomap_iter *iomi)
+		struct iomap_iter *iomi, bool generation)
 {
 	gfp_t gfp = (iomi->flags & IOMAP_NOWAIT) ? GFP_NOWAIT : GFP_KERNEL;
 	struct iomap_dio_simple *sr;
@@ -1029,7 +1047,7 @@ ssize_t __iomap_dio_read_simple(struct kiocb *iocb, struct iov_iter *iter,
 	}
 	sr = container_of(bio, struct iomap_dio_simple, bio);
 	sr->iocb = iocb;
-	sr->dio_flags = 0;
+	sr->dio_flags = generation ? IOMAP_DIO_GENERATION : 0;
 
 	bio->bi_iter.bi_sector = iomap_sector(&iomi->iomap, iomi->pos);
 	bio->bi_ioprio = iocb->ki_ioprio;
@@ -1074,7 +1092,7 @@ ssize_t __iomap_dio_read_simple(struct kiocb *iocb, struct iov_iter *iter,
 out_bio_put:
 	bio_put(bio);
 out_dio_end:
-	inode_dio_end(iomi->inode);
+	inode_dio_end_generation(iomi->inode, generation);
 	return ret;
 }
 EXPORT_SYMBOL_GPL(__iomap_dio_read_simple);
fs/xfs/xfs_file.c +1 -1
index d8202da15aca..d4446887453f 100644
@@ -255,7 +255,7 @@ xfs_file_dio_read(
 				&xfs_dio_read_bounce_ops, IOMAP_DIO_BOUNCE,
 				NULL, 0);
 	} else {
-		ret = iomap_dio_read_simple(iocb, to, xfs_read_iomap_begin);
+		ret = iomap_dio_read_simple(iocb, to, xfs_read_iomap_begin, 0);
 		if (ret == -ENOTBLK)
 			ret = iomap_dio_rw(iocb, to, &xfs_read_iomap_ops, NULL,
 					0, NULL, 0);
include/linux/iomap.h +38 -18

99 lines not on this page · raw message

Signature · 1 line
2.56.0
#3 lore raw

RFC PATCH 3/6 fs: add KUnit coverage for generation-based DIO draining

In reply to Vitali Lovich

Exercise admission before lazy allocation, rejection of overlapping DIO, disjoint new-generation requests and cohort rollover. Check that iomap consumes caller registrations on simple-read fallback and generic early returns, including an old-generation completion during an active drain.

Keep generation registration inline in normal builds. When DIO_DRAIN_KUNIT_TEST is enabled, provide an out-of-line definition in fs/inode.c with a static stub and one function address across translation units. Keep the KUnit stub headers out of linux/fs.h.

Use the stub to pause the real admission helper after its provisional increment and before its first pointer load. Publish the first drain allocation and verify that cutover completes while the reader is paused. The resumed overlapping admission must reject the request and withdraw its old-generation registration. Release both threads and any outstanding DIO count before reporting failures. Skip this race test without two online CPUs.

Check snapshot reads while a latch writer is interrupted at either copy update, and exercise repeated cutover and range reuse across both generations.

---
 fs/Kconfig                 |  13 ++
 fs/Makefile                |   1 +
 fs/inode.c                 |  13 ++
 fs/tests/dio_drain_kunit.c | 393 +++++++++++++++++++++++++++++++++++++
 include/linux/fs.h         |   5 +
 5 files changed, 425 insertions(+)
 create mode 100644 fs/tests/dio_drain_kunit.c
fs/Kconfig +13 -0
index e05917adcd60..4d4fff6e217b 100644
@@ -421,4 +421,17 @@ source "fs/unicode/Kconfig"
 config IO_WQ
 	bool
 
+config DIO_DRAIN_KUNIT_TEST
+	tristate "KUnit tests for direct I/O range draining" if !KUNIT_ALL_TESTS
+	depends on KUNIT && BLOCK
+	select FS_IOMAP
+	default KUNIT_ALL_TESTS
+	help
+	  Test direct I/O range admission, generation accounting, and
+	  seqcount_latch range snapshots across cohort cutovers, including
+	  iomap early-return ownership and delayed-admission races.
+	  The concurrent admission test requires at least two online CPUs.
+
+	  If unsure, say N.
+
 endmenu
fs/Makefile +1 -0
index 055dfc23d82b..55714a15a8d1 100644
@@ -28,6 +28,7 @@ obj-$(CONFIG_SIGNALFD)		+= signalfd.o
 obj-$(CONFIG_TIMERFD)		+= timerfd.o
 obj-$(CONFIG_EVENTFD)		+= eventfd.o
 obj-$(CONFIG_AIO)               += aio.o
+obj-$(CONFIG_DIO_DRAIN_KUNIT_TEST) += tests/dio_drain_kunit.o
 obj-$(CONFIG_FS_DAX)		+= dax.o
 obj-$(CONFIG_FS_ENCRYPTION)	+= crypto/
 obj-$(CONFIG_FS_VERITY)		+= verity/
fs/inode.c +13 -0
index cb35eefe0d40..4642a1977c01 100644
@@ -23,6 +23,9 @@
 #include <linux/rw_hint.h>
 #include <linux/seq_file.h>
 #include <linux/debugfs.h>
+#if IS_ENABLED(CONFIG_DIO_DRAIN_KUNIT_TEST)
+#include <kunit/static_stub.h>
+#endif
 #include <trace/events/writeback.h>
 #define CREATE_TRACE_POINTS
 #include <trace/events/timestamp.h>
@@ -2772,6 +2775,16 @@ bool inode_dio_finished(const struct inode *inode)
 }
 EXPORT_SYMBOL(inode_dio_finished);
 
+#if IS_ENABLED(CONFIG_DIO_DRAIN_KUNIT_TEST)
+bool inode_dio_begin_generation(struct inode *inode)
+{
+	KUNIT_STATIC_STUB_REDIRECT(inode_dio_begin_generation, inode);
+	return atomic_fetch_inc(&inode->i_dio_count) &
+		INODE_DIO_GENERATION;
+}
+EXPORT_SYMBOL_GPL(inode_dio_begin_generation);
+#endif
+
 /*
  * Allocated on the first draining operation, never on ordinary DIO. The
  * filesystem owns the pointer and retains the allocation until inode reclaim.
fs/tests/dio_drain_kunit.c new file +393 -0

393 lines not on this page · raw message

include/linux/fs.h +5 -0
index e5c2e857e530..02a33ed754b7 100644
@@ -3216,11 +3216,16 @@ static inline bool inode_dio_drain_overlap(struct inode *inode,
 	return range.active && last >= range.start && pos <= range.last;
 }
 
+/* Test builds need a single function address for the registration stub. */
+#if IS_ENABLED(CONFIG_DIO_DRAIN_KUNIT_TEST)
+bool inode_dio_begin_generation(struct inode *inode);
+#else
 static inline bool inode_dio_begin_generation(struct inode *inode)
 {
 	return atomic_fetch_inc(&inode->i_dio_count) &
 		INODE_DIO_GENERATION;
 }
+#endif
 
 static inline void inode_dio_end_generation(struct inode *inode, bool generation)
 {
Signature · 1 line
2.56.0
#4 lore raw

RFC PATCH 4/6 xfs: add range-drain state and latch-based DIO admission

In reply to Vitali Lovich

Prepare XFS for range draining with lazily allocated inode-private state, retained across VFS inode recycling and freed at XFS inode reclamation. Provide ->dio_drain_complete to resolve the state for older requests.

Register provisionally before the final latch range snapshot for every direct read and write submission. Transfer the token to iomap, and obtain a fresh admission for simple-read fallback or write-check retries.

Overlapping IOCB_NOWAIT requests return -EAGAIN. Blocking requests drop IOLOCK before waiting for a nonoverlapping snapshot and contribute no DIO count while asleep. Writers reacquire through xfs_ilock_iocb_for_write(), repeat append and limit checks, and recheck unaligned COW eligibility because a clone can share blocks while IOLOCK is dropped.

Establish the final admission and ownership rules before enabling either range-drain consumer.

---
 fs/xfs/xfs_file.c   | 148 ++++++++++++++++++++++++++++++++++++++++----
 fs/xfs/xfs_icache.c |   2 +
 fs/xfs/xfs_inode.h  |   1 +
 fs/xfs/xfs_iops.c   |   9 +++
 4 files changed, 149 insertions(+), 11 deletions(-)
fs/xfs/xfs_file.c +137 -11
index d4446887453f..33c8edab4054 100644
@@ -37,6 +37,7 @@
 #include <linux/fadvise.h>
 #include <linux/mount.h>
 #include <linux/filelock.h>
+#include <linux/wait_bit.h>
 
 static const struct vm_operations_struct xfs_file_vm_ops;
 
@@ -227,6 +228,78 @@ xfs_dio_read_bounce_submit_io(
 	submit_bio(bio);
 }
 
+static bool
+xfs_dio_range_overlap(
+	struct xfs_inode	*ip,
+	loff_t			pos,
+	size_t			len)
+{
+	struct inode_dio_drain	*drain;
+	bool			overlap;
+
+	/* Acquire the initialized allocation published by inode_dio_drain_get(). */
+	drain = smp_load_acquire(&ip->i_dio_drain);
+	overlap = inode_dio_drain_overlap(VFS_I(ip), drain, pos, len);
+	return overlap;
+}
+
+/* Register provisionally before the final exclusion snapshot. */
+static bool
+xfs_dio_try_begin(
+	struct xfs_inode	*ip,
+	loff_t			pos,
+	size_t			len,
+	unsigned int		*dio_flags)
+{
+	bool			generation;
+
+	if (!inode_dio_try_begin(VFS_I(ip), &ip->i_dio_drain, pos, len,
+			&generation))
+		return false;
+	*dio_flags &= ~IOMAP_DIO_GENERATION;
+	*dio_flags |= IOMAP_DIO_ACCOUNTED;
+	if (generation)
+		*dio_flags |= IOMAP_DIO_GENERATION;
+	return true;
+}
+
+/* No request is counted while waiting for an overlapping exclusion. */
+static int
+xfs_dio_range_wait(
+	struct kiocb		*iocb,
+	size_t			len,
+	unsigned int		*iolock,
+	bool			write)
+{
+	struct inode		*inode = file_inode(iocb->ki_filp);
+	struct xfs_inode	*ip = XFS_I(inode);
+	struct inode_dio_drain	*drain;
+	int			waited = 0;
+	int			error;
+
+	while (xfs_dio_range_overlap(ip, iocb->ki_pos, len)) {
+		if (iocb->ki_flags & IOCB_NOWAIT)
+			return -EAGAIN;
+		/* The successful overlap check acquired this permanent allocation. */
+		drain = READ_ONCE(ip->i_dio_drain);
+		xfs_iunlock(ip, *iolock);
+		wait_var_event(&inode->i_dio_count,
+			!inode_dio_drain_overlap(inode, drain, iocb->ki_pos, len));
+		/* Re-evaluate the required write lock mode after dropping IOLOCK. */
+		if (write) {
+			error = xfs_ilock_iocb_for_write(iocb, iolock);
+			if (error) {
+				*iolock = 0;
+				return error;
+			}
+		} else {
+			xfs_ilock(ip, *iolock);
+		}
+		waited = 1;
+	}
+	return waited;
+}
+
 static const struct iomap_dio_ops xfs_dio_read_bounce_ops = {
 	.submit_io	= xfs_dio_read_bounce_submit_io,
 	.bio_set	= &iomap_ioend_bioset,
@@ -238,6 +311,10 @@ xfs_file_dio_read(
 	struct iov_iter		*to)
 {
 	struct xfs_inode	*ip = XFS_I(file_inode(iocb->ki_filp));
+	unsigned int		iolock = XFS_IOLOCK_SHARED;
+	unsigned int		dio_flags = 0;
+	bool			bounce = mapping_stable_writes(iocb->ki_filp->f_mapping);
+	bool			simple = !bounce;
 	ssize_t			ret;
 
 	trace_xfs_file_direct_read(iocb, to);
@@ -250,16 +327,27 @@ xfs_file_dio_read(
 	ret = xfs_ilock_iocb(iocb, XFS_IOLOCK_SHARED);
 	if (ret)
 		return ret;
-	if (mapping_stable_writes(iocb->ki_filp->f_mapping)) {
+retry:
+	ret = xfs_dio_range_wait(iocb, iov_iter_count(to), &iolock, false);
+	if (ret < 0)
+		goto out_unlock;
+	if (!xfs_dio_try_begin(ip, iocb->ki_pos, iov_iter_count(to), &dio_flags))
+		goto retry;
+	if (!simple) {
 		ret = iomap_dio_rw(iocb, to, &xfs_read_iomap_ops,
-				&xfs_dio_read_bounce_ops, IOMAP_DIO_BOUNCE,
-				NULL, 0);
+					bounce ? &xfs_dio_read_bounce_ops : NULL,
+					dio_flags | (bounce ? IOMAP_DIO_BOUNCE : 0),
+					NULL, 0);
 	} else {
-		ret = iomap_dio_read_simple(iocb, to, xfs_read_iomap_begin, 0);
-		if (ret == -ENOTBLK)
-			ret = iomap_dio_rw(iocb, to, &xfs_read_iomap_ops, NULL,
-					0, NULL, 0);
+		ret = iomap_dio_read_simple(iocb, to, xfs_read_iomap_begin,
+				dio_flags);
+		if (ret == -ENOTBLK) {
+			/* Fallback needs a fresh admission and registration. */
+			simple = false;
+			goto retry;
+		}
 	}
+out_unlock:
 	xfs_iunlock(ip, XFS_IOLOCK_SHARED);
 
 	return ret;
@@ -438,9 +526,10 @@ xfs_file_write_zero_eof(
 /*
  * Common pre-write limit and setup checks.
  *
- * Called with the iolock held either shared and exclusive according to
- * @iolock, and returns with it held.  Might upgrade the iolock to exclusive
- * if called for a direct write beyond i_size.
+ * Called with the iolock held shared or exclusive according to @iolock.
+ * Returns with it held unless reacquisition fails, in which case *@iolock
+ * is set to zero.  Might upgrade the iolock to exclusive if called for a
+ * direct write beyond i_size.
  */
 STATIC ssize_t
 xfs_file_write_checks(
@@ -455,10 +544,23 @@ xfs_file_write_checks(
 	ssize_t			error;
 
 restart:
+	/* Normalize append position and enforce limits before range admission. */
 	error = generic_write_checks(iocb, from);
 	if (error <= 0)
 		return error;
 
+	if (iocb->ki_flags & IOCB_DIRECT) {
+		error = xfs_dio_range_wait(iocb, iov_iter_count(from), iolock,
+				true);
+		if (error < 0)
+			return error;
+		if (error) {
+			iov_iter_reexpand(from, count);
+			/* EOF and limits can change while IOLOCK is dropped. */
+			goto restart;
+		}
+	}
+
 	if (iocb->ki_flags & IOCB_NOWAIT) {
 		error = break_layout(inode, false);
 		if (error == -EWOULDBLOCK)
@@ -737,6 +839,7 @@ xfs_file_dio_write_aligned(
 {
 	unsigned int		iolock = XFS_IOLOCK_SHARED;
 	unsigned int		dio_flags = 0;
+	size_t			count = iov_iter_count(from);
 	ssize_t			ret;
 
 	/*
@@ -750,6 +853,7 @@ xfs_file_dio_write_aligned(
 	ret = xfs_ilock_iocb_for_write(iocb, &iolock);
 	if (ret)
 		return ret;
+retry_checks:
 	ret = xfs_file_write_checks(iocb, from, &iolock, ac);
 	if (ret)
 		goto out_unlock;
@@ -765,10 +869,15 @@ xfs_file_dio_write_aligned(
 	}
 	if (mapping_stable_writes(iocb->ki_filp->f_mapping))
 		dio_flags |= IOMAP_DIO_BOUNCE;
+	if (!xfs_dio_try_begin(ip, iocb->ki_pos, iov_iter_count(from), &dio_flags)) {
+		iov_iter_reexpand(from, count);
+		goto retry_checks;
+	}
 	trace_xfs_file_direct_write(iocb, from);
 	ret = iomap_dio_rw(iocb, from, ops, dops, dio_flags, ac, 0);
 out_unlock:
-	xfs_iunlock(ip, iolock);
+	if (iolock)
+		xfs_iunlock(ip, iolock);
 	return ret;
 }
 
@@ -829,6 +938,7 @@ xfs_file_dio_write_atomic(
 	if (ret)
 		return ret;
 
+retry_checks:
 	ret = xfs_file_write_checks(iocb, from, &iolock, NULL);
 	if (ret)
 		goto out_unlock;
@@ -842,6 +952,10 @@ xfs_file_dio_write_atomic(
 	trace_xfs_file_direct_write(iocb, from);
 	if (mapping_stable_writes(iocb->ki_filp->f_mapping))
 		dio_flags |= IOMAP_DIO_BOUNCE;
+	if (!xfs_dio_try_begin(ip, iocb->ki_pos, iov_iter_count(from), &dio_flags)) {
+		iov_iter_reexpand(from, ocount);
+		goto retry_checks;
+	}
 	ret = iomap_dio_rw(iocb, from, dops, &xfs_dio_write_ops, dio_flags,
 			NULL, 0);
 
@@ -919,10 +1033,18 @@ xfs_file_dio_write_unaligned(
 		goto out_unlock;
 	}
 
+retry_checks:
 	ret = xfs_file_write_checks(iocb, from, &iolock, NULL);
 	if (ret)
 		goto out_unlock;
 
+	/* The checks can drop IOLOCK, allowing a clone to share this block. */
+	if (xfs_is_cow_inode(ip)) {
+		trace_xfs_reflink_bounce_dio_write(iocb, from);
+		ret = -ENOTBLK;
+		goto out_unlock;
+	}
+
 	/*
 	 * If we are doing exclusive unaligned I/O, this must be the only I/O
 	 * in-flight.  Otherwise we risk data corruption due to unwritten extent
@@ -934,6 +1056,10 @@ xfs_file_dio_write_unaligned(
 
 	if (mapping_stable_writes(iocb->ki_filp->f_mapping))
 		flags |= IOMAP_DIO_BOUNCE;
+	if (!xfs_dio_try_begin(ip, iocb->ki_pos, iov_iter_count(from), &flags)) {
+		iov_iter_reexpand(from, count);
+		goto retry_checks;
+	}
 
 	trace_xfs_file_direct_write(iocb, from);
 	ret = iomap_dio_rw(iocb, from, &xfs_direct_write_iomap_ops,
fs/xfs/xfs_icache.c +2 -0
index de8be344e987..e26df6894618 100644
@@ -110,6 +110,7 @@ xfs_inode_alloc(
 	ip->i_mount = mp;
 	memset(&ip->i_imap, 0, sizeof(struct xfs_imap));
 	ip->i_cowfp = NULL;
+	ip->i_dio_drain = NULL;
 	memset(&ip->i_af, 0, sizeof(ip->i_af));
 	ip->i_af.if_format = XFS_DINODE_FMT_EXTENTS;
 	memset(&ip->i_df, 0, sizeof(ip->i_df));
@@ -156,6 +157,7 @@ xfs_inode_free_callback(
 		xfs_inode_item_destroy(ip);
 	}
 
+	kfree(ip->i_dio_drain);
 	kmem_cache_free(xfs_inode_cache, ip);
 }
 
fs/xfs/xfs_inode.h +1 -0
index 1602027cd0aa..a537f0416a47 100644
@@ -41,6 +41,7 @@ typedef struct xfs_inode {
 	struct xfs_inode_log_item *i_itemp;	/* logging information */
 	struct rw_semaphore	i_lock;		/* inode lock */
 	atomic_t		i_pincount;	/* inode pin count */
+	struct inode_dio_drain	*i_dio_drain; /* lazily allocated DIO drain */
 	struct llist_node	i_gclist;	/* deferred inactivation list */
 
 	/*
fs/xfs/xfs_iops.c +9 -0
index d1306e723899..9dbd15ff0d0d 100644
@@ -1260,6 +1260,14 @@ xfs_vn_tmpfile(
 	return finish_open_simple(file, err);
 }
 
+static void
+xfs_vn_dio_drain_complete(
+	struct inode		*inode)
+{
+	/* The generation cutover orders i_dio_drain initialization before this callback. */
+	inode_dio_drain_complete(inode, READ_ONCE(XFS_I(inode)->i_dio_drain));
+}
+
 static const struct inode_operations xfs_inode_operations = {
 	.get_inode_acl		= xfs_get_acl,
 	.set_acl		= xfs_set_acl,
@@ -1271,6 +1279,7 @@ static const struct inode_operations xfs_inode_operations = {
 	.sync_lazytime		= xfs_vn_sync_lazytime,
 	.fileattr_get		= xfs_fileattr_get,
 	.fileattr_set		= xfs_fileattr_set,
+	.dio_drain_complete	= xfs_vn_dio_drain_complete,
 };
 
 static const struct inode_operations xfs_dir_inode_operations = {
Signature · 1 line
2.56.0
#5 lore raw

RFC PATCH 5/6 xfs: use range-based DIO draining for aligned hole punches

In reply to Vitali Lovich

Hole punching holds exclusive IOLOCK while draining DIO and modifying the range, blocking new submissions throughout the inode. Use shared IOLOCK and a latch-published range exclusion for eligible aligned data-device punches so disjoint new DIO can proceed.

Reject obvious ineligible requests before allocating drain state or taking the drain mutex. Obtain the drain mutex before IOLOCK and recheck eligibility under shared IOLOCK. A waiter must not hold shared IOLOCK while the mutex owner may drop and reacquire IOLOCK exclusively during write checks. Retain the existing path for DAX, realtime, privilege/capability stripping (!IS_NOSEC), reflink remapping, unaligned punches, layout breaking, or an unrepresentable rounded endpoint. Round the exclusion to the larger of the allocation unit and PAGE_SIZE, matching cache invalidation.

Drain the pre-cutover cohort before taking MMAPLOCK: an in-flight DIO can fault in a buffer backed by the same file. Skip unnecessary partial block zeroing for aligned data-device punches so the operation can retain shared IOLOCK. Keep the exclusion through extent removal and any required synchronous log force, and report allocation or drain-start errors.

---
 fs/xfs/xfs_bmap_util.c |  9 ++++-
 fs/xfs/xfs_file.c      | 88 ++++++++++++++++++++++++++++++++++++++++++
 fs/xfs/xfs_inode.c     | 10 +++++
 3 files changed, 105 insertions(+), 2 deletions(-)
fs/xfs/xfs_bmap_util.c +7 -2
index 865aec3ae5ab..30759c6f94d3 100644
@@ -889,8 +889,8 @@ xfs_free_file_space(
 		return 0;
 
 	/*
-	 * Now AIO and DIO has drained we flush and (if necessary) invalidate
-	 * the cached range over the first operation we are about to run.
+	 * The caller has excluded and drained DIO over the affected range.
+	 * Flush and invalidate the cached range before removing its mappings.
 	 */
 	error = xfs_flush_unmap_range(ip, offset, len);
 	if (error)
@@ -917,6 +917,11 @@ xfs_free_file_space(
 		}
 	}
 
+	/* An aligned data-device punch needs no partial-block zeroing. */
+	if (!XFS_IS_REALTIME_INODE(ip) &&
+	    !((offset | len) & mp->m_blockmask))
+		return 0;
+
 	/*
 	 * Now that we've unmap all full blocks we'll have to zero out any
 	 * partial block at the beginning and/or end.  xfs_zero_range is smart
fs/xfs/xfs_file.c +88 -0

100 lines not on this page · raw message

fs/xfs/xfs_inode.c +10 -0
index 621513d7215e..97eb239858cb 100644
@@ -118,6 +118,16 @@ xfs_lock_flags_assert(
  *
  * i_rwsem -> invalidate_lock -> page_lock -> i_ilock
  *
+ * DIO range drainers add an outer mutex:
+ *
+ * i_dio_drain->lock -> i_rwsem -> invalidate_lock -> page_lock -> i_ilock
+ *
+ * Never wait for the drain mutex while holding IOLOCK: its owner may drop
+ * shared IOLOCK and reacquire it exclusively during write checks. A waiter
+ * holding shared IOLOCK would prevent that upgrade and deadlock both drainers.
+ * The mutex stays held through exclusion removal, including extent freeing
+ * and any synchronous log force. DIO admission and completion do not take it.
+ *
  * mmap_lock locking order:
  *
  * i_rwsem -> page lock -> mmap_lock
Signature · 1 line
2.56.0
#6 lore raw

RFC PATCH 6/6 xfs: use range-based DIO draining for post-EOF zeroing

In reply to Vitali Lovich

Zeroing a gap before a direct write normally drains DIO with exclusive IOLOCK. Use range draining for block-aligned, non-atomic data-device writes entering write checks beyond EOF with shared IOLOCK.

Drop IOLOCK before obtaining the lazy drain state and its mutex, then reacquire through xfs_ilock_iocb_for_write() and repeat write checks. A drainer may need IOLOCK_EXCL during these checks; a second drainer must not hold shared IOLOCK while waiting for its mutex, or both would block. Publish the exclusion under shared IOLOCK, demoting first if required, and drain the pre-cutover cohort while admitting disjoint new DIO.

Round the exclusion outward to the larger of the filesystem block size and mapping_max_folio_size() to cover every folio touched by zeroing and invalidation. Recheck EOF after draining because completions can advance it, then zero any remaining gap under MMAPLOCK_EXCL.

Finish the exclusion before submitting the triggering write, which can share its final folio. Release the drain mutex on every write-check exit. Ineligible writes retain existing handling; allocation and drain-start errors propagate to the caller.

---
 fs/xfs/xfs_file.c | 109 +++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 94 insertions(+), 15 deletions(-)
fs/xfs/xfs_file.c +94 -15
index c8b3c4657bcb..0daa73871986 100644
@@ -449,6 +449,55 @@ xfs_file_splice_read(
 	return ret;
 }
 
+/*
+ * Serialize zeroing with I/O to all cache folios that can cover the old EOF
+ * block and gap, not unrelated requests outside those folios. Clear the
+ * exclusion before submitting this write, which can share the final folio.
+ * Drain the finite cohort admitted before the generation cutover, including
+ * COW end-I/O remapping. New unrelated requests can proceed under shared IOLOCK.
+ */
+static int
+xfs_file_write_zero_eof_range(
+	struct kiocb		*iocb,
+	loff_t			isize,
+	unsigned int		*iolock,
+	struct inode_dio_drain	*drain)
+{
+	struct inode		*inode = file_inode(iocb->ki_filp);
+	struct xfs_inode	*ip = XFS_I(inode);
+	loff_t			granularity = max_t(loff_t, i_blocksize(inode),
+					mapping_max_folio_size(inode->i_mapping));
+	loff_t			start = round_down(isize, granularity);
+	loff_t			last = (iocb->ki_pos - 1) | (granularity - 1);
+	int			error = 0;
+
+	error = kiocb_modified(iocb);
+	if (error)
+		return error;
+	if (*iolock == XFS_IOLOCK_EXCL) {
+		xfs_ilock_demote(ip, XFS_IOLOCK_EXCL);
+		*iolock = XFS_IOLOCK_SHARED;
+	}
+	/* Folio invalidation is wider than zeroing, even for sub-page blocks. */
+	error = inode_dio_drain_start(inode, drain, start, last);
+	if (error)
+		return error;
+	inode_dio_drain_wait(inode, drain);
+	spin_lock(&ip->i_flags_lock);
+	isize = i_size_read(inode);
+	spin_unlock(&ip->i_flags_lock);
+	if (iocb->ki_pos > isize) {
+		trace_xfs_zero_eof(ip, isize, iocb->ki_pos - isize);
+		xfs_ilock(ip, XFS_MMAPLOCK_EXCL);
+		error = iomap_zero_range(inode, isize, iocb->ki_pos - isize,
+				NULL, &xfs_buffered_write_iomap_ops,
+				&xfs_iomap_write_ops, NULL);
+		xfs_iunlock(ip, XFS_MMAPLOCK_EXCL);
+	}
+	inode_dio_drain_finish(inode, drain);
+	return error;
+}
+
 /*
  * Take care of zeroing post-EOF blocks when they might exist.
  *
@@ -463,20 +512,17 @@ xfs_file_write_zero_eof(
 	unsigned int		*iolock,
 	size_t			count,
 	bool			*drained_dio,
-	struct xfs_zone_alloc_ctx *ac)
+	struct xfs_zone_alloc_ctx *ac,
+	struct inode_dio_drain	*drain)
 {
 	struct xfs_inode	*ip = XFS_I(iocb->ki_filp->f_mapping->host);
 	loff_t			isize;
 	int			error;
 
 	/*
-	 * We need to serialise against EOF updates that occur in IO completions
-	 * here. We want to make sure that nobody is changing the size while
-	 * we do this check until we have placed an IO barrier (i.e. hold
-	 * XFS_IOLOCK_EXCL) that prevents new IO from being dispatched.  The
-	 * spinlock effectively forms a memory barrier once we have
-	 * XFS_IOLOCK_EXCL so we are guaranteed to see the latest EOF value and
-	 * hence be able to correctly determine if we need to run zeroing.
+	 * Pair with EOF updates in DIO completion. The IOLOCK excludes truncate,
+	 * so EOF can only move forwards. Recheck after establishing either a
+	 * range exclusion or the exclusive IOLOCK and draining the relevant I/O.
 	 */
 	spin_lock(&ip->i_flags_lock);
 	isize = i_size_read(VFS_I(ip));
@@ -489,6 +535,9 @@ xfs_file_write_zero_eof(
 	if (iocb->ki_flags & IOCB_NOWAIT)
 		return -EAGAIN;
 
+	if (drain)
+		return xfs_file_write_zero_eof_range(iocb, isize, iolock, drain);
+
 	if (!*drained_dio) {
 		/*
 		 * If zeroing is needed and we are currently holding the iolock
@@ -539,21 +588,47 @@ xfs_file_write_checks(
 	struct xfs_zone_alloc_ctx *ac)
 {
 	struct inode		*inode = iocb->ki_filp->f_mapping->host;
+	struct inode_dio_drain	*drain = NULL;
 	size_t			count = iov_iter_count(from);
 	bool			drained_dio = false;
 	ssize_t			error;
 
+	/*
+	 * Another drainer may need IOLOCK_EXCL during write checks. Do not pin
+	 * shared IOLOCK while waiting for its drain mutex.
+	 */
+	if (*iolock == XFS_IOLOCK_SHARED &&
+	    (iocb->ki_flags & IOCB_DIRECT) &&
+	    !(iocb->ki_flags & IOCB_ATOMIC) &&
+	    !XFS_IS_REALTIME_INODE(XFS_I(inode)) &&
+	    IS_ALIGNED(iocb->ki_pos | count, i_blocksize(inode)) &&
+	    iocb->ki_pos > i_size_read(inode)) {
+		if (iocb->ki_flags & IOCB_NOWAIT)
+			return -EAGAIN;
+		xfs_iunlock(XFS_I(inode), *iolock);
+		drain = inode_dio_drain_get(&XFS_I(inode)->i_dio_drain);
+		if (IS_ERR(drain)) {
+			xfs_ilock(XFS_I(inode), *iolock);
+			return PTR_ERR(drain);
+		}
+		mutex_lock(&drain->lock);
+		error = xfs_ilock_iocb_for_write(iocb, iolock);
+		if (error) {
+			*iolock = 0;
+			goto out;
+		}
+	}
 restart:
 	/* Normalize append position and enforce limits before range admission. */
 	error = generic_write_checks(iocb, from);
 	if (error <= 0)
-		return error;
+		goto out;
 
 	if (iocb->ki_flags & IOCB_DIRECT) {
 		error = xfs_dio_range_wait(iocb, iov_iter_count(from), iolock,
 				true);
 		if (error < 0)
-			return error;
+			goto out;
 		if (error) {
 			iov_iter_reexpand(from, count);
 			/* EOF and limits can change while IOLOCK is dropped. */
@@ -570,7 +645,7 @@ xfs_file_write_checks(
 	}
 
 	if (error)
-		return error;
+		goto out;
 
 	/*
 	 * For changing security info in file_remove_privs() we need i_rwsem
@@ -582,7 +657,7 @@ xfs_file_write_checks(
 		error = xfs_ilock_iocb(iocb, *iolock);
 		if (error) {
 			*iolock = 0;
-			return error;
+			goto out;
 		}
 		goto restart;
 	}
@@ -599,14 +674,18 @@ xfs_file_write_checks(
 	 */
 	if (iocb->ki_pos > i_size_read(inode)) {
 		error = xfs_file_write_zero_eof(iocb, from, iolock, count,
-				&drained_dio, ac);
+				&drained_dio, ac, drain);
 		if (error == 1)
 			goto restart;
 		if (error)
-			return error;
+			goto out;
 	}
 
-	return kiocb_modified(iocb);
+	error = kiocb_modified(iocb);
+out:
+	if (drain)
+		mutex_unlock(&drain->lock);
+	return error;
 }
 
 static ssize_t
Signature · 1 line
2.56.0