From 68a0be3ce975ab85af0d64fc1669ef0fdb552fb5 Mon Sep 17 00:00:00 2001 From: Kieran Bingham Date: Tue, 29 Jun 2021 16:11:25 +0100 Subject: libcamera: v4l2_videodevice: Handle unexpected buffers A kernel bug can lead to unexpected buffers being dequeued where we haven't entered the buffer in our queuedBuffers_ list. This causes invalid accesses if not handled correctly within libcamera, and while it is a kernel issue, we must protect against unpatched kernels. Handle unexpected buffers by returning a nullptr, and move cache management after the validation of the buffer. Signed-off-by: Kieran Bingham Change-Id: I8c8e0b72a2e529589a1e68b4bcd25bb11c261879 --- src/libcamera/v4l2_videodevice.cpp | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/libcamera/v4l2_videodevice.cpp b/src/libcamera/v4l2_videodevice.cpp index da2af6a1..33cd9fa4 100644 --- a/src/libcamera/v4l2_videodevice.cpp +++ b/src/libcamera/v4l2_videodevice.cpp @@ -1519,9 +1519,28 @@ FrameBuffer *V4L2VideoDevice::dequeueBuffer() LOG(V4L2, Debug) << "Dequeuing buffer " << buf.index; + auto it = queuedBuffers_.find(buf.index); + /* + * If the video node fails to stream-on successfully (which can occur + * when queuing a buffer), a vb2 kernel bug can lead to the buffer which + * returns a failure upon queuing, being mistakenly kept in the kernel. + * This leads to the kernel notifying us that a buffer is available to + * dequeue, which we have no awareness of being queued, and thus we will + * not find it in the queuedBuffers_ list. + * + * Whilst this is a kernel bug and should be fixed there, ensure that we + * safely ignore buffers which are unexpected to prevent crashes on + * unpatched kernels. + */ + if (it == queuedBuffers_.end()) { + LOG(V4L2, Error) + << "Dequeued an unexpected buffer: " << buf.index; + + return nullptr; + } + cache_->put(buf.index); - auto it = queuedBuffers_.find(buf.index); FrameBuffer *buffer = it->second; queuedBuffers_.erase(it); -- cgit v1.2.1