[PATCH] iomap: cap DIO reads at the last block of the file

From: Zizhi Wo

Date: Fri Dec 04 2026 - 20:22:08 EST


From: Zizhi Wo <wozizhi@xxxxxxxxxx>

__iomap_dio_rw() only rejects reads that start at or past EOF. A read
that crosses EOF keeps its full length, so the bytes past i_size are
still processed, and a hole among them is zero-filled into the caller's
buffer with iov_iter_zero(). Those bytes are reverted after the loop and
never returned.

The extra work also costs performance for every iterator. For a
user-backed iterator it can also fail: if the pages past i_size are not
writable, the read returns -EFAULT instead of the bytes it did read.

Cap iomi.len at round_up(dio->i_size, i_blocksize(inode)) - iomi.pos.
iomap_length() bounds every extent operation by iomi.len, so nothing
past the last block is read or zero-filled.

i_size = 8K, block size = 4K, read at offset 4K with length 8K:

0 4K 8K 12K
| | | |
file: [============|============]
request: [============|============]
returned: [============]
old: [= 4K data ==|= 4K zero ==] <- extra zero-fill
new: [= 4K data ==]

Use i_blocksize() and not the device logical block size. With
IOMAP_DIO_FSBLOCK_ALIGNED, i_blocksize() is the unit iomap checks.
Without it the unit is the bdev logical block size, which is only
known inside iomap_begin and can differ between mappings (xfs rtdev,
btrfs multi-device). Rounding up to i_blocksize() is still correct:
those filesystems reject a block size smaller than the device logical
block size, and both are powers of two, so the rounded length is a
multiple of it.

Truncating the caller's iterator would give the same bound but is not
safe: btrfs and gfs2 reuse it after a partial read and i_size may grow
between attempts, so the part beyond i_size must stay in it. Capping
iomi.len leaves the iterator untouched.

Signed-off-by: Zizhi Wo <wozizhi@xxxxxxxxxx>
---
fs/iomap/direct-io.c | 10 ++++++++++
1 file changed, 10 insertions(+)

diff --git a/fs/iomap/direct-io.c b/fs/iomap/direct-io.c
index f00b0841fdd0..b1a6583b57fb 100644
--- a/fs/iomap/direct-io.c
+++ b/fs/iomap/direct-io.c
@@ -738,10 +738,20 @@ __iomap_dio_rw(struct kiocb *iocb, struct iov_iter *iter,

if (iov_iter_rw(iter) == READ) {
if (iomi.pos >= dio->i_size)
goto out_free_dio;

+ /*
+ * Reading or zero-filling past the last block of the file is
+ * pointless, and the zero-fill can fail with -EFAULT on an
+ * otherwise valid short read. Cap this call at the end of
+ * that block.
+ */
+ iomi.len = min_t(u64, iomi.len,
+ round_up(dio->i_size, i_blocksize(inode)) -
+ iomi.pos);
+
if (user_backed_iter(iter))
dio->flags |= IOMAP_DIO_USER_BACKED;

ret = kiocb_write_and_wait(iocb, iomi.len);
if (ret)
--
2.52.0