mirror of https://lore.kernel.org/lkml/
 help / color / mirror / Atom feed
* Re: [RFC PATCH v2 2/8] iomap: add dma-buf direct I/O guards
@ 2026-11-25 17:16 Yun Wang
  0 siblings, 0 replies; 2+ messages in thread
From: Yun Wang @ 2026-11-25 17:16 UTC (permalink / raw)
  To: Mengmeng Zhao
  Cc: hch, anuj1072538, anuj20.g, nj.shetty, axboe, sumit.semwal,
	christian.koenig, phasta, djbw, willy, jack, viro, brauner,
	tytso, adilger.kernel, libaokun, ojaswin, ritesh.list, yi.zhang,
	asml.silence, corbet, skhan, rdunlap, liwang, zhaomengmeng,
	mcgrof, linux-block, linux-kernel, linux-fsdevel, nvdimm,
	linux-ext4, linux-xfs, linux-doc, linux-media, dri-devel,
	linaro-mm-sig

On Fri, Nov 13, 2026 at 03:06:15PM +0800, Mengmeng Zhao wrote:
>  static int iomap_dio_hole_iter(struct iomap_iter *iter, struct iomap_dio *dio)
>  {
> -	loff_t copied = iov_iter_zero(iomap_length(iter), dio->submit.iter);
> +	loff_t copied;
> +
> +	/* zero-filling walks the data pages */
> +	if (iov_iter_is_dmabuf_map(dio->submit.iter))
> +		return -EOPNOTSUPP;

This also fails reads that run past EOF.  The filesystem maps the range
beyond the last block as a hole too, so a dma-buf read that starts
before EOF and ends past the last block of the file fails as a whole,
while the same O_DIRECT read into user memory returns the bytes up to
EOF.

I found it while testing the series for fastsafetensors' dma-buf copier
[1], which loads model weights from NVMe into GPU memory with READ_FIXED
into registered dma-bufs.  I ran v2 on top of v7.4-rc2 in a QEMU guest
with an emulated NVMe namespace, reading into udmabufs.  With a
5000-byte file on ext4 with 4 KiB blocks, reading [4096, 12288):

  READ_FIXED into a registered udmabuf -> -EOPNOTSUPP
  O_DIRECT pread() into user memory    -> 904

It fails the same way whether the read is the first one on the buffer,
is issued inline once the map exists, or is forced to io-wq with
IOSQE_ASYNC.

Reading a file in fixed-size chunks hits this on the last chunk unless
the file size is a multiple of the chunk size.  With 1 KiB blocks it
also breaks the copier's normal pattern, 4 KiB-aligned reads up to
round_up(i_size, 4096): the last read fails.

Nothing past EOF is reported to the caller anyway: __iomap_dio_rw()
reverts the iterator to i_size and iomap_dio_complete() truncates the
result to it.  So a hole that starts at or after EOF can be stepped
over; a hole inside the file still needs zeroes and still fails.
Something like this on top of the series, or folded into this patch:

diff --git a/fs/iomap/direct-io.c b/fs/iomap/direct-io.c
index 83fda6973bb9..2de6d379f811 100644
--- a/fs/iomap/direct-io.c
+++ b/fs/iomap/direct-io.c
@@ -596,9 +596,20 @@ static int iomap_dio_hole_iter(struct iomap_iter *iter, struct iomap_dio *dio)
 {
 	loff_t copied;
 
-	/* zero-filling walks the data pages */
-	if (iov_iter_is_dmabuf_map(dio->submit.iter))
-		return -EOPNOTSUPP;
+	if (iov_iter_is_dmabuf_map(dio->submit.iter)) {
+		u64 length = iomap_length(iter);
+
+		/* zero-filling walks the data pages */
+		if (iter->pos < dio->i_size)
+			return -EOPNOTSUPP;
+		/*
+		 * Past EOF there is nothing to zero: the read is truncated to
+		 * i_size before it is reported, so step over the hole.
+		 */
+		iov_iter_advance(dio->submit.iter, length);
+		dio->size += length;
+		return iomap_iter_advance(iter, length);
+	}
 
 	copied = iov_iter_zero(iomap_length(iter), dio->submit.iter);
 

Signed-off-by: Yun Wang <arsenova@a7snv.com>

With it, the read above returns 904 with the right data in all three
cases.  Holes and unwritten extents inside the file still return
-EOPNOTSUPP, including a hole that straddles EOF after the file was
extended with ftruncate().

The rest of the series behaved as the cover letter describes in that
setup, with 4 KiB and 1 KiB blocks: registration on an O_DIRECT file,
reads into arbitrary offsets of the buffer, reads through a dup()ed fd,
-EBADF through another file's slot, -EINVAL when registering a buffered
fd, -EOPNOTSUPP after F_SETFL clears O_DIRECT and success again once it
is set back, WRITE_FIXED including a write that extends the file, and a
clean e2fsck afterwards.  I have not run it on real NVMe hardware or
xfstests yet.

This report and the reproducer below were drafted with the help of an
AI coding assistant (Claude Opus 5.5); the fix is mine.

[1] https://github.com/foundation-model-stack/fastsafetensors/issues/139

Thanks,
Yun

Reproducer.  It needs /dev/udmabuf and a filesystem with this series
on an NVMe namespace:

  head -c 5000 /dev/urandom > /mnt/f && sync
  ./dmabuf_eof_read /mnt/f 4096 8192             # first read on the buffer
  ./dmabuf_eof_read /mnt/f 4096 8192 warm        # map exists, inline issue
  ./dmabuf_eof_read /mnt/f 4096 8192 warm async  # IOSQE_ASYNC

// SPDX-License-Identifier: GPL-2.0
/*
 * Read a file range into a udmabuf that is registered against the file as
 * an io_uring fixed buffer, and compare with an O_DIRECT pread() of the
 * same range into user memory.
 *
 *   dmabuf_eof_read <file> <offset> <length> [warm] [async]
 *
 *   warm   first read [0, 4096) through the same buffer, so the dma-buf map
 *          exists and the measured read can be issued inline (nonblocking)
 *   async  set IOSQE_ASYNC on the measured read (issue it from io-wq)
 *
 * Exits 0 when READ_FIXED returns what pread() returns and the bytes match.
 * Needs /dev/udmabuf, and a kernel and filesystem with io_uring dma-buf
 * registered buffers.  The UAPI bits are declared locally because they are
 * newer than most installed headers.
 */
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <linux/udmabuf.h>

#define IORING_OFF_SQ_RING		0ULL
#define IORING_OFF_SQES			0x10000000ULL
#define IORING_ENTER_GETEVENTS		(1U << 0)
#define IORING_REGISTER_BUFFERS2	15
#define IORING_REGISTER_BUFFERS_UPDATE	16
#define IORING_RSRC_REGISTER_SPARSE	(1U << 0)
#define IORING_RSRC_UPDATE_EXTENDED	(1U << 1)
#define IO_REGBUF_TYPE_DMABUF		2
#define IORING_OP_READ_FIXED		4
#define IOSQE_ASYNC			(1U << 4)

struct sqe {
	uint8_t opcode, flags;
	uint16_t ioprio;
	int32_t fd;
	uint64_t off, addr;
	uint32_t len, rw_flags;
	uint64_t user_data;
	uint16_t buf_index, personality;
	int32_t splice_fd_in;
	uint64_t addr3, pad2;
};

struct cqe {
	uint64_t user_data;
	int32_t res;
	uint32_t flags;
};

struct sq_offsets {
	uint32_t head, tail, ring_mask, ring_entries, flags, dropped, array, resv1;
	uint64_t user_addr;
};

struct cq_offsets {
	uint32_t head, tail, ring_mask, ring_entries, overflow, cqes, flags, resv1;
	uint64_t user_addr;
};

struct params {
	uint32_t sq_entries, cq_entries, flags, sq_thread_cpu, sq_thread_idle;
	uint32_t features, wq_fd, resv[3];
	struct sq_offsets sq_off;
	struct cq_offsets cq_off;
};

struct rsrc_register {
	uint32_t nr, flags;
	uint64_t resv2, data, tags;
};

struct rsrc_update2 {
	uint32_t offset, flags;
	uint64_t data, tags;
	uint32_t nr, resv2;
};

struct regbuf_desc {
	uint32_t type, flags;
	uint64_t size, uaddr;
	int32_t dmabuf_fd, target_fd;
	uint64_t resv[6];
};

_Static_assert(sizeof(struct sqe) == 64, "io_uring_sqe");
_Static_assert(sizeof(struct cqe) == 16, "io_uring_cqe");
_Static_assert(sizeof(struct params) == 120, "io_uring_params");
_Static_assert(sizeof(struct rsrc_register) == 32, "io_uring_rsrc_register");
_Static_assert(sizeof(struct rsrc_update2) == 32, "io_uring_rsrc_update2");
_Static_assert(sizeof(struct regbuf_desc) == 80, "io_uring_regbuf_desc");

struct ring {
	int fd;
	struct params p;
	char *rings;
	struct sqe *sqes;
};

static void die(const char *what)
{
	perror(what);
	exit(2);
}

static void ring_init(struct ring *r)
{
	size_t sq_size, cq_size;

	memset(r, 0, sizeof(*r));
	r->fd = syscall(SYS_io_uring_setup, 4, &r->p);
	if (r->fd < 0)
		die("io_uring_setup");
	sq_size = r->p.sq_off.array + r->p.sq_entries * sizeof(uint32_t);
	cq_size = r->p.cq_off.cqes + r->p.cq_entries * sizeof(struct cqe);
	/* SQ and CQ rings share one mapping (IORING_FEAT_SINGLE_MMAP) */
	r->rings = mmap(NULL, sq_size > cq_size ? sq_size : cq_size,
			PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, r->fd,
			IORING_OFF_SQ_RING);
	r->sqes = mmap(NULL, r->p.sq_entries * sizeof(struct sqe),
		       PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, r->fd,
		       IORING_OFF_SQES);
	if (r->rings == MAP_FAILED || r->sqes == MAP_FAILED)
		die("mmap ring");
}

/* one READ_FIXED from slot 0; addr is the byte offset into the dma-buf */
static int read_fixed(struct ring *r, int fd, off_t off, size_t len,
		      uint64_t buf_off, uint8_t sqe_flags)
{
	uint32_t *sq_tail = (uint32_t *)(r->rings + r->p.sq_off.tail);
	uint32_t sq_mask = *(uint32_t *)(r->rings + r->p.sq_off.ring_mask);
	uint32_t *sq_array = (uint32_t *)(r->rings + r->p.sq_off.array);
	uint32_t *cq_head = (uint32_t *)(r->rings + r->p.cq_off.head);
	uint32_t *cq_tail = (uint32_t *)(r->rings + r->p.cq_off.tail);
	uint32_t cq_mask = *(uint32_t *)(r->rings + r->p.cq_off.ring_mask);
	uint32_t tail = *sq_tail, idx = tail & sq_mask, head;
	struct cqe *cqe;
	int res;

	memset(&r->sqes[idx], 0, sizeof(struct sqe));
	r->sqes[idx].opcode = IORING_OP_READ_FIXED;
	r->sqes[idx].flags = sqe_flags;
	r->sqes[idx].fd = fd;
	r->sqes[idx].off = off;
	r->sqes[idx].addr = buf_off;
	r->sqes[idx].len = len;
	r->sqes[idx].buf_index = 0;
	sq_array[idx] = idx;
	__atomic_store_n(sq_tail, tail + 1, __ATOMIC_RELEASE);
	if (syscall(SYS_io_uring_enter, r->fd, 1, 1, IORING_ENTER_GETEVENTS,
		    NULL, 0) < 0)
		die("io_uring_enter");
	head = *cq_head;
	if (head == __atomic_load_n(cq_tail, __ATOMIC_ACQUIRE)) {
		fprintf(stderr, "no completion\n");
		exit(2);
	}
	cqe = (struct cqe *)(r->rings + r->p.cq_off.cqes) + (head & cq_mask);
	res = cqe->res;
	__atomic_store_n(cq_head, head + 1, __ATOMIC_RELEASE);
	return res;
}

int main(int argc, char **argv)
{
	struct rsrc_register reg = { .nr = 1, .flags = IORING_RSRC_REGISTER_SPARSE };
	struct regbuf_desc desc = { .type = IO_REGBUF_TYPE_DMABUF };
	struct rsrc_update2 up = { .flags = IORING_RSRC_UPDATE_EXTENDED, .nr = 1 };
	struct udmabuf_create create = { .flags = UDMABUF_FLAGS_CLOEXEC };
	int fd, ufd, memfd, dmabuf, res, warm = 0, async = 0, i;
	unsigned char *view, *host;
	size_t length, size;
	ssize_t expect;
	struct ring r;
	off_t offset;

	if (argc < 4) {
		fprintf(stderr, "usage: %s <file> <offset> <length> [warm] [async]\n",
			argv[0]);
		return 2;
	}
	for (i = 4; i < argc; i++) {
		if (!strcmp(argv[i], "warm"))
			warm = 1;
		else if (!strcmp(argv[i], "async"))
			async = 1;
	}
	offset = strtoll(argv[2], NULL, 0);
	length = strtoull(argv[3], NULL, 0);
	size = (length + 4095) & ~4095UL;
	if (size < 4096)
		size = 4096;

	fd = open(argv[1], O_RDONLY | O_DIRECT);
	if (fd < 0)
		die("open");

	/* the reference: the same range read into user memory */
	if (posix_memalign((void **)&host, 4096, size))
		die("posix_memalign");
	expect = pread(fd, host, length, offset);
	if (expect < 0)
		die("pread");

	/* a udmabuf over a sealed memfd */
	memfd = memfd_create("dmabuf-eof", MFD_ALLOW_SEALING);
	if (memfd < 0 || ftruncate(memfd, size) ||
	    fcntl(memfd, F_ADD_SEALS, F_SEAL_SHRINK))
		die("memfd");
	view = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, memfd, 0);
	if (view == MAP_FAILED)
		die("mmap memfd");
	ufd = open("/dev/udmabuf", O_RDWR);
	if (ufd < 0)
		die("open /dev/udmabuf");
	create.memfd = memfd;
	create.size = size;
	dmabuf = ioctl(ufd, UDMABUF_CREATE, &create);
	if (dmabuf < 0)
		die("UDMABUF_CREATE");

	/* a ring with one sparse buffer slot holding the dma-buf */
	ring_init(&r);
	if (syscall(SYS_io_uring_register, r.fd, IORING_REGISTER_BUFFERS2, &reg,
		    sizeof(reg)) < 0)
		die("IORING_REGISTER_BUFFERS2");
	desc.dmabuf_fd = dmabuf;
	desc.target_fd = fd;
	up.data = (uint64_t)(uintptr_t)&desc;
	if (syscall(SYS_io_uring_register, r.fd, IORING_REGISTER_BUFFERS_UPDATE,
		    &up, sizeof(up)) < 0)
		die("register dma-buf");

	if (warm) {
		res = read_fixed(&r, fd, 0, 4096, 0, 0);
		if (res != 4096) {
			fprintf(stderr, "warm-up read returned %d\n", res);
			return 2;
		}
	}
	memset(view, 0xa5, size);
	res = read_fixed(&r, fd, offset, length, 0, async ? IOSQE_ASYNC : 0);

	printf("READ_FIXED into dma-buf (%s, %s): %d%s%s, O_DIRECT pread(): %zd\n",
	       warm ? "map ready" : "first read", async ? "IOSQE_ASYNC" : "inline",
	       res, res < 0 ? " " : "", res < 0 ? strerror(-res) : "", expect);
	if (res != expect)
		return 1;
	if (res > 0 && memcmp(view, host, res)) {
		printf("data differs\n");
		return 1;
	}
	return 0;
}


^ permalink raw reply	[flat|nested] 2+ messages in thread
* [RFC PATCH v2 0/8] ext4: Add dma-buf read/write support
@ 2026-11-13  7:06 Mengmeng Zhao
  2026-11-13  7:06 ` [RFC PATCH v2 2/8] iomap: add dma-buf direct I/O guards Mengmeng Zhao
  0 siblings, 1 reply; 2+ messages in thread
From: Mengmeng Zhao @ 2026-11-13  7:06 UTC (permalink / raw)
  To: Christoph Hellwig, Anuj Gupta, Nitesh Shetty, Jens Axboe,
	Sumit Semwal, christian.koenig, Philipp Stanner, Dan Williams,
	Matthew Wilcox, Jan Kara, Alexander Viro, Christian Brauner,
	tytso, Andreas Dilger, Baokun Li, Ojaswin Mujoo,
	Ritesh Harjani (IBM),
	Zhang Yi, asml.silence, Jonathan Corbet, Shuah Khan,
	Randy Dunlap
  Cc: linux-block, linux-kernel, linux-fsdevel, nvdimm, linux-ext4,
	linux-xfs, linux-doc, linux-media, dri-devel, linaro-mm-sig,
	Li Wang, Mengmeng Zhao

From: Mengmeng Zhao <zhaomengmeng@kylinos.cn>

This series adds dma-buf read/write support for ext4. The dma-buf direct
I/O infrastructure allows dma-buf to be handed to file I/O as an iov_iter,
but currently it only supports raw block devices. To better serve the
GPU-NVMe direct access through normal filesystems, prior work for XFS has
been discussed at [1]. We are also interested in this field and working on
it [2].

The series is based on v7.4-rc2 (7475ea8b5861), which already contains
the common dma-buf direct I/O infrastructure, so it no longer depends on a
separate base tree.
Patches 1-2 carry the block and iomap prerequisites from Nitesh Shetty and
Anuj Gupta:
- bdev_init_dma_buf_io_ctx in patch 1 was moved to block/bdev.c as
suggested by Christoph.
- iomap_file_init_dma_buf_io_ctx from that series is not carried. ext4
calls bdev_init_dma_buf_io_ctx directly, and the capability check is
handled by FMODE_CAN_DMABUF_IO.

The design is:
- FMODE_CAN_DMABUF_IO marks files that can be the target of dma-buf I/O;
  a filesystem sets it at open time for inodes whose data can be reached
  without the page cache.
- dma_buf_io_ctx_create() refuses files that lack the flag and checks the
  current f_flags for O_DIRECT at registration.
- As F_SETFL can clear O_DIRECT afterwards, the paths that would fall back
  to buffered or copied I/O still need per-I/O checks in the callers.
- DAX is rechecked per I/O because it can be enabled after open.
- iomap must not ask for a buffered fallback on behalf of a dma-buf
  iterator: -ENOTBLK would be refused by the callers and would turn a
  failure into a successful transfer of zero bytes.

Patch 3 keeps the buffered fallback out of dma-buf I/O, patches 4-7 add
the refusals on the common paths and the capability flag, and patch 8
enables ext4.

Known limitation: 
1. A dma-buf read that reaches a hole or an unwritten
extent fails as a whole, even when an earlier mapped extent was already
transferred into the buffer, so the caller does not learn how much of the
dma-buf was filled.  Reporting the prefix instead would return a short
read, which callers cannot tell apart from the end of the file, and both
the buffered and the direct path normally hide holes by zero-filling.
Probing the mapping before submitting anything would fix it, but that
belongs to the common iomap series.

2. A refused dma-buf I/O reaches the caller as -EOPNOTSUPP through
iomap_dio_set_error(), which also emits an fserror notification even
though no I/O was submitted.  The report could be limited to requests
that did submit a bio, since iomap_dio_bio_iter() accounts dio->size at
submission time, but that changes what fserror users see for every iomap
filesystem, so this version leaves it as it is and asks the fserror
maintainers.

Testing:
- io_uring dma-buf suite (udmabuf + REGISTER_BUFFERS_UPDATE + READ_FIXED /
  WRITE_FIXED) against ext4 on a PCIe NVMe namespace, all passed.
- xfstests -g quick on ext4 devices: 689 tests ran, 11 reported  failures,
  all of them environment related, no failure is attributable to this 
  series.

[1] https://lore.kernel.org/linux-xfs/20261016091919.971295-1-anuj1072538@gmail.com/
[2] https://lore.kernel.org/all/20260908131545.105987-1-liwang@kylinos.cn/

Changelog:
==========
RFC v2:
- Rebased onto v7.4-rc2 and dropped the dependency on a separate base
  tree; the block and iomap prerequisites are patches 1-2.
- Added patch 3, which reports why a dma-buf direct I/O could not be done
  instead of asking for a buffered fallback that the callers refuse.
- Split the block changes: patch 4 only factors the integrity check
  into a helper, and patch 5 refuses a dma-buf bio in the inline
  encryption fallback, which is where the data pages are walked
  instead of in blk_mq_submit_bio(). (Christoph)
- Dropped the mm/filemap and iomap_file_buffered_write() guards; the
  refusals now happen in the callers that would fall back to buffered
  or copied I/O. (Christoph)
- Added the FMODE_CAN_DMABUF_IO flag and use it to check whether a bdev or
  a filesystem can do dma-buf I/O. (Christoph)

RFC v1:
- https://lore.kernel.org/all/20261105065847.196540-1-mengmeng.zhao@linux.dev/

Mengmeng Zhao (6):
  iomap: don't ask for a buffered fallback for dma-buf iterators
  blk-mq: factor out a dma-buf bio refusal helper
  blk-crypto: refuse dma-buf bios in the fallback path
  fs: add FMODE_CAN_DMABUF_IO and require it for dma-buf I/O contexts
  dax: refuse dma-buf iterators in dax_iomap_rw()
  ext4: support dma-buf registered buffers for direct I/O

Nitesh Shetty (2):
  block: factor out bdev_init_dma_buf_io_ctx()
  iomap: add dma-buf direct I/O guards

 .../filesystems/iomap/operations.rst          |  3 ++
 block/bdev.c                                  | 14 ++++++
 block/blk-crypto.c                            |  8 ++++
 block/blk-mq.c                                | 24 ++++++----
 block/fops.c                                  | 12 +----
 drivers/dma-buf/dma-buf-io.c                  | 13 ++++--
 fs/dax.c                                      |  4 ++
 fs/ext4/ext4.h                                | 11 +++++
 fs/ext4/file.c                                | 44 +++++++++++++++++--
 fs/iomap/direct-io.c                          | 41 +++++++++++++++--
 include/linux/blkdev.h                        |  8 ++++
 include/linux/fs.h                            |  8 +++-
 12 files changed, 159 insertions(+), 31 deletions(-)


base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb
-- 
2.43.0


^ permalink raw reply	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-11-25 17:16 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-25 17:16 [RFC PATCH v2 2/8] iomap: add dma-buf direct I/O guards Yun Wang
  -- strict thread matches above, loose matches on Subject: below --
2026-11-13  7:06 [RFC PATCH v2 0/8] ext4: Add dma-buf read/write support Mengmeng Zhao
2026-11-13  7:06 ` [RFC PATCH v2 2/8] iomap: add dma-buf direct I/O guards Mengmeng Zhao

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox

all inboxes | Powered by JetHome®