Skip to contentSkip to conversation

media: synchronize CPU access to imported DMA-BUFs

PATCH In review Karl Mehltretter 3 participants 7 messages Nov 7 – Nov 12

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

v2 cover media: synchronize CPU access to imported DMA-BUFs

uvcvideo and vivid (when using vb2-vmalloc) access imported DMA-BUFs through a kernel vmap without cache synchronization. When a non-coherent importer such as V3D maps the same DMA-BUF persistently, captured data remains in the CPU cache while physical RAM holds stale bytes.

Add an opt-in uses_cpu_access queue flag for vb2-vmalloc queues to bracket the interval from buf_prepare() through buf_finish() with dma_buf_begin_cpu_access() and dma_buf_end_cpu_access(). Keep this opt-in because some vb2-vmalloc drivers pass imported buffers to hardware, and end CPU access in process context because DMA-BUF callbacks may sleep.

This follows the per-queue flag proposed here:
https://lore.kernel.org/r/CAAFQd5Am5jBev5P1HmsdeHoJfROZat3bi1W=UsN7wpVqw-XUQQ@mail.gmail.com/

Based on Linux 7.4-rc1 with prerequisite patch "media: videobuf2: finish prepared buffers in VIDIOC_REMOVE_BUFS":
https://lore.kernel.org/r/[email protected]/

Changes in v2:
- Split patch 1 of v1 into the standalone VIDIOC_REMOVE_BUFS patch above and use its __vb2_buf_cancel() helper so queue cancellation and VIDIOC_REMOVE_BUFS share the finish path (Tomasz).
- Scope uses_cpu_access to vb2-vmalloc queues and drop the attach_dmabuf dma_dir parameter from vb2_mem_ops, videobuf2-dma-contig, videobuf2-dma-sg and videobuf2-vmalloc (Tomasz).
- Enable uses_cpu_access in vivid only when vivid uses vb2_vmalloc_memops (Tomasz).

Link to v1:
https://lore.kernel.org/r/[email protected]/

Testing:

- Raspberry Pi 500+ (6.18.34+rpt-rpi-2712, aarch64, 16 KiB pages, Sunplus UVC camera 1bcf:2701 and Broadcom V3D 7.1 GPU), backport of the prerequisite patch plus patches 1 and 2: eight 640x480 YUYV frames (614,400 B) captured into DMA-BUFs pre-seeded with 0xA5 and imported into persistent EGL_LINUX_DMA_BUF_EXT textures before VIDIOC_STREAMON, then copied by V3D 7.1 immediately after VIDIOC_DQBUF:

  Heap                        Baseline stale      Patched v2 stale
  /dev/dma_heap/linux,cma     8/8 (329,890 B)        0/8 (0 B)
  /dev/dma_heap/system        8/8 (509,818 B)        0/8 (0 B)

- QEMU virt (arm64, Linux 7.4-rc1 with the prerequisite patch and patches 1-3, VIDEO_ADV_DEBUG=y, DEBUG_ATOMIC_SLEEP=y): six vivid lifecycle cases (stream, streamoff-queued, prepare-reqbufs0, prepare-remove, close-streaming, replace-dmabuf) across single-planar and multi-planar queues with kprobe counters on dma_buf_begin_cpu_access() and dma_buf_end_cpu_access():

Queue begin/end calls Unbalanced Warnings

  vivid vb2-vmalloc (SP)           34 / 34            0           0
  vivid vb2-vmalloc (MP)           34 / 34            0           0
  vivid vb2-dma-contig (SP)         0 / 0             0           0
  vivid vb2-dma-contig (MP)         0 / 0             0           0
  20x prepare-remove (vmalloc)     20 / 20            0           0

Assisted by an LLM for code changes, test harnesses and commit message drafting.

Karl Mehltretter (3):
media: videobuf2: add opt-in DMA-BUF CPU access
media: uvcvideo: synchronize imported DMA-BUFs for CPU access
media: vivid: synchronize imported DMA-BUFs for CPU access

 .../media/common/videobuf2/videobuf2-core.c   | 76 +++++++++++++++++++
 drivers/media/test-drivers/vivid/vivid-core.c |  4 +-
 drivers/media/usb/uvc/uvc_queue.c             |  1 +
 include/media/videobuf2-core.h                |  5 ++
 4 files changed, 85 insertions(+), 1 deletion(-)

base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
prerequisite-patch-id: aa99d5c3c27082cbe003ed94a195e3de415777c9

Signature · 1 line
2.39.5 (Apple Git-154)
#1 lore raw

PATCH v2 1/3 media: videobuf2: add opt-in DMA-BUF CPU access

Drivers that transfer buffer contents with the CPU must bracket access to imported DMA-BUFs with dma_buf_begin_cpu_access() and dma_buf_end_cpu_access().

Add a uses_cpu_access queue flag for vb2-vmalloc queues to bracket the interval from buf_prepare() through buf_finish(), using read access for output queues and write access for capture queues.

Keep this opt-in because some vb2-vmalloc drivers pass imported buffers to hardware, and end access in process context because DMA-BUF callbacks may sleep and return errors.

---
v2:
- Scope uses_cpu_access to vb2-vmalloc queues and drop the attach_dmabuf dma_dir parameter from vb2_mem_ops and the allocators (Tomasz Figa).
- Call __vb2_buf_end_cpu_access() from __vb2_buf_cancel() (Tomasz Figa).

 .../media/common/videobuf2/videobuf2-core.c   | 76 +++++++++++++++++++
 include/media/videobuf2-core.h                |  5 ++
 2 files changed, 81 insertions(+)
drivers/media/common/videobuf2/videobuf2-core.c +76 -0
index 29e539ee002e..6c32d3cccb93 100644
@@ -371,6 +371,65 @@ static void __vb2_buf_mem_finish(struct vb2_buffer *vb)
 		call_void_memop(vb, finish, vb->planes[plane].mem_priv);
 }
 
+/* Output buffers are read by the driver; capture buffers are written. */
+static enum dma_data_direction vb2_cpu_access_dir(const struct vb2_queue *q)
+{
+	return q->is_output ? DMA_FROM_DEVICE : DMA_TO_DEVICE;
+}
+
+static bool __vb2_dmabuf_is_duplicate(const struct vb2_buffer *vb,
+				      unsigned int plane)
+{
+	unsigned int i;
+
+	for (i = 0; i < plane; i++)
+		if (vb->planes[i].dbuf == vb->planes[plane].dbuf)
+			return true;
+
+	return false;
+}
+
+static void __vb2_buf_end_cpu_access(struct vb2_buffer *vb,
+				     unsigned int num_planes)
+{
+	struct vb2_queue *q = vb->vb2_queue;
+	enum dma_data_direction dir = vb2_cpu_access_dir(q);
+	unsigned int plane;
+
+	for (plane = 0; plane < num_planes; plane++) {
+		int ret;
+
+		if (__vb2_dmabuf_is_duplicate(vb, plane))
+			continue;
+
+		ret = dma_buf_end_cpu_access(vb->planes[plane].dbuf, dir);
+		if (ret)
+			pr_warn_ratelimited("[%s] failed to end CPU access to dmabuf plane %u: %d\n",
+					    q->name, plane, ret);
+	}
+}
+
+static int __vb2_buf_begin_cpu_access(struct vb2_buffer *vb)
+{
+	struct vb2_queue *q = vb->vb2_queue;
+	enum dma_data_direction dir = vb2_cpu_access_dir(q);
+	unsigned int plane;
+	int ret;
+
+	for (plane = 0; plane < vb->num_planes; plane++) {
+		if (__vb2_dmabuf_is_duplicate(vb, plane))
+			continue;
+
+		ret = dma_buf_begin_cpu_access(vb->planes[plane].dbuf, dir);
+		if (ret) {
+			__vb2_buf_end_cpu_access(vb, plane);
+			return ret;
+		}
+	}
+
+	return 0;
+}
+
 /*
  * __setup_offsets() - setup unique offsets ("cookies") for every plane in
  * the buffer.
@@ -1504,9 +1563,21 @@ static int __prepare_dmabuf(struct vb2_buffer *vb)
 		}
 	}
 
+	if (q->uses_cpu_access) {
+		ret = __vb2_buf_begin_cpu_access(vb);
+		if (ret) {
+			dprintk(q, 1, "failed to begin CPU access to dmabuf: %d\n",
+				ret);
+			call_void_vb_qop(vb, buf_cleanup, vb);
+			goto err_put_vb2_buf;
+		}
+	}
+
 	ret = call_vb_qop(vb, buf_prepare, vb);
 	if (ret) {
 		dprintk(q, 1, "buffer preparation failed\n");
+		if (q->uses_cpu_access)
+			__vb2_buf_end_cpu_access(vb, vb->num_planes);
 		call_void_vb_qop(vb, buf_cleanup, vb);
 		goto err_put_vb2_buf;
 	}
@@ -1720,6 +1791,7 @@ EXPORT_SYMBOL_GPL(vb2_core_prepare_buf);
 static void __vb2_buf_cancel(struct vb2_buffer *vb)
 {
 	struct media_request *req = vb->req_obj.req;
+	struct vb2_queue *q = vb->vb2_queue;
 
 	/*
 	 * If a request is associated with this buffer, then
@@ -1743,6 +1815,8 @@ static void __vb2_buf_cancel(struct vb2_buffer *vb)
 
 	if (vb->prepared) {
 		call_void_vb_qop(vb, buf_finish, vb);
+		if (q->memory == VB2_MEMORY_DMABUF && q->uses_cpu_access)
+			__vb2_buf_end_cpu_access(vb, vb->num_planes);
 		vb->prepared = 0;
 	}
 	__vb2_dqbuf(vb);
@@ -2191,6 +2265,8 @@ int vb2_core_dqbuf(struct vb2_queue *q, unsigned int *pindex, void *pb,
 	}
 
 	call_void_vb_qop(vb, buf_finish, vb);
+	if (q->memory == VB2_MEMORY_DMABUF && q->uses_cpu_access)
+		__vb2_buf_end_cpu_access(vb, vb->num_planes);
 	vb->prepared = 0;
 
 	if (pindex)
include/media/videobuf2-core.h +5 -0
index 4b4f4c15c53a..bbcdd8c8989a 100644
@@ -510,6 +510,10 @@ struct vb2_buf_ops {
  *		->finish().
  * @non_coherent_mem: when set queue will attempt to allocate buffers using
  *		non-coherent memory.
+ * @uses_cpu_access: the driver transfers buffer data with the CPU instead of
+ *		DMA. For imported dma-bufs on vb2-vmalloc queues, videobuf2
+ *		brackets the interval from buf_prepare through buf_finish with
+ *		dma_buf_begin_cpu_access() and dma_buf_end_cpu_access().
  * @lock:	pointer to a mutex that protects the &struct vb2_queue. The
  *		driver must set this to a mutex to let the v4l2 core serialize
  *		the queuing ioctls. This lock is used when waiting for a new
@@ -614,6 +618,7 @@ struct vb2_queue {
 	unsigned int			uses_requests:1;
 	unsigned int			allow_cache_hints:1;
 	unsigned int			non_coherent_mem:1;
+	unsigned int			uses_cpu_access:1;
 
 	struct mutex			*lock;
 	void				*owner;
Signature · 1 line
2.39.5 (Apple Git-154)
#2 lore raw

PATCH v2 2/3 media: uvcvideo: synchronize imported DMA-BUFs for CPU access

In reply to Karl Mehltretter

uvcvideo writes USB payloads into imported DMA-BUFs with the CPU without cache synchronization, leaving physical RAM stale for non-coherent DMA importers.

Set uses_cpu_access to bracket the driver's CPU access.

Fixes ccc4c539c05f ("[media] v4l: uvc: add support for DMABUF importing")
---
 drivers/media/usb/uvc/uvc_queue.c | 1 +
 1 file changed, 1 insertion(+)
drivers/media/usb/uvc/uvc_queue.c +1 -0
index 3c002c8f442f..1f92ee96e071 100644
@@ -247,6 +247,7 @@ int uvc_queue_init(struct uvc_streaming *stream, struct uvc_video_queue *queue,
 	queue->queue.drv_priv = queue;
 	queue->queue.buf_struct_size = sizeof(struct uvc_buffer);
 	queue->queue.mem_ops = &vb2_vmalloc_memops;
+	queue->queue.uses_cpu_access = true;
 	queue->queue.timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC
 		| V4L2_BUF_FLAG_TSTAMP_SRC_SOE;
 	queue->queue.lock = &queue->mutex;
Signature · 1 line
2.39.5 (Apple Git-154)
#3 lore raw

PATCH v2 3/3 media: vivid: synchronize imported DMA-BUFs for CPU access

In reply to Karl Mehltretter

When configured to use vb2-vmalloc, vivid accesses imported DMA-BUFs with the CPU without cache synchronization, leaving physical RAM stale after capture.

Set uses_cpu_access on vb2-vmalloc queues to bracket the driver's CPU access.

Fixes c88a96b023d8 ("[media] vivid: add core driver code")

---
v2:
- Set uses_cpu_access only when vivid uses vb2_vmalloc_memops (allocators[dev->inst] != 1) instead of unconditionally (Tomasz Figa).

 drivers/media/test-drivers/vivid/vivid-core.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/media/test-drivers/vivid/vivid-core.c +3 -1
index c042d92db175..f6c7460cdba7 100644
@@ -919,8 +919,10 @@ static int vivid_create_queue(struct vivid_dev *dev,
 	if (buf_type == V4L2_BUF_TYPE_VBI_CAPTURE)
 		q->max_num_buffers = 32768;
 
-	if (allocators[dev->inst] != 1)
+	if (allocators[dev->inst] != 1) {
 		q->io_modes |= VB2_USERPTR;
+		q->uses_cpu_access = true;
+	}
 	q->drv_priv = dev;
 	q->buf_struct_size = sizeof(struct vivid_buffer);
 	q->ops = ops;
Signature · 1 line
2.39.5 (Apple Git-154)
maintainer
#4 lore raw
In reply to Karl Mehltretter

Hi Karl,

We discussed in v1 how this is not the right approach. Why are you posting a v2 without addressing that ? You need to go back to the design table.

Quoted 78 lines · Karl Mehltretter

uvcvideo and vivid (when using vb2-vmalloc) access imported DMA-BUFs through a kernel vmap without cache synchronization. When a non-coherent importer such as V3D maps the same DMA-BUF persistently, captured data remains in the CPU cache while physical RAM holds stale bytes.

Add an opt-in uses_cpu_access queue flag for vb2-vmalloc queues to bracket the interval from buf_prepare() through buf_finish() with dma_buf_begin_cpu_access() and dma_buf_end_cpu_access(). Keep this opt-in because some vb2-vmalloc drivers pass imported buffers to hardware, and end CPU access in process context because DMA-BUF callbacks may sleep.

This follows the per-queue flag proposed here:
https://lore.kernel.org/r/CAAFQd5Am5jBev5P1HmsdeHoJfROZat3bi1W=UsN7wpVqw-XUQQ@mail.gmail.com/

Based on Linux 7.4-rc1 with prerequisite patch "media: videobuf2: finish prepared buffers in VIDIOC_REMOVE_BUFS":
https://lore.kernel.org/r/[email protected]/

Changes in v2:
- Split patch 1 of v1 into the standalone VIDIOC_REMOVE_BUFS patch above and use its __vb2_buf_cancel() helper so queue cancellation and VIDIOC_REMOVE_BUFS share the finish path (Tomasz).
- Scope uses_cpu_access to vb2-vmalloc queues and drop the attach_dmabuf dma_dir parameter from vb2_mem_ops, videobuf2-dma-contig, videobuf2-dma-sg and videobuf2-vmalloc (Tomasz).
- Enable uses_cpu_access in vivid only when vivid uses vb2_vmalloc_memops (Tomasz).

Link to v1:
https://lore.kernel.org/r/[email protected]/

Testing:

- Raspberry Pi 500+ (6.18.34+rpt-rpi-2712, aarch64, 16 KiB pages, Sunplus UVC camera 1bcf:2701 and Broadcom V3D 7.1 GPU), backport of the prerequisite patch plus patches 1 and 2: eight 640x480 YUYV frames (614,400 B) captured into DMA-BUFs pre-seeded with 0xA5 and imported into persistent EGL_LINUX_DMA_BUF_EXT textures before VIDIOC_STREAMON, then copied by V3D 7.1 immediately after VIDIOC_DQBUF:

  Heap                        Baseline stale      Patched v2 stale
  /dev/dma_heap/linux,cma     8/8 (329,890 B)        0/8 (0 B)
  /dev/dma_heap/system        8/8 (509,818 B)        0/8 (0 B)

- QEMU virt (arm64, Linux 7.4-rc1 with the prerequisite patch and patches 1-3, VIDEO_ADV_DEBUG=y, DEBUG_ATOMIC_SLEEP=y): six vivid lifecycle cases (stream, streamoff-queued, prepare-reqbufs0, prepare-remove, close-streaming, replace-dmabuf) across single-planar and multi-planar queues with kprobe counters on dma_buf_begin_cpu_access() and dma_buf_end_cpu_access():

Queue begin/end calls Unbalanced Warnings

  vivid vb2-vmalloc (SP)           34 / 34            0           0
  vivid vb2-vmalloc (MP)           34 / 34            0           0
  vivid vb2-dma-contig (SP)         0 / 0             0           0
  vivid vb2-dma-contig (MP)         0 / 0             0           0
  20x prepare-remove (vmalloc)     20 / 20            0           0

Assisted by an LLM for code changes, test harnesses and commit message drafting.

Karl Mehltretter (3):
media: videobuf2: add opt-in DMA-BUF CPU access
media: uvcvideo: synchronize imported DMA-BUFs for CPU access
media: vivid: synchronize imported DMA-BUFs for CPU access

 .../media/common/videobuf2/videobuf2-core.c   | 76 +++++++++++++++++++
 drivers/media/test-drivers/vivid/vivid-core.c |  4 +-
 drivers/media/usb/uvc/uvc_queue.c             |  1 +
 include/media/videobuf2-core.h                |  5 ++
 4 files changed, 85 insertions(+), 1 deletion(-)

base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
prerequisite-patch-id: aa99d5c3c27082cbe003ed94a195e3de415777c9

Signature · 1 line
2.39.5 (Apple Git-154)
Signature · 3 lines
Regards,

Laurent Pinchart
#5 lore raw
Quoted 6 lines · Laurent Pinchart

Hi Karl,

We discussed in v1 how this is not the right approach. Why are you posting a v2 without addressing that ? You need to go back to the design table.

v1 ended with two conflicting positions on non-coherent DMA-BUFs:

- Laurent [1] and Nicolas [2]: end_cpu_access(WRITE) only marks the CPU cache dirty, and non-coherent DMA importers clean before starting DMA. Persistent DRM/KMS imports then need a sync call on each submission.
- Christian [3]: devices must access DMA-BUFs coherently with the CPU, using begin/end_cpu_access() around CPU accesses. Importing a buffer with dirty CPU caches onto a non-coherent device is intentionally unsupported. Today cma_heap and system_heap sync all mapped attachments inside begin/end_cpu_access().

On my Pi 500+ with a USB UVC camera (640x480 YUYV) and V3D on CMA DMA-BUFs:

- Without vb2 CPU sync, V3D reads stale data on 8/8 zero-copy frames.
- With vb2 begin/end_cpu_access() on cma_heap, zero-copy V3D is clean (0/8 stale). CPU capture takes 91 us/frame without a V3D import, and 144 us/frame when an idle V3D PRIME import is attached.
- With a test heap that tracks CPU cache state and syncs imported BOs at V3D job submission, zero-copy V3D stays clean (0/8 stale) and the idle-V3D CPU read drops back to 89 us/frame.

Question to all: should I look at opt-in cache-state tracking in dma-buf (with a sync call before DMA submission), or keep begin/end_cpu_access() as is and handle CPU consumers via V4L2 cache hints?

[1] https://lore.kernel.org/r/[email protected]/
[2] https://lore.kernel.org/r/[email protected]/
[3] https://lore.kernel.org/r/[email protected]/

Thanks,
Karl

#6 lore raw
Quoted 30 lines · Karl Mehltretter
Quoted 6 lines · Laurent Pinchart

Hi Karl,

We discussed in v1 how this is not the right approach. Why are you posting a v2 without addressing that ? You need to go back to the design table.

v1 ended with two conflicting positions on non-coherent DMA-BUFs:

- Laurent [1] and Nicolas [2]: end_cpu_access(WRITE) only marks the CPU cache dirty, and non-coherent DMA importers clean before starting DMA. Persistent DRM/KMS imports then need a sync call on each submission.
- Christian [3]: devices must access DMA-BUFs coherently with the CPU, using begin/end_cpu_access() around CPU accesses. Importing a buffer with dirty CPU caches onto a non-coherent device is intentionally unsupported. Today cma_heap and system_heap sync all mapped attachments inside begin/end_cpu_access().

On my Pi 500+ with a USB UVC camera (640x480 YUYV) and V3D on CMA DMA-BUFs:

- Without vb2 CPU sync, V3D reads stale data on 8/8 zero-copy frames.
- With vb2 begin/end_cpu_access() on cma_heap, zero-copy V3D is clean (0/8 stale). CPU capture takes 91 us/frame without a V3D import, and 144 us/frame when an idle V3D PRIME import is attached.
- With a test heap that tracks CPU cache state and syncs imported BOs at V3D job submission, zero-copy V3D stays clean (0/8 stale) and the idle-V3D CPU read drops back to 89 us/frame.

Quoted 4 lines

Question to all: should I look at opt-in cache-state tracking in dma-buf (with a sync call before DMA submission), or keep begin/end_cpu_access() as is and handle CPU consumers via V4L2 cache hints?

A sync call before DMA operation is something we intentionally rejected.

Background is that exporters should export the buffers as they need/use it and not have specialized handling just to serve importers which would be not testable without the importer etc...

What we could do is to consistently use begin/end_cpu_access() and/or let exporters expose if their buffers might be dirty in the CPU cache so that importers can properly reject them.

Regards,
Christian.

Quoted 7 lines

[1] https://lore.kernel.org/r/[email protected]/
[2] https://lore.kernel.org/r/[email protected]/
[3] https://lore.kernel.org/r/[email protected]/

Thanks,
Karl