[PATCH v2 0/2] media: videobuf2: publish buffers in bufs_bitmap under mmap_lock

From: Ricardo Ribalda

Date: Tue Nov 03 2026 - 06:31:38 EST


vb2_mmap() only takes q->mmap_lock, not the main queue serialization
lock (q->lock). Commit a286b0837e13 ("media: core: Add bitmap manage
bufs array entries") started setting bits in q->bufs_bitmap inside
__vb2_queue_alloc() before buffer memory is allocated and without
holding q->mmap_lock, allowing a concurrent mmap() to access a
half-initialized buffer and hit a use-after-free if allocation or
.buf_init() fails, and prematurely counting tentative buffers during
partial-allocation .queue_setup() re-checks.

Patch 1 fixes this by dropping set_bit() from vb2_queue_add_buffer() and
publishing the range in q->bufs_bitmap via vb2_queue_publish_buffers()
under q->mmap_lock once allocation and .queue_setup() succeed.

Patch 2 adds smp_mb__before_atomic() / test_bit_acquire() ordering on
q->bufs_bitmap for lockless vb2_get_buffer() callers (such as
vb2_find_buffer() called from stateless mem2mem .device_run() while
VIDIOC_CREATE_BUFS runs on weakly-ordered architectures).

This series was generated by an LLM, but supervised and reviewed by a
human (not the most handsome human, but a human).

---
Changes in v2:
- Keep vb2_queue_add_buffer() without set_bit() so __vb2_queue_alloc()
stays unchanged, and add vb2_queue_publish_buffers() using atomic
set_bit() (rather than non-atomic bitmap_set(), since vb2_get_buffer()
has lockless readers).
- Split the smp_mb__before_atomic() / test_bit_acquire() memory barrier
pair into a separate patch with an explanation of the arm64
VIDIOC_CREATE_BUFS vs vb2_find_buffer() race.
- Drop lockdep_assert_held() from vb2_queue_remove_buffer().
- Simplify the !q->bufs guard in __vb2_queue_free() to 'if (!q->bufs)
return;' (still needed as a NULL check now that __vb2_queue_free()
indexes q->bufs[] directly instead of going through vb2_get_buffer(),
since vb2_core_queue_release() and REQBUFS(0) call it when
q->bufs == NULL).
- Clarify @bufs and @bufs_bitmap documentation in struct vb2_queue.
- Link to v1: https://lore.kernel.org/r/20261102-vb2-mmap_lock-v1-1-fe550fe03ed8@xxxxxxxxxxxx

---
Ricardo Ribalda (2):
media: videobuf2: publish buffers in bufs_bitmap under mmap_lock
media: videobuf2: order buffer initialization before bufs_bitmap publication

drivers/media/common/videobuf2/videobuf2-core.c | 74 +++++++++++++++++++++----
include/media/videobuf2-core.h | 14 +++--
2 files changed, 74 insertions(+), 14 deletions(-)
---
base-commit: 6628e7d4c6b25c8d18f1345e3a20d21829aae7e4
change-id: 20261102-vb2-mmap_lock-959e0cc4edb3

Best regards,
--
Ricardo Ribalda <ribalda@xxxxxxxxxxxx>