ext4: allow more DIO writes under shared i_rwsem
Baokun Li
reviewercover ext4: allow more DIO writes under shared i_rwsem
Hi all,
This series relaxes the i_rwsem requirements of ext4_dio_write_iter() so that more direct I/O writes can proceed under the shared lock.
It continues the work started by Peng Wang's RFC [1]; I'm taking over this effort going forward.
ext4_dio_write_checks() currently calls ext4_overwrite_io() to decide whether the shared lock is sufficient. Its single ext4_map_blocks() lookup only sees the first contiguous extent of the same type, which forces the exclusive lock for two cases that are actually safe under the shared lock (see individual patches for the full safety argument):
1. Aligned writes spanning multiple already-allocated extents (e.g. written + unwritten, or two discontiguous written extents).
2. Unaligned writes whose head/tail partial blocks land on written extents but the fully-covered middle blocks include hole or unwritten extents.
Patch 1 skips the ext4_overwrite_io() pre-check entirely for aligned non-extending writes, letting them proceed under the shared lock regardless of extent state.
Patch 2 replaces ext4_overwrite_io() with ext4_dio_needs_zeroing(), which directly answers the question driving the lock decision. It checks only the head and tail partial blocks (at most two ext4_map_blocks() calls), and ignores the state of middle blocks.
Testing
=======
"kvm-xfstests -c ext4/all -g auto" passes with no new failures.
Performance
===========
Hardware: /dev/sda (rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfs
Test 1: aligned 8K DIO writes spanning written+unwritten extent boundaries. Each thread writes its own 1G region sequentially; the file is rebuilt between runs so every block is written exactly once.
Metric: IOPS.
JOBS base +patch 1 +patch 1+2 speedup
---- --------- -------- ---------- -------
1 42,322 43,329 43,087 1.02x
2 68,516 70,677 66,958 1.03x
4 62,489 97,072 101,468 1.62x
8 58,701 110,819 113,679 1.94x
16 58,569 116,392 115,272 1.97x
32 60,860 117,244 119,621 1.97xWall time at JOBS=32: 69.2s (base) -> 35.4s (patched), 1.96x faster.
Test 2: unaligned DIO writes (14336 bytes at +512 within each 16K stripe). Each stripe is laid out as [written][unwritten][unwritten] [written], so the head and tail partial blocks land on written extents but the middle is unwritten. Metric: IOPS.
JOBS base +patch 1 +patch 1+2 speedup
---- --------- -------- ---------- -------
1 15,547 15,975 17,381 1.12x
2 15,910 14,808 34,172 2.15x
4 15,014 14,828 57,567 3.83x
8 15,022 14,648 81,947 5.46x
16 14,586 14,262 99,126 6.80x
32 14,047 13,809 92,519 6.59xWall time at JOBS=32: 149.3s (base) -> 22.7s (patched), 6.58x faster.
In test 2, patch 1 alone has no effect (slight noise) because patch 1 only touches the aligned write path. Patch 2 introduces ext4_dio_needs_zeroing() which precisely identifies when partial block zeroing is required, allowing the shared lock for the much larger set of unaligned writes that don't actually trigger zeroing.
Comments and questions are, as always, welcome.
Thanks,
Baokun
[1]: https://patch.msgid.link/[email protected]
Baokun Li (2):
ext4: skip overwrite check for aligned non-extending DIO writes
ext4: base unaligned DIO lock decision on partial block zeroing
fs/ext4/file.c | 132 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 89 insertions(+), 43 deletions(-)
Signature · 1 line
2.43.7
Baokun Li
reviewerPATCH 1/2 ext4: skip overwrite check for aligned non-extending DIO writes
Currently, ext4_dio_write_checks() calls ext4_overwrite_io() to determine if a write is a pure overwrite, and upgrades to exclusive i_rwsem if not. However, ext4_overwrite_io() uses a single ext4_map_blocks() call which only returns the first contiguous extent of the same type. A write spanning multiple pre-allocated extents (e.g. written + unwritten, or two physically discontiguous written extents) produces a false negative, forcing an unnecessary exclusive lock upgrade.
After commit 5d87c7fca2c1 ("ext4: avoid starting handle when dio writing an unwritten extent") and commit 012924f0eeef ("ext4: remove useless ext4_iomap_overwrite_ops"), ext4_iomap_begin()'s fast path accepts both EXT4_MAP_MAPPED and EXT4_MAP_UNWRITTEN without starting a journal transaction. The iomap iteration naturally handles multi-extent
ranges: each call returns the mapping for the current segment, and unwritten-to-written conversion is deferred to ext4_dio_write_end_io(). This means the common case of mixed written/unwritten extents never reaches ext4_iomap_alloc() at all.
Even for the less common case where the range contains a hole and ext4_iomap_alloc() is needed, exclusive i_rwsem is still unnecessary for aligned non-extending writes:
- truncate/punch_hole are kept out: they require exclusive i_rwsem (blocked by our shared lock during allocation), and inode_dio_begin() keeps their inode_dio_wait() blocked until in-flight bios complete.
- i_data_sem write-lock inside ext4_map_blocks() serializes concurrent extent tree modifications (parallel writers to the same hole).
- The journal handle is per-thread and does not require i_rwsem exclusion.
- i_disksize and orphan list are not involved in non-extending writes.
Skip the ext4_overwrite_io() check entirely for aligned writes by initializing overwrite to true and only calling ext4_overwrite_io() for unaligned writes. Unaligned writes still need the extent state check because concurrent partial block zeroing in the DIO layer requires exclusive serialization unless the range is a pure written-extent overwrite.
Performance:
Hardware: /dev/sda (rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfs
Aligned 8K DIO writes spanning written+unwritten extent boundaries. Each thread writes its own 1G region sequentially; the file is rebuilt between runs so every block is written exactly once. Metric: IOPS.
JOBS Before After speedup
---- -------- --------- -------
1 42,322 43,329 1.02x
2 68,516 70,677 1.03x
4 62,489 97,072 1.55x
8 58,701 110,819 1.89x
16 58,569 116,392 1.99x
32 60,860 117,244 1.93xWall time at JOBS=32: 69.2s (Before) -> 35.4s (After), 1.96x faster.
--- fs/ext4/file.c | 52 +++++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 22 deletions(-)
fs/ext4/file.c +30 -22
@@ -428,16 +428,27 @@ static const struct iomap_dio_ops ext4_dio_write_ops = {* condition requires an exclusive inode lock. If yes, then we restart the * whole operation by releasing the shared lock and acquiring exclusive lock. * -* - For unaligned_io we never take shared lock as it may cause data corruption -* when two unaligned IO tries to modify the same block e.g. while zeroing. +* The decision is layered, evaluated in this order: * -* - For extending writes case we don't take the shared lock, since it requires -* updating inode i_disksize and/or orphan handling with exclusive lock. +* 1. If file_modified() needs to update security info (!IS_NOSEC), upgrade +* to the exclusive lock -- the security update itself requires it, +* regardless of whether the write extends the file or is aligned. * -* - shared locking will only be true mostly with overwrites, including -* initialized blocks and unwritten blocks. +* 2. If the write extends i_size or i_disksize, upgrade to the exclusive +* lock to safely update i_disksize and the orphan list, regardless of +* alignment. * -* - Otherwise we will switch to exclusive i_rwsem lock. +* 3. Otherwise, for aligned non-extending writes, shared lock is always +* sufficient regardless of extent state (written, unwritten, or hole). +* truncate/punch_hole cannot run while we hold the shared i_rwsem +* (they need it exclusively); after we release it, inode_dio_begin() +* keeps their inode_dio_wait() blocked until in-flight bios complete. +* i_data_sem serializes concurrent extent tree modifications. +* +* 4. Otherwise, the write is unaligned and non-extending. Shared lock is +* only safe for pure written-extent overwrites. Unwritten extents or +* holes require exclusive lock because concurrent partial block zeroing +* in the DIO layer could corrupt data. */ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, bool *ilock_shared, bool *extend,
@@ -448,7 +459,7 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,loff_t offset;size_t count;ssize_t ret; -bool overwrite, unaligned_io, unwritten; +bool overwrite = true, unaligned_io, unwritten = false; restart: ret =ext4_generic_write_checks (iocb, from);
@@ -460,22 +471,19 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count); - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten);/* -* Determine whether we need to upgrade to an exclusive lock. This is -* required to change security info in file_modified(), for extending -* I/O, any form of non-overwrite I/O, and unaligned I/O to unwritten -* extents (as partial block zeroing may be required). -* -* Note that unaligned writes are allowed under shared lock so long as -* they are pure overwrites. Otherwise, concurrent unaligned writes risk -* data corruption due to partial block zeroing in the dio layer, and so -* the I/O must occur exclusively. +* For unaligned writes we need to know the extent state to determine +* whether shared lock is safe. For aligned writes we skip this check +* entirely since allocation under shared lock is safe. */ +if (unaligned_io) + overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); + +/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || !overwrite || - (unaligned_io && unwritten)))) { + ((!IS_NOSEC (inode) || *extend || + (unaligned_io && (!overwrite || unwritten))))) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;
@@ -490,8 +498,8 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,* Now that locking is settled, determine dio flags and exclusivity * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce * behavior already. The inode lock is already held exclusive if the -* write is non-overwrite or extending, so drain all outstanding dio and -* set the force wait dio flag. +* write is unaligned non-overwrite or extending, so drain all +* outstanding dio and set the force wait dio flag. */ if (!*ilock_shared && (unaligned_io || *extend)) {if (iocb->ki_flags &IOCB_NOWAIT ) {
Signature · 1 line
2.43.7
Re: [PATCH 1/2] ext4: skip overwrite check for aligned non-extending DIO writes
Quoted 56 lines · Baokun Li
Currently,
ext4_dio_write_checks()callsext4_overwrite_io()to determine if a write is a pure overwrite, and upgrades to exclusivei_rwsemif not. However,ext4_overwrite_io()uses a singleext4_map_blocks()call which only returns the first contiguous extent of the same type. A write spanning multiple pre-allocated extents (e.g. written + unwritten, or two physically discontiguous written extents) produces a false negative, forcing an unnecessary exclusive lock upgrade.After commit
5d87c7fca2c1("ext4: avoid starting handle when dio writing an unwritten extent") and commit012924f0eeef("ext4: remove uselessext4_iomap_overwrite_ops"), ext4_iomap_begin()'s fast path accepts bothEXT4_MAP_MAPPEDandEXT4_MAP_UNWRITTENwithout starting a journal transaction. The iomap iteration naturally handles multi-extent
ranges: each call returns the mapping for the current segment, and unwritten-to-written conversion is deferred toext4_dio_write_end_io(). This means the common case of mixed written/unwritten extents never reachesext4_iomap_alloc()at all.Even for the less common case where the range contains a hole and
ext4_iomap_alloc()is needed, exclusivei_rwsemis still unnecessary for aligned non-extending writes:- truncate/punch_hole are kept out: they require exclusive
i_rwsem(blocked by our shared lock during allocation), andinode_dio_begin()keeps theirinode_dio_wait()blocked until in-flight bios complete.
-i_data_semwrite-lock insideext4_map_blocks()serializes concurrent extent tree modifications (parallel writers to the same hole).
- The journal handle is per-thread and does not requirei_rwsemexclusion.
-i_disksizeand orphan list are not involved in non-extending writes.Skip the
ext4_overwrite_io()check entirely for aligned writes by initializing overwrite to true and only callingext4_overwrite_io()for unaligned writes. Unaligned writes still need the extent state check because concurrent partial block zeroing in the DIO layer requires exclusive serialization unless the range is a pure written-extent overwrite.Performance:
Hardware:
/dev/sda(rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfsAligned 8K DIO writes spanning written+unwritten extent boundaries. Each thread writes its own 1G region sequentially; the file is rebuilt between runs so every block is written exactly once. Metric: IOPS.
JOBS Before After speedup
---- -------- --------- -------1 42,322 43,329 1.02x 2 68,516 70,677 1.03x 4 62,489 97,072 1.55x 8 58,701 110,819 1.89x 16 58,569 116,392 1.99x 32 60,860 117,244 1.93x
Quoted 3 lines
Wall time at JOBS=32: 69.2s (Before) -> 35.4s (After), 1.96x faster.
Signed-off-by Baokun Li <[email protected]>
Uh, that's a significant change. I have to say I feel slightly uneasy :). But I don't see a hole in your justification and the patch looks good. Nice find and feel free to add:
Honza
Quoted 98 lines
--- fs/ext4/file.c | 52 +++++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 22 deletions(-)fs/ext4/file.c +30
-22@@ -428,16 +428,27 @@ static const struct iomap_dio_ops ext4_dio_write_ops = {* condition requires an exclusive inode lock. If yes, then we restart the * whole operation by releasing the shared lock and acquiring exclusive lock. * -* - For unaligned_io we never take shared lock as it may cause data corruption -* when two unaligned IO tries to modify the same block e.g. while zeroing. +* The decision is layered, evaluated in this order: * -* - For extending writes case we don't take the shared lock, since it requires -* updating inode i_disksize and/or orphan handling with exclusive lock. +* 1. If file_modified() needs to update security info (!IS_NOSEC), upgrade +* to the exclusive lock -- the security update itself requires it, +* regardless of whether the write extends the file or is aligned. * -* - shared locking will only be true mostly with overwrites, including -* initialized blocks and unwritten blocks. +* 2. If the write extends i_size or i_disksize, upgrade to the exclusive +* lock to safely update i_disksize and the orphan list, regardless of +* alignment. * -* - Otherwise we will switch to exclusive i_rwsem lock. +* 3. Otherwise, for aligned non-extending writes, shared lock is always +* sufficient regardless of extent state (written, unwritten, or hole). +* truncate/punch_hole cannot run while we hold the shared i_rwsem +* (they need it exclusively); after we release it, inode_dio_begin() +* keeps their inode_dio_wait() blocked until in-flight bios complete. +* i_data_sem serializes concurrent extent tree modifications. +* +* 4. Otherwise, the write is unaligned and non-extending. Shared lock is +* only safe for pure written-extent overwrites. Unwritten extents or +* holes require exclusive lock because concurrent partial block zeroing +* in the DIO layer could corrupt data. */ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, bool *ilock_shared, bool *extend,@@ -448,7 +459,7 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,loff_t offset;size_t count;ssize_t ret; -bool overwrite, unaligned_io, unwritten; +bool overwrite = true, unaligned_io, unwritten = false; restart: ret =ext4_generic_write_checks (iocb, from);@@ -460,22 +471,19 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count); - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten);/* -* Determine whether we need to upgrade to an exclusive lock. This is -* required to change security info in file_modified(), for extending -* I/O, any form of non-overwrite I/O, and unaligned I/O to unwritten -* extents (as partial block zeroing may be required). -* -* Note that unaligned writes are allowed under shared lock so long as -* they are pure overwrites. Otherwise, concurrent unaligned writes risk -* data corruption due to partial block zeroing in the dio layer, and so -* the I/O must occur exclusively. +* For unaligned writes we need to know the extent state to determine +* whether shared lock is safe. For aligned writes we skip this check +* entirely since allocation under shared lock is safe. */ +if (unaligned_io) + overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); + +/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || !overwrite || - (unaligned_io && unwritten)))) { + ((!IS_NOSEC (inode) || *extend || + (unaligned_io && (!overwrite || unwritten))))) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;@@ -490,8 +498,8 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,* Now that locking is settled, determine dio flags and exclusivity * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce * behavior already. The inode lock is already held exclusive if the -* write is non-overwrite or extending, so drain all outstanding dio and -* set the force wait dio flag. +* write is unaligned non-overwrite or extending, so drain all +* outstanding dio and set the force wait dio flag. */ if (!*ilock_shared && (unaligned_io || *extend)) {if (iocb->ki_flags &IOCB_NOWAIT ) {Signature · 1 line
2.43.7
Signature · 2 lines
Jan Kara <[email protected]> SUSE Labs, CR
Re: [PATCH 1/2] ext4: skip overwrite check for aligned non-extending DIO writes
In reply to Baokun LiQuoted 56 lines · Baokun Li
Currently,
ext4_dio_write_checks()callsext4_overwrite_io()to determine if a write is a pure overwrite, and upgrades to exclusivei_rwsemif not. However,ext4_overwrite_io()uses a singleext4_map_blocks()call which only returns the first contiguous extent of the same type. A write spanning multiple pre-allocated extents (e.g. written + unwritten, or two physically discontiguous written extents) produces a false negative, forcing an unnecessary exclusive lock upgrade.After commit
5d87c7fca2c1("ext4: avoid starting handle when dio writing an unwritten extent") and commit012924f0eeef("ext4: remove uselessext4_iomap_overwrite_ops"), ext4_iomap_begin()'s fast path accepts bothEXT4_MAP_MAPPEDandEXT4_MAP_UNWRITTENwithout starting a journal transaction. The iomap iteration naturally handles multi-extent
ranges: each call returns the mapping for the current segment, and unwritten-to-written conversion is deferred toext4_dio_write_end_io(). This means the common case of mixed written/unwritten extents never reachesext4_iomap_alloc()at all.Even for the less common case where the range contains a hole and
ext4_iomap_alloc()is needed, exclusivei_rwsemis still unnecessary for aligned non-extending writes:- truncate/punch_hole are kept out: they require exclusive
i_rwsem(blocked by our shared lock during allocation), andinode_dio_begin()keeps theirinode_dio_wait()blocked until in-flight bios complete.
-i_data_semwrite-lock insideext4_map_blocks()serializes concurrent extent tree modifications (parallel writers to the same hole).
- The journal handle is per-thread and does not requirei_rwsemexclusion.
-i_disksizeand orphan list are not involved in non-extending writes.Skip the
ext4_overwrite_io()check entirely for aligned writes by initializing overwrite to true and only callingext4_overwrite_io()for unaligned writes. Unaligned writes still need the extent state check because concurrent partial block zeroing in the DIO layer requires exclusive serialization unless the range is a pure written-extent overwrite.Performance:
Hardware:
/dev/sda(rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfsAligned 8K DIO writes spanning written+unwritten extent boundaries. Each thread writes its own 1G region sequentially; the file is rebuilt between runs so every block is written exactly once. Metric: IOPS.
JOBS Before After speedup
---- -------- --------- -------1 42,322 43,329 1.02x 2 68,516 70,677 1.03x 4 62,489 97,072 1.55x 8 58,701 110,819 1.89x 16 58,569 116,392 1.99x 32 60,860 117,244 1.93x
Quoted 3 lines
Wall time at JOBS=32: 69.2s (Before) -> 35.4s (After), 1.96x faster.
Signed-off-by Baokun Li <[email protected]>
Ha, this is a good idea and a nice speed-up!
Quoted 95 lines
--- fs/ext4/file.c | 52 +++++++++++++++++++++++++++++--------------------- 1 file changed, 30 insertions(+), 22 deletions(-)fs/ext4/file.c +30
-22@@ -428,16 +428,27 @@ static const struct iomap_dio_ops ext4_dio_write_ops = {* condition requires an exclusive inode lock. If yes, then we restart the * whole operation by releasing the shared lock and acquiring exclusive lock. * -* - For unaligned_io we never take shared lock as it may cause data corruption -* when two unaligned IO tries to modify the same block e.g. while zeroing. +* The decision is layered, evaluated in this order: * -* - For extending writes case we don't take the shared lock, since it requires -* updating inode i_disksize and/or orphan handling with exclusive lock. +* 1. If file_modified() needs to update security info (!IS_NOSEC), upgrade +* to the exclusive lock -- the security update itself requires it, +* regardless of whether the write extends the file or is aligned. * -* - shared locking will only be true mostly with overwrites, including -* initialized blocks and unwritten blocks. +* 2. If the write extends i_size or i_disksize, upgrade to the exclusive +* lock to safely update i_disksize and the orphan list, regardless of +* alignment. * -* - Otherwise we will switch to exclusive i_rwsem lock. +* 3. Otherwise, for aligned non-extending writes, shared lock is always +* sufficient regardless of extent state (written, unwritten, or hole). +* truncate/punch_hole cannot run while we hold the shared i_rwsem +* (they need it exclusively); after we release it, inode_dio_begin() +* keeps their inode_dio_wait() blocked until in-flight bios complete. +* i_data_sem serializes concurrent extent tree modifications. +* +* 4. Otherwise, the write is unaligned and non-extending. Shared lock is +* only safe for pure written-extent overwrites. Unwritten extents or +* holes require exclusive lock because concurrent partial block zeroing +* in the DIO layer could corrupt data. */ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, bool *ilock_shared, bool *extend,@@ -448,7 +459,7 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,loff_t offset;size_t count;ssize_t ret; -bool overwrite, unaligned_io, unwritten; +bool overwrite = true, unaligned_io, unwritten = false; restart: ret =ext4_generic_write_checks (iocb, from);@@ -460,22 +471,19 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count); - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten);/* -* Determine whether we need to upgrade to an exclusive lock. This is -* required to change security info in file_modified(), for extending -* I/O, any form of non-overwrite I/O, and unaligned I/O to unwritten -* extents (as partial block zeroing may be required). -* -* Note that unaligned writes are allowed under shared lock so long as -* they are pure overwrites. Otherwise, concurrent unaligned writes risk -* data corruption due to partial block zeroing in the dio layer, and so -* the I/O must occur exclusively. +* For unaligned writes we need to know the extent state to determine +* whether shared lock is safe. For aligned writes we skip this check +* entirely since allocation under shared lock is safe. */ +if (unaligned_io) + overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); + +/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || !overwrite || - (unaligned_io && unwritten)))) { + ((!IS_NOSEC (inode) || *extend || + (unaligned_io && (!overwrite || unwritten))))) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;@@ -490,8 +498,8 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,* Now that locking is settled, determine dio flags and exclusivity * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce * behavior already. The inode lock is already held exclusive if the -* write is non-overwrite or extending, so drain all outstanding dio and -* set the force wait dio flag. +* write is unaligned non-overwrite or extending, so drain all +* outstanding dio and set the force wait dio flag. */ if (!*ilock_shared && (unaligned_io || *extend)) {if (iocb->ki_flags &IOCB_NOWAIT ) {
A message that is not in the archive (sent off-list or not yet received): [email protected]
Baokun Li
reviewerRe: [PATCH 1/2] ext4: skip overwrite check for aligned non-extending DIO writes
Quoted 50 lines · On 2026/6/12 00:47, [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] The patch breaks NOWAIT semantics for aligned non-extending DIO writes to holes. By skipping the extent state check, NOWAIT writes bypass the-EAGAINrejection and proceed to block allocation, where they unconditionally block on journal start and semaphore acquisition. --commit
bdbf8ead96e36f6fd25f65d829a85df07b09be6a
Author: Baokun Li <[email protected]>ext4: skip overwrite check for aligned non-extending DIO writes
This commit optimizes aligned non-extending direct I/O writes by skipping the
ext4_overwrite_io()extent state check. It avoids unnecessary exclusive lock upgrades for writes spanning mixed extents, improving concurrent DIO performance.Quoted 11 lines
fs/ext4/file.c +0
-1@@ -460,22 +471,19 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count); - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten);/* [ ... ]
fs/ext4/file.c
Quoted 12 lines
fs/ext4/file.c +6
-2+if (unaligned_io) + overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); + +/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || !overwrite || - (unaligned_io && unwritten)))) { + ((!IS_NOSEC (inode) || *extend || + (unaligned_io && (!overwrite || unwritten))))) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;[Severity: High]
Does this change break NOWAIT semantics for aligned non-extending DIO writes to holes?Looking at
ext4_dio_write_checks()infs/ext4/file.c, by skipping the extent state check for aligned writes, it seems an aligned NOWAIT write to a hole will no longer trigger this-EAGAINrejection.If the rejection is bypassed, the write will proceed to block allocation in
ext4_iomap_alloc(), which does not check forIOMAP_NOWAITand will unconditionally block on journal start and semaphore acquisition:
Quoted 9 lines
fs/ext4/inode.c:ext4_iomap_alloc()
... handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits); if (IS_ERR(handle)) return PTR_ERR(handle);Could this lead to stalled
io_uringworker threads and performance degradation since NOWAIT operations are expected to never sleep?
Hi,
Sashiko reported a NOWAIT semantics breakage, which I'll address in the next version with the following change:
fs/ext4/inode.c +0 -0
@@ -3672,6 +3672,9 @@ static int ext4_iomap_alloc(struct inode *inode,
struct ext4_map_blocks *map,
int ret, dio_credits, m_flags = 0, retries = 0; bool force_commit = false;
if (flags & IOMAP_NOWAIT)
return -EAGAIN;
A few other NOWAIT fixes will also be included:
- Replace file_modified with kiocb_modified
- Wire up NOWAIT in ext4_map_blocks() (both ext4_iomap_begin and ext4_overwrite_io paths), reusing the existing EXT4_GET_BLOCKS_CACHED_NOWAIT flag
Thanks,
Baokun
Baokun Li
reviewerPATCH 2/2 ext4: base unaligned DIO lock decision on partial block zeroing
In reply to Baokun LiFor unaligned DIO writes, the previous ext4_overwrite_io() required the entire range to fall within a single written extent. This was overly
conservative: the DIO layer only performs partial block zeroing for the head and tail blocks when they are partially covered by the write. Middle blocks that are fully covered are written as whole blocks without any zeroing, so they are safe regardless of extent state.
Therefore exclusive lock is only required when partial block zeroing will actually happen:
- The head partial block (if any) lands on a hole or unwritten extent.
- The tail partial block (if any) lands on a hole or unwritten extent.
Middle full-cover blocks can be in any state (hole, unwritten, or written) - block allocation under shared lock is safe per the previous patch's analysis (inode_dio_begin + i_data_sem protection).
Replace ext4_overwrite_io() with ext4_dio_needs_zeroing(), which directly answers the question driving the lock decision. It uses at most two ext4_map_blocks() calls: one for the head partial block (also catching the case where it spans through the tail), and one for the tail partial block if not already covered.
This enables shared lock for previously-rejected scenarios such as:
- Unaligned write spanning written extent + mid-range hole + written extent at the tail.
- Unaligned write where the partial blocks land on written extents but the middle has unwritten extents.
Performance:
Hardware: /dev/sda (rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfs
Unaligned DIO writes (14336 bytes at +512 within each 16K stripe). Each stripe is laid out as [written][unwritten][unwritten][written], so the head and tail partial blocks land on written extents but the middle is unwritten. Metric: IOPS.
JOBS Before After speedup
---- -------- --------- -------
1 15,547 17,381 1.12x
2 15,910 34,172 2.15x
4 15,014 57,567 3.83x
8 15,022 81,947 5.46x
16 14,586 99,126 6.80x
32 14,047 92,519 6.59xWall time at JOBS=32: 149.3s (Before) -> 22.7s (After), 6.58x faster.
--- fs/ext4/file.c | 108 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 73 insertions(+), 35 deletions(-)
fs/ext4/file.c +73 -35
@@ -213,31 +213,60 @@ ext4_extending_io(struct inode *inode, loff_t offset, size_t len)return false; } -/* Is IO overwriting allocated or initialized blocks? */ -static bool ext4_overwrite_io (struct inode *inode, -loff_t pos,loff_t len,bool *unwritten) +/* +* Does an unaligned DIO write require partial block zeroing? +* +* Partial block zeroing is performed only for the head and tail blocks +* when they are partially covered by the write and the underlying extent +* is a hole or unwritten. Middle blocks (fully covered by the write) +* are written as whole blocks without zeroing. +* +* When zeroing is required, two concurrent unaligned DIO writes to the +* same partial block can race and corrupt each other's data, so the +* caller must take the exclusive i_rwsem and drain in-flight DIO. When +* zeroing is not required, shared lock is safe -- block allocation and +* unwritten conversion for middle blocks are protected by i_data_sem +* and inode_dio_begin(). +*/ +static bool ext4_dio_needs_zeroing (struct inode *inode,loff_t pos,loff_t len) {struct ext4_map_blocks map;unsigned int blkbits = inode->i_blkbits; -int err, blklen; +unsigned long blockmask = inode->i_sb->s_blocksize -1 ; +bool head_partial, tail_partial; +ext4_lblk_t head_lblk, tail_lblk; +int err;if (pos + len >i_size_read (inode)) -return false; +return true; - map.m_lblk = pos >> blkbits; - map.m_len =EXT4_MAX_BLOCKS (len, pos, blkbits); - blklen = map.m_len; + head_partial = (pos & blockmask) !=0 ; + tail_partial = ((pos + len) & blockmask) !=0 ; + head_lblk = pos >> blkbits; + tail_lblk = (pos + len -1 ) >> blkbits; + +/* Check the head partial block. */ +if (head_partial) { + map.m_lblk = head_lblk; + map.m_len = tail_lblk - head_lblk +1 ; + err =ext4_map_blocks (NULL , inode, &map,0 ); +if (err <=0 || !(map.m_flags &EXT4_MAP_MAPPED )) +return true; +/* If this mapping already covers the tail block, we're done. */ +if (!tail_partial || map.m_lblk + err > tail_lblk) +return false; + } - err =ext4_map_blocks (NULL , inode, &map,0 ); -if (err != blklen) -return false; -/* -* 'err==len' means that all of the blocks have been preallocated, -* regardless of whether they have been initialized or not. We need to -* check m_flags to distinguish the unwritten extents. -*/ - *unwritten = !(map.m_flags &EXT4_MAP_MAPPED ); -return true; +/* Check the tail partial block. */ +if (tail_partial) { + map.m_lblk = tail_lblk; + map.m_len =1 ; + err =ext4_map_blocks (NULL , inode, &map,0 ); +if (err <=0 || !(map.m_flags &EXT4_MAP_MAPPED )) +return true; + } + +return false; } static ssize_t ext4_generic_write_checks(struct kiocb *iocb,
@@ -446,9 +475,10 @@ static const struct iomap_dio_ops ext4_dio_write_ops = {* i_data_sem serializes concurrent extent tree modifications. * * 4. Otherwise, the write is unaligned and non-extending. Shared lock is -* only safe for pure written-extent overwrites. Unwritten extents or -* holes require exclusive lock because concurrent partial block zeroing -* in the DIO layer could corrupt data. +* safe unless the DIO layer needs to perform partial block zeroing -- +* i.e. the head or tail partial block sits on a hole or unwritten +* extent. In that case upgrade to the exclusive lock and drain +* in-flight DIO to avoid races with concurrent partial block zeroing. */ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, bool *ilock_shared, bool *extend,
@@ -459,7 +489,7 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,loff_t offset;size_t count;ssize_t ret; -bool overwrite = true, unaligned_io, unwritten = false; +bool needs_zeroing = false; restart: ret =ext4_generic_write_checks (iocb, from);
@@ -469,21 +499,22 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, offset = iocb->ki_pos; count = ret; - unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count);/* -* For unaligned writes we need to know the extent state to determine -* whether shared lock is safe. For aligned writes we skip this check -* entirely since allocation under shared lock is safe. +* For unaligned writes, check whether partial block zeroing will be +* needed. If so, exclusive lock is required to serialize against +* concurrent DIO that could race with the zeroing. +* +* For aligned writes we skip this check entirely since allocation +* under shared lock is safe. */ -if (unaligned_io) - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); +if (ext4_unaligned_io (inode, from, offset)) + needs_zeroing =ext4_dio_needs_zeroing (inode, offset, count);/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || - (unaligned_io && (!overwrite || unwritten))))) { + (!IS_NOSEC (inode) || *extend || needs_zeroing)) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;
@@ -497,16 +528,23 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,/* * Now that locking is settled, determine dio flags and exclusivity * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce -* behavior already. The inode lock is already held exclusive if the -* write is unaligned non-overwrite or extending, so drain all -* outstanding dio and set the force wait dio flag. +* behavior already. When holding the exclusive lock for a write that +* needs partial block zeroing or is extending the file, we must wait +* for the I/O to complete synchronously: +* +* - needs_zeroing: drain in-flight DIO whose end_io could race with +* our partial block zeroing, and force synchronous completion so we +* don't leave in-flight zeroing bios for the next writer to drain. +* +* - extend: the caller must update i_disksize after I/O completion, +* which requires the data to be on disk first. */ -if (!*ilock_shared && (unaligned_io || *extend)) { +if (!*ilock_shared && (needs_zeroing || *extend)) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out; } -if (unaligned_io && (!overwrite || unwritten)) +if (needs_zeroing)inode_dio_wait (inode); *dio_flags =IOMAP_DIO_FORCE_WAIT ; }
Signature · 1 line
2.43.7
Re: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
Quoted 47 lines · Baokun Li
For unaligned DIO writes, the previous
ext4_overwrite_io()required the entire range to fall within a single written extent. This was overly
conservative: the DIO layer only performs partial block zeroing for the head and tail blocks when they are partially covered by the write. Middle blocks that are fully covered are written as whole blocks without any zeroing, so they are safe regardless of extent state.Therefore exclusive lock is only required when partial block zeroing will actually happen:
- The head partial block (if any) lands on a hole or unwritten extent.
- The tail partial block (if any) lands on a hole or unwritten extent.Middle full-cover blocks can be in any state (hole, unwritten, or written) - block allocation under shared lock is safe per the previous patch's analysis (
inode_dio_begin+i_data_semprotection).Replace
ext4_overwrite_io()withext4_dio_needs_zeroing(), which directly answers the question driving the lock decision. It uses at most twoext4_map_blocks()calls: one for the head partial block (also catching the case where it spans through the tail), and one for the tail partial block if not already covered.This enables shared lock for previously-rejected scenarios such as:
- Unaligned write spanning written extent + mid-range hole + written extent at the tail.
- Unaligned write where the partial blocks land on written extents but the middle has unwritten extents.Performance:
Hardware:
/dev/sda(rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfsUnaligned DIO writes (14336 bytes at +512 within each 16K stripe). Each stripe is laid out as [written][unwritten][unwritten][written], so the head and tail partial blocks land on written extents but the middle is unwritten. Metric: IOPS.
JOBS Before After speedup
---- -------- --------- -------1 15,547 17,381 1.12x 2 15,910 34,172 2.15x 4 15,014 57,567 3.83x 8 15,022 81,947 5.46x 16 14,586 99,126 6.80x 32 14,047 92,519 6.59x
Quoted 3 lines
Wall time at JOBS=32: 149.3s (Before) -> 22.7s (After), 6.58x faster.
Signed-off-by Baokun Li <[email protected]>
Looks good. Feel free to add:
Honza
Quoted 173 lines
--- fs/ext4/file.c | 108 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 73 insertions(+), 35 deletions(-)fs/ext4/file.c +73
-35@@ -213,31 +213,60 @@ ext4_extending_io(struct inode *inode, loff_t offset, size_t len)return false; } -/* Is IO overwriting allocated or initialized blocks? */ -static bool ext4_overwrite_io (struct inode *inode, -loff_t pos,loff_t len,bool *unwritten) +/* +* Does an unaligned DIO write require partial block zeroing? +* +* Partial block zeroing is performed only for the head and tail blocks +* when they are partially covered by the write and the underlying extent +* is a hole or unwritten. Middle blocks (fully covered by the write) +* are written as whole blocks without zeroing. +* +* When zeroing is required, two concurrent unaligned DIO writes to the +* same partial block can race and corrupt each other's data, so the +* caller must take the exclusive i_rwsem and drain in-flight DIO. When +* zeroing is not required, shared lock is safe -- block allocation and +* unwritten conversion for middle blocks are protected by i_data_sem +* and inode_dio_begin(). +*/ +static bool ext4_dio_needs_zeroing (struct inode *inode,loff_t pos,loff_t len) {struct ext4_map_blocks map;unsigned int blkbits = inode->i_blkbits; -int err, blklen; +unsigned long blockmask = inode->i_sb->s_blocksize -1 ; +bool head_partial, tail_partial; +ext4_lblk_t head_lblk, tail_lblk; +int err;if (pos + len >i_size_read (inode)) -return false; +return true; - map.m_lblk = pos >> blkbits; - map.m_len =EXT4_MAX_BLOCKS (len, pos, blkbits); - blklen = map.m_len; + head_partial = (pos & blockmask) !=0 ; + tail_partial = ((pos + len) & blockmask) !=0 ; + head_lblk = pos >> blkbits; + tail_lblk = (pos + len -1 ) >> blkbits; + +/* Check the head partial block. */ +if (head_partial) { + map.m_lblk = head_lblk; + map.m_len = tail_lblk - head_lblk +1 ; + err =ext4_map_blocks (NULL , inode, &map,0 ); +if (err <=0 || !(map.m_flags &EXT4_MAP_MAPPED )) +return true; +/* If this mapping already covers the tail block, we're done. */ +if (!tail_partial || map.m_lblk + err > tail_lblk) +return false; + } - err =ext4_map_blocks (NULL , inode, &map,0 ); -if (err != blklen) -return false; -/* -* 'err==len' means that all of the blocks have been preallocated, -* regardless of whether they have been initialized or not. We need to -* check m_flags to distinguish the unwritten extents. -*/ - *unwritten = !(map.m_flags &EXT4_MAP_MAPPED ); -return true; +/* Check the tail partial block. */ +if (tail_partial) { + map.m_lblk = tail_lblk; + map.m_len =1 ; + err =ext4_map_blocks (NULL , inode, &map,0 ); +if (err <=0 || !(map.m_flags &EXT4_MAP_MAPPED )) +return true; + } + +return false; } static ssize_t ext4_generic_write_checks(struct kiocb *iocb,@@ -446,9 +475,10 @@ static const struct iomap_dio_ops ext4_dio_write_ops = {* i_data_sem serializes concurrent extent tree modifications. * * 4. Otherwise, the write is unaligned and non-extending. Shared lock is -* only safe for pure written-extent overwrites. Unwritten extents or -* holes require exclusive lock because concurrent partial block zeroing -* in the DIO layer could corrupt data. +* safe unless the DIO layer needs to perform partial block zeroing -- +* i.e. the head or tail partial block sits on a hole or unwritten +* extent. In that case upgrade to the exclusive lock and drain +* in-flight DIO to avoid races with concurrent partial block zeroing. */ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, bool *ilock_shared, bool *extend,@@ -459,7 +489,7 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,loff_t offset;size_t count;ssize_t ret; -bool overwrite = true, unaligned_io, unwritten = false; +bool needs_zeroing = false; restart: ret =ext4_generic_write_checks (iocb, from);@@ -469,21 +499,22 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, offset = iocb->ki_pos; count = ret; - unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count);/* -* For unaligned writes we need to know the extent state to determine -* whether shared lock is safe. For aligned writes we skip this check -* entirely since allocation under shared lock is safe. +* For unaligned writes, check whether partial block zeroing will be +* needed. If so, exclusive lock is required to serialize against +* concurrent DIO that could race with the zeroing. +* +* For aligned writes we skip this check entirely since allocation +* under shared lock is safe. */ -if (unaligned_io) - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); +if (ext4_unaligned_io (inode, from, offset)) + needs_zeroing =ext4_dio_needs_zeroing (inode, offset, count);/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || - (unaligned_io && (!overwrite || unwritten))))) { + (!IS_NOSEC (inode) || *extend || needs_zeroing)) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;@@ -497,16 +528,23 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,/* * Now that locking is settled, determine dio flags and exclusivity * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce -* behavior already. The inode lock is already held exclusive if the -* write is unaligned non-overwrite or extending, so drain all -* outstanding dio and set the force wait dio flag. +* behavior already. When holding the exclusive lock for a write that +* needs partial block zeroing or is extending the file, we must wait +* for the I/O to complete synchronously: +* +* - needs_zeroing: drain in-flight DIO whose end_io could race with +* our partial block zeroing, and force synchronous completion so we +* don't leave in-flight zeroing bios for the next writer to drain. +* +* - extend: the caller must update i_disksize after I/O completion, +* which requires the data to be on disk first. */ -if (!*ilock_shared && (unaligned_io || *extend)) { +if (!*ilock_shared && (needs_zeroing || *extend)) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out; } -if (unaligned_io && (!overwrite || unwritten)) +if (needs_zeroing)inode_dio_wait (inode); *dio_flags =IOMAP_DIO_FORCE_WAIT ; }Signature · 1 line
2.43.7
Signature · 2 lines
Jan Kara <[email protected]> SUSE Labs, CR
Re: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
In reply to Baokun LiQuoted 47 lines · Baokun Li
For unaligned DIO writes, the previous
ext4_overwrite_io()required the entire range to fall within a single written extent. This was overly
conservative: the DIO layer only performs partial block zeroing for the head and tail blocks when they are partially covered by the write. Middle blocks that are fully covered are written as whole blocks without any zeroing, so they are safe regardless of extent state.Therefore exclusive lock is only required when partial block zeroing will actually happen:
- The head partial block (if any) lands on a hole or unwritten extent.
- The tail partial block (if any) lands on a hole or unwritten extent.Middle full-cover blocks can be in any state (hole, unwritten, or written) - block allocation under shared lock is safe per the previous patch's analysis (
inode_dio_begin+i_data_semprotection).Replace
ext4_overwrite_io()withext4_dio_needs_zeroing(), which directly answers the question driving the lock decision. It uses at most twoext4_map_blocks()calls: one for the head partial block (also catching the case where it spans through the tail), and one for the tail partial block if not already covered.This enables shared lock for previously-rejected scenarios such as:
- Unaligned write spanning written extent + mid-range hole + written extent at the tail.
- Unaligned write where the partial blocks land on written extents but the middle has unwritten extents.Performance:
Hardware:
/dev/sda(rotational disk, ~1 GB/s sustained write)
Filesystem: ext4 default mkfsUnaligned DIO writes (14336 bytes at +512 within each 16K stripe). Each stripe is laid out as [written][unwritten][unwritten][written], so the head and tail partial blocks land on written extents but the middle is unwritten. Metric: IOPS.
JOBS Before After speedup
---- -------- --------- -------1 15,547 17,381 1.12x 2 15,910 34,172 2.15x 4 15,014 57,567 3.83x 8 15,022 81,947 5.46x 16 14,586 99,126 6.80x 32 14,047 92,519 6.59x
Quoted 3 lines
Wall time at JOBS=32: 149.3s (Before) -> 22.7s (After), 6.58x faster.
Signed-off-by Baokun Li <[email protected]>
A nice conclusion and a solid speed-up.
Quoted 170 lines
--- fs/ext4/file.c | 108 +++++++++++++++++++++++++++++++++---------------- 1 file changed, 73 insertions(+), 35 deletions(-)fs/ext4/file.c +73
-35@@ -213,31 +213,60 @@ ext4_extending_io(struct inode *inode, loff_t offset, size_t len)return false; } -/* Is IO overwriting allocated or initialized blocks? */ -static bool ext4_overwrite_io (struct inode *inode, -loff_t pos,loff_t len,bool *unwritten) +/* +* Does an unaligned DIO write require partial block zeroing? +* +* Partial block zeroing is performed only for the head and tail blocks +* when they are partially covered by the write and the underlying extent +* is a hole or unwritten. Middle blocks (fully covered by the write) +* are written as whole blocks without zeroing. +* +* When zeroing is required, two concurrent unaligned DIO writes to the +* same partial block can race and corrupt each other's data, so the +* caller must take the exclusive i_rwsem and drain in-flight DIO. When +* zeroing is not required, shared lock is safe -- block allocation and +* unwritten conversion for middle blocks are protected by i_data_sem +* and inode_dio_begin(). +*/ +static bool ext4_dio_needs_zeroing (struct inode *inode,loff_t pos,loff_t len) {struct ext4_map_blocks map;unsigned int blkbits = inode->i_blkbits; -int err, blklen; +unsigned long blockmask = inode->i_sb->s_blocksize -1 ; +bool head_partial, tail_partial; +ext4_lblk_t head_lblk, tail_lblk; +int err;if (pos + len >i_size_read (inode)) -return false; +return true; - map.m_lblk = pos >> blkbits; - map.m_len =EXT4_MAX_BLOCKS (len, pos, blkbits); - blklen = map.m_len; + head_partial = (pos & blockmask) !=0 ; + tail_partial = ((pos + len) & blockmask) !=0 ; + head_lblk = pos >> blkbits; + tail_lblk = (pos + len -1 ) >> blkbits; + +/* Check the head partial block. */ +if (head_partial) { + map.m_lblk = head_lblk; + map.m_len = tail_lblk - head_lblk +1 ; + err =ext4_map_blocks (NULL , inode, &map,0 ); +if (err <=0 || !(map.m_flags &EXT4_MAP_MAPPED )) +return true; +/* If this mapping already covers the tail block, we're done. */ +if (!tail_partial || map.m_lblk + err > tail_lblk) +return false; + } - err =ext4_map_blocks (NULL , inode, &map,0 ); -if (err != blklen) -return false; -/* -* 'err==len' means that all of the blocks have been preallocated, -* regardless of whether they have been initialized or not. We need to -* check m_flags to distinguish the unwritten extents. -*/ - *unwritten = !(map.m_flags &EXT4_MAP_MAPPED ); -return true; +/* Check the tail partial block. */ +if (tail_partial) { + map.m_lblk = tail_lblk; + map.m_len =1 ; + err =ext4_map_blocks (NULL , inode, &map,0 ); +if (err <=0 || !(map.m_flags &EXT4_MAP_MAPPED )) +return true; + } + +return false; } static ssize_t ext4_generic_write_checks(struct kiocb *iocb,@@ -446,9 +475,10 @@ static const struct iomap_dio_ops ext4_dio_write_ops = {* i_data_sem serializes concurrent extent tree modifications. * * 4. Otherwise, the write is unaligned and non-extending. Shared lock is -* only safe for pure written-extent overwrites. Unwritten extents or -* holes require exclusive lock because concurrent partial block zeroing -* in the DIO layer could corrupt data. +* safe unless the DIO layer needs to perform partial block zeroing -- +* i.e. the head or tail partial block sits on a hole or unwritten +* extent. In that case upgrade to the exclusive lock and drain +* in-flight DIO to avoid races with concurrent partial block zeroing. */ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, bool *ilock_shared, bool *extend,@@ -459,7 +489,7 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,loff_t offset;size_t count;ssize_t ret; -bool overwrite = true, unaligned_io, unwritten = false; +bool needs_zeroing = false; restart: ret =ext4_generic_write_checks (iocb, from);@@ -469,21 +499,22 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from, offset = iocb->ki_pos; count = ret; - unaligned_io =ext4_unaligned_io (inode, from, offset); *extend =ext4_extending_io (inode, offset, count);/* -* For unaligned writes we need to know the extent state to determine -* whether shared lock is safe. For aligned writes we skip this check -* entirely since allocation under shared lock is safe. +* For unaligned writes, check whether partial block zeroing will be +* needed. If so, exclusive lock is required to serialize against +* concurrent DIO that could race with the zeroing. +* +* For aligned writes we skip this check entirely since allocation +* under shared lock is safe. */ -if (unaligned_io) - overwrite =ext4_overwrite_io (inode, offset, count, &unwritten); +if (ext4_unaligned_io (inode, from, offset)) + needs_zeroing =ext4_dio_needs_zeroing (inode, offset, count);/* Determine whether we need to upgrade to an exclusive lock. */ if (*ilock_shared && - ((!IS_NOSEC (inode) || *extend || - (unaligned_io && (!overwrite || unwritten))))) { + (!IS_NOSEC (inode) || *extend || needs_zeroing)) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out;@@ -497,16 +528,23 @@ static ssize_t ext4_dio_write_checks(struct kiocb *iocb, struct iov_iter *from,/* * Now that locking is settled, determine dio flags and exclusivity * requirements. We don't use DIO_OVERWRITE_ONLY because we enforce -* behavior already. The inode lock is already held exclusive if the -* write is unaligned non-overwrite or extending, so drain all -* outstanding dio and set the force wait dio flag. +* behavior already. When holding the exclusive lock for a write that +* needs partial block zeroing or is extending the file, we must wait +* for the I/O to complete synchronously: +* +* - needs_zeroing: drain in-flight DIO whose end_io could race with +* our partial block zeroing, and force synchronous completion so we +* don't leave in-flight zeroing bios for the next writer to drain. +* +* - extend: the caller must update i_disksize after I/O completion, +* which requires the data to be on disk first. */ -if (!*ilock_shared && (unaligned_io || *extend)) { +if (!*ilock_shared && (needs_zeroing || *extend)) {if (iocb->ki_flags &IOCB_NOWAIT ) { ret = -EAGAIN ; goto out; } -if (unaligned_io && (!overwrite || unwritten)) +if (needs_zeroing)inode_dio_wait (inode); *dio_flags =IOMAP_DIO_FORCE_WAIT ; }
Baokun Li
reviewerRe: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
In reply to Baokun LiHi all,
Thank you for your review!
After extensive testing, I found that after merging this patch, generic/746 started failing intermittently on ext3 (mkfs.ext4 -O ^extents). The test triggers a "Page cache invalidation failure on direct I/O" warning, and subsequent fsync returns -EIO.
The underlying race existed before this patch, but this patch appears to have widened the reproduction window considerably, so I thought it worth trying to address. Here is my analysis:
On no-extent inodes, DIO writes that hit holes cannot use unwritten extents. ext4_iomap_alloc() leaves m_flags=0, so ext4_map_blocks() returns 0 for a hole, and:
if (!m_flags && !ret)
ret = -ENOTBLK;
The iomap layer returns -ENOTBLK to ext4, which falls back to buffered I/O. The fallback path dirties pages in the page cache, then flushes and invalidates them. However, concurrent async DIO completions to other blocks on the same inode can run kiocb_invalidate_post_direct_write() without holding the inode lock.
Consider a file with two 4k extents: [hole][written]. Thread A does DIO to the written extent, while thread B does DIO spanning both extents:
kworker A (4k DIO, allocated block) kworker B (8k DIO, hole->fallback) ----------------------------------- ----------------------------------- inode_lock_shared() inode_lock_shared() iomap_dio_rw(): iomap_dio_rw():
kiocb_invalidate_pages -> clean iomap_begin -> -ENOTBLK submit_bio (async) dio->size = 0 inode_unlock_shared() inode_unlock_shared()
[bio pending in block layer] /* fallback: inode lock released */ ext4_buffered_write_iter() inode_lock(exclusive) generic_perform_write() -> dirty pages [0, 8k] inode_unlock(exclusive)
/* pages still dirty here */ [bio completes] filemap_write_and_wait_range() iomap_dio_complete() -> flush dirty pages kiocb_invalidate_post_direct_write() invalidate_mapping_pages() invalidate_inode_pages2_range()
-> finds dirty page! /* window closed */ -> dio_warn_stale_pagecache()
-> errseq_set(-EIO)
The critical window is the gap between ext4_buffered_write_iter() dirtying pages and filemap_write_and_wait_range() flushing them. In this window the inode lock is not held, so another thread's async DIO completion is free to invalidate the still-dirty pages in the page cache.
This race has always existed on ext3 because indirect-block inodes lack unwritten-extent support. However, the window was extremely narrow in practice, because the old ext4_overwrite_io() checked every block and would conservatively take an exclusive lock. This patch replaced it with ext4_dio_needs_zeroing(), which only checks head and tail blocks, making unaligned DIO more likely to take a shared lock and proportionally increasing the chance of hitting the race.
I tried a couple of alternatives before settling on the patch below:
1. Force exclusive lock + IOMAP_DIO_FORCE_WAIT for all no-extent DIO. This closes the window for new DIO submissions, but does not protect against bio completions from previously submitted async DIO, which run independently of the inode lock.
2. Wrap the fallback dirty+flush+invalidate sequence in filemap_invalidate_lock(). However, the ext4 DIO and iomap layers do not use this lock, so it would not serialise against DIO completions.
One straightforward approach that seems correct is to skip direct I/O for no-extent inodes entirely, by returning 0 from ext4_dio_alignment():
fs/ext4/inode.c +0 -0
@@ -6131,6 +6131,8 @@ u32 ext4_dio_alignment(struct inode *inode)
{
if (fsverity_active(inode))
return 0;
+ if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return 0;
if (ext4_should_journal_data(inode))
return 0;
if (ext4_has_inline_data(inode))
With this, ext4_should_use_dio() returns false for no-extent inodes, and all I/O goes through ext4_buffered_write_iter() directly, bypassing the DIO path entirely. On ext3, DIO to a hole already falls back to buffered I/O, so there is essentially no performance benefit to using DIO in the first place.
Note that with this change, the fallback branch in ext4_dio_write_iter():
if (ret >= 0 && iov_iter_count(from)) {
/* buffered fallback */
}
would also become dead code for extent-based inodes (since unwritten extents guarantee iomap_dio_rw() never returns zero with unconsumed data), and could be removed in a follow-up cleanup.
Thoughts? Is there a reason to preserve DIO on no-extent inodes that I'm missing?
Looking forward to your feedback.
Thanks,
Baokun
Re: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
Hi, Baokun!
Quoted 44 lines · Baokun Li
Hi all,
Thank you for your review!
After extensive testing, I found that after merging this patch, generic/746 started failing intermittently on ext3 (mkfs.ext4 -O ^extents). The test triggers a "Page cache invalidation failure on direct I/O" warning, and subsequent fsync returns
-EIO.The underlying race existed before this patch, but this patch appears to have widened the reproduction window considerably, so I thought it worth trying to address. Here is my analysis:
On no-extent inodes, DIO writes that hit holes cannot use unwritten extents.
ext4_iomap_alloc()leaves m_flags=0, soext4_map_blocks()returns 0 for a hole, and:if (!m_flags && !ret)
ret =-ENOTBLK;The iomap layer returns
-ENOTBLKto ext4, which falls back to buffered I/O. The fallback path dirties pages in the page cache, then flushes and invalidates them. However, concurrent async DIO completions to other blocks on the same inode can runkiocb_invalidate_post_direct_write()without holding the inode lock.Consider a file with two 4k extents: [hole][written]. Thread A does DIO to the written extent, while thread B does DIO spanning both extents:
kworker A (4k DIO, allocated block) kworker B (8k DIO,
hole->fallback) ----------------------------------- ----------------------------------- inode_lock_shared()inode_lock_shared()iomap_dio_rw():iomap_dio_rw():
kiocb_invalidate_pages-> cleaniomap_begin->-ENOTBLKsubmit_bio(async) dio->size = 0 inode_unlock_shared()inode_unlock_shared()[bio pending in block layer] /* fallback: inode lock released */
ext4_buffered_write_iter()inode_lock(exclusive)generic_perform_write()-> dirty pages [0, 8k]inode_unlock(exclusive)
Quoted 9 lines
/* pages still dirty here */ [bio completes]
filemap_write_and_wait_range()iomap_dio_complete() -> flush dirty pageskiocb_invalidate_post_direct_write()invalidate_mapping_pages()invalidate_inode_pages2_range()
-> finds dirty page! /* window closed */ ->dio_warn_stale_pagecache()
->errseq_set(-EIO)
It looks like this issue occurs when invalidate_inode_pages2_range() checks beyond the DIO write range, which may only happen when folio size is larger than block size. Is that correct?
Quoted 20 lines
The critical window is the gap between
ext4_buffered_write_iter()dirtying pages andfilemap_write_and_wait_range()flushing them. In this window the inode lock is not held, so another thread's async DIO completion is free to invalidate the still-dirty pages in the page cache.This race has always existed on ext3 because indirect-block inodes lack unwritten-extent support. However, the window was extremely narrow in practice, because the old
ext4_overwrite_io()checked every block and would conservatively take an exclusive lock. This patch replaced it withext4_dio_needs_zeroing(), which only checks head and tail blocks, making unaligned DIO more likely to take a shared lock and proportionally increasing the chance of hitting the race.I tried a couple of alternatives before settling on the patch below:
1. Force exclusive lock +
IOMAP_DIO_FORCE_WAITfor all no-extent DIO. This closes the window for new DIO submissions, but does not protect against bio completions from previously submitted async DIO, which run independently of the inode lock.
Quoted 5 lines
2. Wrap the fallback dirty+flush+invalidate sequence in filemap_invalidate_lock(). However, the ext4 DIO and iomap layers do not use this lock, so it would not serialise against DIO completions.
Could we add a call to inode_dio_wait() before falling back to buffered I/O? That is, in thread B, when falling back to buffered I/O, could we acquire the exclusive inode lock and then call inode_dio_wait() to wait for in-flight DIO to complete? This should close the race window. Since scenarios where DIO writes to holes on ext3 are relatively rare, the performance impact should be minimal (I suppose).
Quoted 28 lines
One straightforward approach that seems correct is to skip direct I/O for no-extent inodes entirely, by returning 0 from
ext4_dio_alignment():fs/ext4/inode.c +2
-0@@ -6131,6 +6131,8 @@ u32 ext4_dio_alignment(struct inode *inode) { if (fsverity_active(inode)) return 0; + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return 0; if (ext4_should_journal_data(inode)) return 0; if (ext4_has_inline_data(inode))With this,
ext4_should_use_dio()returns false for no-extent inodes, and all I/O goes throughext4_buffered_write_iter()directly, bypassing the DIO path entirely. On ext3, DIO to a hole already falls back to buffered I/O, so there is essentially no performance benefit to using DIO in the first place.Note that with this change, the fallback branch in
ext4_dio_write_iter():if (ret >= 0 &&
iov_iter_count(from)) {
/* buffered fallback */
}
Quoted 7 lines
would also become dead code for extent-based inodes (since unwritten extents guarantee
iomap_dio_rw()never returns zero with unconsumed data), and could be removed in a follow-up cleanup.Thoughts? Is there a reason to preserve DIO on no-extent inodes that I'm missing?
Hmm, this would also cause DIO to fall back to buffered I/O in common extending write cases, which I think would be unacceptable.
Cheers,
Yi.
Quoted 8 lines
Looking forward to your feedback.
Thanks,
Baokun
Baokun Li
reviewerRe: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
Quoted 63 lines · Zhang Yi
Hi, Baokun!
Quoted 50 lines · Baokun Li
Hi all,
Thank you for your review!
After extensive testing, I found that after merging this patch, generic/746
started failing intermittently on ext3 (mkfs.ext4 -O ^extents). The test
triggers a "Page cache invalidation failure on direct I/O" warning, and subsequent fsync returns-EIO.The underlying race existed before this patch, but this patch appears to have widened the reproduction window considerably, so I thought it worth trying to address. Here is my analysis:
On no-extent inodes, DIO writes that hit holes cannot use unwritten extents.
ext4_iomap_alloc()leaves m_flags=0, soext4_map_blocks()returns 0 for a hole, and:if (!m_flags && !ret)
ret =-ENOTBLK;The iomap layer returns
-ENOTBLKto ext4, which falls back to buffered I/O. The fallback path dirties pages in the page cache, then flushes and invalidates them. However, concurrent async DIO completions to other blocks on the same inode can runkiocb_invalidate_post_direct_write()
without holding the inode lock.Consider a file with two 4k extents: [hole][written]. Thread A does DIO to the written extent, while thread B does DIO spanning both extents:
kworker A (4k DIO, allocated block) kworker B (8k DIO,
hole->fallback)
-----------------------------------
-----------------------------------
inode_lock_shared()inode_lock_shared()iomap_dio_rw():iomap_dio_rw():
kiocb_invalidate_pages-> cleaniomap_begin->-ENOTBLKsubmit_bio(async) dio->size = 0 inode_unlock_shared()inode_unlock_shared()[bio pending in block layer] /* fallback: inode lock released */
ext4_buffered_write_iter()inode_lock(exclusive)generic_perform_write()-> dirty pages [0, 8k]inode_unlock(exclusive)Quoted 9 lines
/* pages still dirty here */ [bio completes]
filemap_write_and_wait_range()iomap_dio_complete() -> flush dirty pageskiocb_invalidate_post_direct_write()invalidate_mapping_pages()invalidate_inode_pages2_range()
-> finds dirty page! /* window closed */ ->dio_warn_stale_pagecache()
->errseq_set(-EIO)
Quoted 3 lines
It looks like this issue occurs when
invalidate_inode_pages2_range()checks beyond the DIO write range, which may only happen when folio size is larger than block size. Is that correct?
Thanks for looking at this!
Not quite — the scenario involves an 8k file with layout
[hole at 0-4k] [written extent at 4k-8k]
and two DIO threads. Thread A does a 4k DIO write at offset 4k; since the target block is a written extent, no fallback occurs. Thread B does an 8k DIO write at offset 0; since blocks 0-4k are a hole on an indirect-block inode and ext3 does not support unwritten extents, iomap returns -ENOTBLK and the entire 8k write falls back to buffered I/O.
Normally the kernel would prevent concurrent BIO and DIO to overlapping ranges on the same file. But because Thread A holds only a shared inode lock (pure overwrite on a written extent), and Thread B's DIO has already returned -ENOTBLK before its buffered fallback begins, both paths can proceed concurrently:
Thread A: 4k DIO at offset 4k Thread B: 8k DIO at offset 0 ───────────────────────────── ───────────────────────────── kiocb_invalidate_pages iomap_begin → -ENOTBLK → page index 1 already clean (indirect inode hole, m_flags=0) submit_bio (async) dio->size = 0 inode_unlock_shared() inode_unlock_shared()
ext4_buffered_write_iter() [bio pending] → dirty page 0 [0, 4k] → dirty page 1 [4k, 8k] inode_unlock() // pages dirty, no lock
[bio completes]iomap_dio_complete():
kiocb_invalidate_post_direct_write()
start = 4096 >> 12 = 1
end = (8191) >> 12 = 1
invalidate_inode_pages2_range(1, 1)
→ page 1 [4k,8k] is DIRTY
→ -EBUSY → errseq_set(-EIO)
Page index 1 corresponds to file offset [4k, 8k], which is exactly Thread A's DIO range. The invalidation is not going beyond the DIO range — the dirty page was placed there by Thread B's buffered fallback, which wrote to [0, 8k] and dirtied the same page.
No large folio is needed; 4k pages and 4k blocks are sufficient.
From the user's perspective, when performing concurrent DIO on a holed ext3 file, the file contents can become corrupted with some probability. If the file is used as a loop device's backing file, this manifests as filesystem corruption inside the loop device.
Quoted 30 lines
Quoted 24 lines
The critical window is the gap between
ext4_buffered_write_iter()dirtying
pages andfilemap_write_and_wait_range()flushing them. In this window the
inode lock is not held, so another thread's async DIO completion is free to
invalidate the still-dirty pages in the page cache.This race has always existed on ext3 because indirect-block inodes lack unwritten-extent support. However, the window was extremely narrow in practice, because the old
ext4_overwrite_io()checked every block and would conservatively take an exclusive lock. This patch replaced it withext4_dio_needs_zeroing(), which only checks head and tail blocks, making unaligned DIO more likely to take a shared lock and proportionally increasing the chance of hitting the race.I tried a couple of alternatives before settling on the patch below:
1. Force exclusive lock +
IOMAP_DIO_FORCE_WAITfor all no-extent DIO. This closes the window for new DIO submissions, but does not protect against bio completions from previously submitted async DIO, which run independently of the inode lock.Quoted 5 lines
2. Wrap the fallback dirty+flush+invalidate sequence in filemap_invalidate_lock(). However, the ext4 DIO and iomap layers do not use this lock, so it would not serialise against DIO completions.
Quoted 7 lines
Could we add a call to
inode_dio_wait()before falling back to buffered I/O? That is, in thread B, when falling back to buffered I/O, could we acquire the exclusive inode lock and then callinode_dio_wait()to wait for in-flight DIO to complete? This should close the race window. Since scenarios where DIO writes to holes on ext3 are relatively rare, the performance impact should be minimal (I suppose).
That's a great idea, thank you!
I had been trying to fix this on the DIO side and didn't consider waiting from the buffered fallback path.
I've tested the approach locally and it closes the race; I'll add a patch using it in the next version.
Quoted 34 lines
Quoted 34 lines
One straightforward approach that seems correct is to skip direct I/O for no-extent inodes entirely, by returning 0 from
ext4_dio_alignment():fs/ext4/inode.c +2
-0@@ -6131,6 +6131,8 @@ u32 ext4_dio_alignment(struct inode *inode) { if (fsverity_active(inode)) return 0; + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return 0; if (ext4_should_journal_data(inode)) return 0; if (ext4_has_inline_data(inode))With this,
ext4_should_use_dio()returns false for no-extent inodes, and all I/O goes throughext4_buffered_write_iter()directly, bypassing the DIO path entirely. On ext3, DIO to a hole already falls back to buffered
I/O, so there is essentially no performance benefit to using DIO in the first place.Note that with this change, the fallback branch in
ext4_dio_write_iter():if (ret >= 0 &&
iov_iter_count(from)) {
/* buffered fallback */
}would also become dead code for extent-based inodes (since unwritten extents guarantee
iomap_dio_rw()never returns zero with unconsumed data), and could be removed in a follow-up cleanup.
Quoted 7 lines
Quoted 3 lines
Thoughts? Is there a reason to preserve DIO on no-extent inodes that I'm missing?
Hmm, this would also cause DIO to fall back to buffered I/O in common extending write cases, which I think would be unacceptable.
Fair point, the regression on extending writes is hard to justify. That said, until we had a better fix, I'd argue a behavioural change was still preferable to potential data corruption. With the inode_dio_wait() approach above, this trade-off goes away.
Thanks,
Baokun
Re: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
Quoted 114 lines · Baokun Li
Quoted 63 lines · Zhang Yi
Hi, Baokun!
Quoted 50 lines · Baokun Li
Hi all,
Thank you for your review!
After extensive testing, I found that after merging this patch, generic/746
started failing intermittently on ext3 (mkfs.ext4 -O ^extents). The test
triggers a "Page cache invalidation failure on direct I/O" warning, and subsequent fsync returns-EIO.The underlying race existed before this patch, but this patch appears to have widened the reproduction window considerably, so I thought it worth trying to address. Here is my analysis:
On no-extent inodes, DIO writes that hit holes cannot use unwritten extents.
ext4_iomap_alloc()leaves m_flags=0, soext4_map_blocks()returns 0 for a hole, and:if (!m_flags && !ret)
ret =-ENOTBLK;The iomap layer returns
-ENOTBLKto ext4, which falls back to buffered I/O. The fallback path dirties pages in the page cache, then flushes and invalidates them. However, concurrent async DIO completions to other blocks on the same inode can runkiocb_invalidate_post_direct_write()
without holding the inode lock.Consider a file with two 4k extents: [hole][written]. Thread A does DIO to the written extent, while thread B does DIO spanning both extents:
kworker A (4k DIO, allocated block) kworker B (8k DIO,
hole->fallback)
-----------------------------------
-----------------------------------
inode_lock_shared()inode_lock_shared()iomap_dio_rw():iomap_dio_rw():
kiocb_invalidate_pages-> cleaniomap_begin->-ENOTBLKsubmit_bio(async) dio->size = 0 inode_unlock_shared()inode_unlock_shared()[bio pending in block layer] /* fallback: inode lock released */
ext4_buffered_write_iter()inode_lock(exclusive)generic_perform_write()-> dirty pages [0, 8k]inode_unlock(exclusive)Quoted 9 lines
/* pages still dirty here */ [bio completes]
filemap_write_and_wait_range()iomap_dio_complete() -> flush dirty pageskiocb_invalidate_post_direct_write()invalidate_mapping_pages()invalidate_inode_pages2_range()
-> finds dirty page! /* window closed */ ->dio_warn_stale_pagecache()
->errseq_set(-EIO)Quoted 3 lines
It looks like this issue occurs when
invalidate_inode_pages2_range()checks beyond the DIO write range, which may only happen when folio size is larger than block size. Is that correct?Thanks for looking at this!
Not quite — the scenario involves an 8k file with layout
[hole at 0-4k] [written extent at 4k-8k]
and two DIO threads. Thread A does a 4k DIO write at offset 4k; since the target block is a written extent, no fallback occurs. Thread B does an 8k DIO write at offset 0; since blocks 0-4k are a hole on an indirect-block inode and ext3 does not support unwritten extents, iomap returns
-ENOTBLKand the entire 8k write falls back to buffered I/O.Normally the kernel would prevent concurrent BIO and DIO to overlapping ranges on the same file. But because Thread A holds only a shared inode lock (pure overwrite on a written extent), and Thread B's DIO has already returned
-ENOTBLKbefore its buffered fallback begins, both paths can proceed concurrently:Thread A: 4k DIO at offset 4k Thread B: 8k DIO at offset 0 ───────────────────────────── ───────────────────────────── kiocb_invalidate_pages
iomap_begin→-ENOTBLK→ page index 1 already clean (indirect inode hole, m_flags=0)submit_bio(async)dio->size= 0 inode_unlock_shared() inode_unlock_shared()
ext4_buffered_write_iter()[bio pending] → dirty page 0 [0, 4k] → dirty page 1 [4k, 8k]inode_unlock()// pages dirty, no lock[bio completes]
iomap_dio_complete():
kiocb_invalidate_post_direct_write()
start = 4096 >> 12 = 1
end = (8191) >> 12 = 1
invalidate_inode_pages2_range(1, 1)
→ page 1 [4k,8k] is DIRTY
→-EBUSY→errseq_set(-EIO)Page index 1 corresponds to file offset [4k, 8k], which is exactly Thread A's DIO range. The invalidation is not going beyond the DIO range — the dirty page was placed there by Thread B's buffered fallback, which wrote to [0, 8k] and dirtied the same page.
Quoted 6 lines
No large folio is needed; 4k pages and 4k blocks are sufficient.
From the user's perspective, when performing concurrent DIO on a holed ext3 file, the file contents can become corrupted with some probability. If the file is used as a loop device's backing file, this manifests as filesystem corruption inside the loop device.
Ha, fair enough. Thanks for the details.
Cheers,
Yi.
Jan Kara
reviewerRe: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
In reply to Baokun LiQuoted 67 lines · Baokun Li
Quoted 59 lines · Zhang Yi
Quoted 48 lines · Baokun Li
Thank you for your review!
After extensive testing, I found that after merging this patch, generic/746
started failing intermittently on ext3 (mkfs.ext4 -O ^extents). The test
triggers a "Page cache invalidation failure on direct I/O" warning, and subsequent fsync returns-EIO.The underlying race existed before this patch, but this patch appears to have widened the reproduction window considerably, so I thought it worth trying to address. Here is my analysis:
On no-extent inodes, DIO writes that hit holes cannot use unwritten extents.
ext4_iomap_alloc()leaves m_flags=0, soext4_map_blocks()returns 0 for a hole, and:if (!m_flags && !ret)
ret =-ENOTBLK;The iomap layer returns
-ENOTBLKto ext4, which falls back to buffered I/O. The fallback path dirties pages in the page cache, then flushes and invalidates them. However, concurrent async DIO completions to other blocks on the same inode can runkiocb_invalidate_post_direct_write()
without holding the inode lock.Consider a file with two 4k extents: [hole][written]. Thread A does DIO to the written extent, while thread B does DIO spanning both extents:
kworker A (4k DIO, allocated block) kworker B (8k DIO,
hole->fallback)
-----------------------------------
-----------------------------------
inode_lock_shared()inode_lock_shared()iomap_dio_rw():iomap_dio_rw():
kiocb_invalidate_pages-> cleaniomap_begin->-ENOTBLKsubmit_bio(async) dio->size = 0 inode_unlock_shared()inode_unlock_shared()[bio pending in block layer] /* fallback: inode lock released */
ext4_buffered_write_iter()inode_lock(exclusive)generic_perform_write()-> dirty pages [0, 8k]inode_unlock(exclusive)Quoted 9 lines
/* pages still dirty here */ [bio completes]
filemap_write_and_wait_range()iomap_dio_complete() -> flush dirty pageskiocb_invalidate_post_direct_write()invalidate_mapping_pages()invalidate_inode_pages2_range()
-> finds dirty page! /* window closed */ ->dio_warn_stale_pagecache()
->errseq_set(-EIO)Quoted 3 lines
It looks like this issue occurs when
invalidate_inode_pages2_range()checks beyond the DIO write range, which may only happen when folio size is larger than block size. Is that correct?Thanks for looking at this!
Not quite — the scenario involves an 8k file with layout
Quoted 8 lines
[hole at 0-4k] [written extent at 4k-8k]
and two DIO threads. Thread A does a 4k DIO write at offset 4k; since the target block is a written extent, no fallback occurs. Thread B does an 8k DIO write at offset 0; since blocks 0-4k are a hole on an indirect-block inode and ext3 does not support unwritten extents, iomap returns
-ENOTBLKand the entire 8k write falls back to buffered I/O.
Right, but for this to happen userspace had to submit two overlapping direct IO writes. This always had undefined behavior so some inconsistent content in the file is more or less acceptable. But as Zhang pointed out, the same failure can also appear when block_size < folio_size and there we should really strive to provide consistent data.
Quoted 36 lines
Quoted 29 lines
Quoted 23 lines
The critical window is the gap between
ext4_buffered_write_iter()dirtying
pages andfilemap_write_and_wait_range()flushing them. In this window the
inode lock is not held, so another thread's async DIO completion is free to
invalidate the still-dirty pages in the page cache.This race has always existed on ext3 because indirect-block inodes lack unwritten-extent support. However, the window was extremely narrow in practice, because the old
ext4_overwrite_io()checked every block and would conservatively take an exclusive lock. This patch replaced it withext4_dio_needs_zeroing(), which only checks head and tail blocks, making unaligned DIO more likely to take a shared lock and proportionally increasing the chance of hitting the race.I tried a couple of alternatives before settling on the patch below:
1. Force exclusive lock +
IOMAP_DIO_FORCE_WAITfor all no-extent DIO. This closes the window for new DIO submissions, but does not protect against bio completions from previously submitted async DIO, which run independently of the inode lock.Quoted 5 lines
2. Wrap the fallback dirty+flush+invalidate sequence in filemap_invalidate_lock(). However, the ext4 DIO and iomap layers do not use this lock, so it would not serialise against DIO completions.
Quoted 7 lines
Could we add a call to
inode_dio_wait()before falling back to buffered I/O? That is, in thread B, when falling back to buffered I/O, could we acquire the exclusive inode lock and then callinode_dio_wait()to wait for in-flight DIO to complete? This should close the race window. Since scenarios where DIO writes to holes on ext3 are relatively rare, the performance impact should be minimal (I suppose).
Quoted 7 lines
That's a great idea, thank you!
I had been trying to fix this on the DIO side and didn't consider waiting from the buffered fallback path.
I've tested the approach locally and it closes the race; I'll add a patch using it in the next version.
Yes, this looks like the best solution so far. The fallback doesn't have to be fast. It was always - you are doing something stupid and we try to fixup for you - kind of thing and bad performance is acceptable in that case.
Quoted 41 lines
Quoted 34 lines
Quoted 34 lines
One straightforward approach that seems correct is to skip direct I/O for no-extent inodes entirely, by returning 0 from
ext4_dio_alignment():fs/ext4/inode.c +2
-0@@ -6131,6 +6131,8 @@ u32 ext4_dio_alignment(struct inode *inode) { if (fsverity_active(inode)) return 0; + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return 0; if (ext4_should_journal_data(inode)) return 0; if (ext4_has_inline_data(inode))With this,
ext4_should_use_dio()returns false for no-extent inodes, and all I/O goes throughext4_buffered_write_iter()directly, bypassing the DIO path entirely. On ext3, DIO to a hole already falls back to buffered
I/O, so there is essentially no performance benefit to using DIO in the first place.Note that with this change, the fallback branch in
ext4_dio_write_iter():if (ret >= 0 &&
iov_iter_count(from)) {
/* buffered fallback */
}would also become dead code for extent-based inodes (since unwritten extents guarantee
iomap_dio_rw()never returns zero with unconsumed data), and could be removed in a follow-up cleanup.Quoted 6 lines
Quoted 3 lines
Thoughts? Is there a reason to preserve DIO on no-extent inodes that I'm missing?
Hmm, this would also cause DIO to fall back to buffered I/O in common extending write cases, which I think would be unacceptable.
Quoted 4 lines
Fair point, the regression on extending writes is hard to justify. That said, until we had a better fix, I'd argue a behavioural change was still preferable to potential data corruption. With the
inode_dio_wait()approach above, this trade-off goes away.
But heavily regressing performance for overwrites or extending DIO writes even on indirect block based files is not really acceptable. There are still users who for whatever reasons stay with old filesystems having indirect block based files and they'd likely notice the regression.
Honza
Signature · 2 lines
Jan Kara <[email protected]> SUSE Labs, CR
Baokun Li
reviewerRe: [PATCH 2/2] ext4: base unaligned DIO lock decision on partial block zeroing
Quoted 75 lines · Jan Kara
Quoted 66 lines · Baokun Li
Quoted 58 lines · Zhang Yi
Quoted 48 lines · Baokun Li
Thank you for your review!
After extensive testing, I found that after merging this patch, generic/746
started failing intermittently on ext3 (mkfs.ext4 -O ^extents). The test
triggers a "Page cache invalidation failure on direct I/O" warning, and subsequent fsync returns-EIO.The underlying race existed before this patch, but this patch appears to have widened the reproduction window considerably, so I thought it worth trying to address. Here is my analysis:
On no-extent inodes, DIO writes that hit holes cannot use unwritten extents.
ext4_iomap_alloc()leaves m_flags=0, soext4_map_blocks()returns 0 for a hole, and:if (!m_flags && !ret)
ret =-ENOTBLK;The iomap layer returns
-ENOTBLKto ext4, which falls back to buffered I/O. The fallback path dirties pages in the page cache, then flushes and invalidates them. However, concurrent async DIO completions to other blocks on the same inode can runkiocb_invalidate_post_direct_write()
without holding the inode lock.Consider a file with two 4k extents: [hole][written]. Thread A does DIO to the written extent, while thread B does DIO spanning both extents:
kworker A (4k DIO, allocated block) kworker B (8k DIO,
hole->fallback)
-----------------------------------
-----------------------------------
inode_lock_shared()inode_lock_shared()iomap_dio_rw():iomap_dio_rw():
kiocb_invalidate_pages-> cleaniomap_begin->-ENOTBLKsubmit_bio(async) dio->size = 0 inode_unlock_shared()inode_unlock_shared()[bio pending in block layer] /* fallback: inode lock released */
ext4_buffered_write_iter()inode_lock(exclusive)generic_perform_write()-> dirty pages [0, 8k]inode_unlock(exclusive)Quoted 9 lines
/* pages still dirty here */ [bio completes]
filemap_write_and_wait_range()iomap_dio_complete() -> flush dirty pageskiocb_invalidate_post_direct_write()invalidate_mapping_pages()invalidate_inode_pages2_range()
-> finds dirty page! /* window closed */ ->dio_warn_stale_pagecache()
->errseq_set(-EIO)Quoted 3 lines
It looks like this issue occurs when
invalidate_inode_pages2_range()checks beyond the DIO write range, which may only happen when folio size is larger than block size. Is that correct?Thanks for looking at this!
Not quite — the scenario involves an 8k file with layout
Quoted 8 lines
[hole at 0-4k] [written extent at 4k-8k]
and two DIO threads. Thread A does a 4k DIO write at offset 4k; since the target block is a written extent, no fallback occurs. Thread B does an 8k DIO write at offset 0; since blocks 0-4k are a hole on an indirect-block inode and ext3 does not support unwritten extents, iomap returns
-ENOTBLKand the entire 8k write falls back to buffered I/O.
Quoted 5 lines
Right, but for this to happen userspace had to submit two overlapping direct IO writes. This always had undefined behavior so some inconsistent content in the file is more or less acceptable. But as Zhang pointed out, the same failure can also appear when
block_size<folio_sizeand there we should really strive to provide consistent data.
Agreed, overlapping DIO is UB from userspace's perspective. However, neither the loop device usage in generic/746 nor the BS < PS scenario that Yi mentioned involves userspace intentionally submitting overlapping DIO writes. Both are triggered through normal I/O paths, so the issue still needs to be addressed.
Quoted 38 lines
Quoted 38 lines
Quoted 29 lines
Quoted 24 lines
The critical window is the gap between
ext4_buffered_write_iter()dirtying
pages andfilemap_write_and_wait_range()flushing them. In this window the
inode lock is not held, so another thread's async DIO completion is free to
invalidate the still-dirty pages in the page cache.This race has always existed on ext3 because indirect-block inodes lack unwritten-extent support. However, the window was extremely narrow in practice, because the old
ext4_overwrite_io()checked every block and would conservatively take an exclusive lock. This patch replaced it withext4_dio_needs_zeroing(), which only checks head and tail blocks, making unaligned DIO more likely to take a shared lock and proportionally increasing the chance of hitting the race.I tried a couple of alternatives before settling on the patch below:
1. Force exclusive lock +
IOMAP_DIO_FORCE_WAITfor all no-extent DIO. This closes the window for new DIO submissions, but does not protect against bio completions from previously submitted async DIO, which run independently of the inode lock.Quoted 5 lines
2. Wrap the fallback dirty+flush+invalidate sequence in filemap_invalidate_lock(). However, the ext4 DIO and iomap layers do not use this lock, so it would not serialise against DIO completions.
Quoted 7 lines
Could we add a call to
inode_dio_wait()before falling back to buffered I/O? That is, in thread B, when falling back to buffered I/O, could we acquire the exclusive inode lock and then callinode_dio_wait()to wait for in-flight DIO to complete? This should close the race window. Since scenarios where DIO writes to holes on ext3 are relatively rare, the performance impact should be minimal (I suppose).That's a great idea, thank you!
Quoted 8 lines
Quoted 5 lines
I had been trying to fix this on the DIO side and didn't consider waiting from the buffered fallback path.
I've tested the approach locally and it closes the race; I'll add a patch using it in the next version.
Yes, this looks like the best solution so far. The fallback doesn't have to be fast. It was always - you are doing something stupid and we try to fixup for you - kind of thing and bad performance is acceptable in that case.
Agreed.
Quoted 43 lines
Quoted 39 lines
Quoted 34 lines
Quoted 34 lines
One straightforward approach that seems correct is to skip direct I/O for no-extent inodes entirely, by returning 0 from
ext4_dio_alignment():fs/ext4/inode.c +2
-0@@ -6131,6 +6131,8 @@ u32 ext4_dio_alignment(struct inode *inode) { if (fsverity_active(inode)) return 0; + if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) + return 0; if (ext4_should_journal_data(inode)) return 0; if (ext4_has_inline_data(inode))With this,
ext4_should_use_dio()returns false for no-extent inodes, and all I/O goes throughext4_buffered_write_iter()directly, bypassing the DIO path entirely. On ext3, DIO to a hole already falls back to buffered
I/O, so there is essentially no performance benefit to using DIO in the first place.Note that with this change, the fallback branch in
ext4_dio_write_iter():if (ret >= 0 &&
iov_iter_count(from)) {
/* buffered fallback */
}would also become dead code for extent-based inodes (since unwritten extents guarantee
iomap_dio_rw()never returns zero with unconsumed data), and could be removed in a follow-up cleanup.Quoted 5 lines
Quoted 3 lines
Thoughts? Is there a reason to preserve DIO on no-extent inodes that I'm missing?
Hmm, this would also cause DIO to fall back to buffered I/O in common extending write cases, which I think would be unacceptable.
Quoted 4 lines
Fair point, the regression on extending writes is hard to justify. That said, until we had a better fix, I'd argue a behavioural change was still preferable to potential data corruption. With the
inode_dio_wait()approach above, this trade-off goes away.
Quoted 6 lines
But heavily regressing performance for overwrites or extending DIO writes even on indirect block based files is not really acceptable. There are still users who for whatever reasons stay with old filesystems having indirect block based files and they'd likely notice the regression.
Honza
Agreed. Significantly degrading performance for common workloads (overwrites, extending writes) to handle a rare race condition is unacceptable for production systems. The current fix with inode_dio_wait() only impacts the fallback path (DIO → buffered I/O), which is already an exceptional and slow path, so the performance impact there is acceptable.
Thanks,
Baokun