Linux virtualization list
 help / color / mirror / Atom feed
* [PATCH v11 0/6] media: add virtio-media driver
@ 2026-11-20 21:59 Brian Daniels
  2026-11-20 21:59 ` [PATCH v11 1/6] media: virtio: Add core driver and session management Brian Daniels
                   ` (5 more replies)
  0 siblings, 6 replies; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Brian Daniels

From: Alexandre Courbot <gnurou@gmail.com>

Add the first version of the virtio-media driver.

This driver acts roughly as a V4L2 relay between user-space and the
virtio virtual device on the host, so it is relatively simple, yet
unconventional. It doesn't use VB2 or other frameworks typically used in
a V4L2 driver, and most of its complexity resides in correctly and
efficiently building the virtio descriptor chain to pass to the host,
avoiding copies whenever possible. This is done by
scatterlist_builder.[ch].

This version supports MMAP buffers. DMABUF support is still pending.
---
Guest Setup

Tests were ran on a Debian 12 guest running with crosvm. The guest image
was created with:

$ virt-builder debian-12 --root-password password:""

Build crosvm and launch the guest starting at the "Crosvm" section on
this page: https://github.com/chromeos/virtio-media/blob/main/TRY_IT_OUT.md#crosvm

NOTE: Before running v4l2-compliance in the guest, you need to install
v4l-utils and ffmpeg:

$ apt update && apt install v4l-utils ffmpeg

---
Compliance Testing

This was tested using v4l2-compliance. Since virtio-media serves as
a proxy to host devices for the guest VMs, we expect the guest
compliance test to essentially match the host compliance test for the
same device.

NOTE: A single failure is fixed when v4l2-compliance is ran on the guest
by patching the v4l2r crate used by crosvm. The patch I used hasn't been
merged but is available here: https://github.com/Gnurou/v4l2r/pull/66.

All tests used a Logitech USB Webcam C925e.

As tested on the host:

$ v4l2-compliance -d0 -s

v4l2-compliance 1.33.0-5523, 64 bits, 64-bit time_t
v4l2-compliance SHA: 7e25bb929095 2026-10-29 15:02:40

Compliance test for uvcvideo device /dev/video0:

Driver Info:
	Driver name      : uvcvideo
	Card type        : Logitech Webcam C925e
	Bus info         : usb-0000:04:00.1-3
	Driver version   : 7.1.6
	Capabilities     : 0x84a00001
		Video Capture
		Metadata Capture
		Streaming
		Extended Pix Format
		Device Capabilities
	Device Caps      : 0x04200001
		Video Capture
		Streaming
		Extended Pix Format
Media Driver Info:
	Driver name      : uvcvideo
	Model            : Logitech Webcam C925e
	Serial           : 686F371F
	Bus info         : usb-0000:04:00.1-3
	Media version    : 7.1.6
	Hardware revision: 0x00000016 (22)
	Driver version   : 7.1.6
Interface Info:
	ID               : 0x03000002
	Type             : V4L Video
Entity Info:
	ID               : 0x00000001 (1)
	Name             : Logitech Webcam C925e
	Function         : V4L2 I/O
	Flags            : default
	Pad 0x01000007   : 0: Sink
	  Link 0x0200001f: from remote pad 0x100000a of entity 'Processing 3' (Video Pixel Formatter): Data, Enabled, Immutable

Required ioctls:
	test MC information (see 'Media Driver Info' above): OK
	test VIDIOC_QUERYCAP: OK
	test invalid ioctls: OK

Allow for multiple opens:
	test second /dev/video0 open: OK
	test VIDIOC_QUERYCAP: OK
	test VIDIOC_G/S_PRIORITY: OK
	test for unlimited opens: OK

Debug ioctls:
	test VIDIOC_DBG_G/S_REGISTER: OK (Not Supported)
	test VIDIOC_LOG_STATUS: OK (Not Supported)

Input ioctls:
	test VIDIOC_G/S_TUNER/ENUM_FREQ_BANDS: OK (Not Supported)
	test VIDIOC_G/S_FREQUENCY: OK (Not Supported)
	test VIDIOC_S_HW_FREQ_SEEK: OK (Not Supported)
	test VIDIOC_ENUMAUDIO: OK (Not Supported)
	test VIDIOC_G/S/ENUMINPUT: OK
	test VIDIOC_G/S_AUDIO: OK (Not Supported)
	Inputs: 1 Audio Inputs: 0 Tuners: 0

Output ioctls:
	test VIDIOC_G/S_MODULATOR: OK (Not Supported)
	test VIDIOC_G/S_FREQUENCY: OK (Not Supported)
	test VIDIOC_ENUMAUDOUT: OK (Not Supported)
	test VIDIOC_G/S/ENUMOUTPUT: OK (Not Supported)
	test VIDIOC_G/S_AUDOUT: OK (Not Supported)
	Outputs: 0 Audio Outputs: 0 Modulators: 0

Input/Output configuration ioctls:
	test VIDIOC_ENUM/G/S/QUERY_STD: OK (Not Supported)
	test VIDIOC_ENUM/G/S/QUERY_DV_TIMINGS: OK (Not Supported)
	test VIDIOC_DV_TIMINGS_CAP: OK (Not Supported)
	test VIDIOC_G/S_EDID: OK (Not Supported)

Control ioctls (Input 0):
	test VIDIOC_QUERY_EXT_CTRL/QUERYMENU: OK
	test VIDIOC_QUERYCTRL: OK
	test VIDIOC_G/S_CTRL: OK
	test VIDIOC_G/S/TRY_EXT_CTRLS: OK
	test VIDIOC_(UN)SUBSCRIBE_EVENT/DQEVENT: OK
	test VIDIOC_G/S_JPEGCOMP: OK (Not Supported)
	Standard Controls: 19 Private Controls: 0

Format ioctls (Input 0):
	test VIDIOC_ENUM_FMT/FRAMESIZES/FRAMEINTERVALS: OK
	test VIDIOC_G/S_PARM: OK
	test VIDIOC_G_FBUF: OK (Not Supported)
	test VIDIOC_G_FMT: OK
	test VIDIOC_TRY_FMT: OK
	test VIDIOC_S_FMT: OK
	test VIDIOC_G_SLICED_VBI_CAP: OK (Not Supported)
	test Cropping: OK (Not Supported)
	test Composing: OK (Not Supported)
	test Scaling: OK (Not Supported)

Codec ioctls (Input 0):
	test VIDIOC_(TRY_)ENCODER_CMD: OK (Not Supported)
	test VIDIOC_G_ENC_INDEX: OK (Not Supported)
	test VIDIOC_(TRY_)DECODER_CMD: OK (Not Supported)

Buffer ioctls (Input 0):
	test VIDIOC_REQBUFS/CREATE_BUFS/QUERYBUF: OK
	test CREATE_BUFS maximum buffers: OK
	test VIDIOC_REMOVE_BUFS: OK
	test VIDIOC_EXPBUF: OK
	test Requests: OK (Not Supported)
	test blocking wait: OK

Test input 0:

Streaming ioctls:
	test read/write: OK (Not Supported)

	Video Capture: Frame #000
	Video Capture: Frame #001
	Video Capture: Frame #002
	Video Capture: Frame #003
	Video Capture: Frame #004
	Video Capture: Frame #005
	Video Capture: Frame #006
	Video Capture: Frame #007
	Video Capture: Frame #008
	Video Capture: Frame #009
	Video Capture: Frame #010
	Video Capture: Frame #011
	Video Capture: Frame #012
	Video Capture: Frame #013
	Video Capture: Frame #014
	Video Capture: Frame #015
	Video Capture: Frame #016
	Video Capture: Frame #017
	Video Capture: Frame #018
	Video Capture: Frame #019
	Video Capture: Frame #020
	Video Capture: Frame #021
	Video Capture: Frame #022
	Video Capture: Frame #023
	Video Capture: Frame #024
	Video Capture: Frame #025
	Video Capture: Frame #026
	Video Capture: Frame #027
	Video Capture: Frame #028
	Video Capture: Frame #029
	Video Capture: Frame #030
	Video Capture: Frame #031
	Video Capture: Frame #032
	Video Capture: Frame #033
	Video Capture: Frame #034
	Video Capture: Frame #035
	Video Capture: Frame #036
	Video Capture: Frame #037
	Video Capture: Frame #038
	Video Capture: Frame #039
	Video Capture: Frame #040
	Video Capture: Frame #041
	Video Capture: Frame #042
	Video Capture: Frame #043
	Video Capture: Frame #044
	Video Capture: Frame #045
	Video Capture: Frame #046
	Video Capture: Frame #047
	Video Capture: Frame #048
	Video Capture: Frame #049
	Video Capture: Frame #050
	Video Capture: Frame #051
	Video Capture: Frame #052
	Video Capture: Frame #053
	Video Capture: Frame #054
	Video Capture: Frame #055
	Video Capture: Frame #056
	Video Capture: Frame #057
	Video Capture: Frame #058
	Video Capture: Frame #059

	test MMAP (no poll, REQBUFS): OK

	Video Capture: Frame #000 (select)
	Video Capture: Frame #001 (select)
	Video Capture: Frame #002 (select)
	Video Capture: Frame #003 (select)
	Video Capture: Frame #004 (select)
	Video Capture: Frame #005 (select)
	Video Capture: Frame #006 (select)
	Video Capture: Frame #007 (select)
	Video Capture: Frame #008 (select)
	Video Capture: Frame #009 (select)
	Video Capture: Frame #010 (select)
	Video Capture: Frame #011 (select)
	Video Capture: Frame #012 (select)
	Video Capture: Frame #013 (select)
	Video Capture: Frame #014 (select)
	Video Capture: Frame #015 (select)
	Video Capture: Frame #016 (select)
	Video Capture: Frame #017 (select)
	Video Capture: Frame #018 (select)
	Video Capture: Frame #019 (select)
	Video Capture: Frame #020 (select)
	Video Capture: Frame #021 (select)
	Video Capture: Frame #022 (select)
	Video Capture: Frame #023 (select)
	Video Capture: Frame #024 (select)
	Video Capture: Frame #025 (select)
	Video Capture: Frame #026 (select)
	Video Capture: Frame #027 (select)
	Video Capture: Frame #028 (select)
	Video Capture: Frame #029 (select)
	Video Capture: Frame #030 (select)
	Video Capture: Frame #031 (select)
	Video Capture: Frame #032 (select)
	Video Capture: Frame #033 (select)
	Video Capture: Frame #034 (select)
	Video Capture: Frame #035 (select)
	Video Capture: Frame #036 (select)
	Video Capture: Frame #037 (select)
	Video Capture: Frame #038 (select)
	Video Capture: Frame #039 (select)
	Video Capture: Frame #040 (select)
	Video Capture: Frame #041 (select)
	Video Capture: Frame #042 (select)
	Video Capture: Frame #043 (select)
	Video Capture: Frame #044 (select)
	Video Capture: Frame #045 (select)
	Video Capture: Frame #046 (select)
	Video Capture: Frame #047 (select)
	Video Capture: Frame #048 (select)
	Video Capture: Frame #049 (select)
	Video Capture: Frame #050 (select)
	Video Capture: Frame #051 (select)
	Video Capture: Frame #052 (select)
	Video Capture: Frame #053 (select)
	Video Capture: Frame #054 (select)
	Video Capture: Frame #055 (select)
	Video Capture: Frame #056 (select)
	Video Capture: Frame #057 (select)
	Video Capture: Frame #058 (select)
	Video Capture: Frame #059 (select)

	test MMAP (select, REQBUFS): OK

	Video Capture: Frame #000 (epoll)
	Video Capture: Frame #001 (epoll)
	Video Capture: Frame #002 (epoll)
	Video Capture: Frame #003 (epoll)
	Video Capture: Frame #004 (epoll)
	Video Capture: Frame #005 (epoll)
	Video Capture: Frame #006 (epoll)
	Video Capture: Frame #007 (epoll)
	Video Capture: Frame #008 (epoll)
	Video Capture: Frame #009 (epoll)
	Video Capture: Frame #010 (epoll)
	Video Capture: Frame #011 (epoll)
	Video Capture: Frame #012 (epoll)
	Video Capture: Frame #013 (epoll)
	Video Capture: Frame #014 (epoll)
	Video Capture: Frame #015 (epoll)
	Video Capture: Frame #016 (epoll)
	Video Capture: Frame #017 (epoll)
	Video Capture: Frame #018 (epoll)
	Video Capture: Frame #019 (epoll)
	Video Capture: Frame #020 (epoll)
	Video Capture: Frame #021 (epoll)
	Video Capture: Frame #022 (epoll)
	Video Capture: Frame #023 (epoll)
	Video Capture: Frame #024 (epoll)
	Video Capture: Frame #025 (epoll)
	Video Capture: Frame #026 (epoll)
	Video Capture: Frame #027 (epoll)
	Video Capture: Frame #028 (epoll)
	Video Capture: Frame #029 (epoll)
	Video Capture: Frame #030 (epoll)
	Video Capture: Frame #031 (epoll)
	Video Capture: Frame #032 (epoll)
	Video Capture: Frame #033 (epoll)
	Video Capture: Frame #034 (epoll)
	Video Capture: Frame #035 (epoll)
	Video Capture: Frame #036 (epoll)
	Video Capture: Frame #037 (epoll)
	Video Capture: Frame #038 (epoll)
	Video Capture: Frame #039 (epoll)
	Video Capture: Frame #040 (epoll)
	Video Capture: Frame #041 (epoll)
	Video Capture: Frame #042 (epoll)
	Video Capture: Frame #043 (epoll)
	Video Capture: Frame #044 (epoll)
	Video Capture: Frame #045 (epoll)
	Video Capture: Frame #046 (epoll)
	Video Capture: Frame #047 (epoll)
	Video Capture: Frame #048 (epoll)
	Video Capture: Frame #049 (epoll)
	Video Capture: Frame #050 (epoll)
	Video Capture: Frame #051 (epoll)
	Video Capture: Frame #052 (epoll)
	Video Capture: Frame #053 (epoll)
	Video Capture: Frame #054 (epoll)
	Video Capture: Frame #055 (epoll)
	Video Capture: Frame #056 (epoll)
	Video Capture: Frame #057 (epoll)
	Video Capture: Frame #058 (epoll)
	Video Capture: Frame #059 (epoll)

	test MMAP (epoll, REQBUFS): OK

	Video Capture: Frame #000
	Video Capture: Frame #001
	Video Capture: Frame #002
	Video Capture: Frame #003
	Video Capture: Frame #004
	Video Capture: Frame #005
	Video Capture: Frame #006
	Video Capture: Frame #007
	Video Capture: Frame #008
	Video Capture: Frame #009
	Video Capture: Frame #010
	Video Capture: Frame #011
	Video Capture: Frame #012
	Video Capture: Frame #013
	Video Capture: Frame #014
	Video Capture: Frame #015
	Video Capture: Frame #016
	Video Capture: Frame #017
	Video Capture: Frame #018
	Video Capture: Frame #019
	Video Capture: Frame #020
	Video Capture: Frame #021
	Video Capture: Frame #022
	Video Capture: Frame #023
	Video Capture: Frame #024
	Video Capture: Frame #025
	Video Capture: Frame #026
	Video Capture: Frame #027
	Video Capture: Frame #028
	Video Capture: Frame #029
	Video Capture: Frame #030
	Video Capture: Frame #031
	Video Capture: Frame #032
	Video Capture: Frame #033
	Video Capture: Frame #034
	Video Capture: Frame #035
	Video Capture: Frame #036
	Video Capture: Frame #037
	Video Capture: Frame #038
	Video Capture: Frame #039
	Video Capture: Frame #040
	Video Capture: Frame #041
	Video Capture: Frame #042
	Video Capture: Frame #043
	Video Capture: Frame #044
	Video Capture: Frame #045
	Video Capture: Frame #046
	Video Capture: Frame #047
	Video Capture: Frame #048
	Video Capture: Frame #049
	Video Capture: Frame #050
	Video Capture: Frame #051
	Video Capture: Frame #052
	Video Capture: Frame #053
	Video Capture: Frame #054
	Video Capture: Frame #055
	Video Capture: Frame #056
	Video Capture: Frame #057
	Video Capture: Frame #058
	Video Capture: Frame #059

	test MMAP (no poll, CREATE_BUFS): OK

	Video Capture: Frame #000 (select)
	Video Capture: Frame #001 (select)
	Video Capture: Frame #002 (select)
	Video Capture: Frame #003 (select)
	Video Capture: Frame #004 (select)
	Video Capture: Frame #005 (select)
	Video Capture: Frame #006 (select)
	Video Capture: Frame #007 (select)
	Video Capture: Frame #008 (select)
	Video Capture: Frame #009 (select)
	Video Capture: Frame #010 (select)
	Video Capture: Frame #011 (select)
	Video Capture: Frame #012 (select)
	Video Capture: Frame #013 (select)
	Video Capture: Frame #014 (select)
	Video Capture: Frame #015 (select)
	Video Capture: Frame #016 (select)
	Video Capture: Frame #017 (select)
	Video Capture: Frame #018 (select)
	Video Capture: Frame #019 (select)
	Video Capture: Frame #020 (select)
	Video Capture: Frame #021 (select)
	Video Capture: Frame #022 (select)
	Video Capture: Frame #023 (select)
	Video Capture: Frame #024 (select)
	Video Capture: Frame #025 (select)
	Video Capture: Frame #026 (select)
	Video Capture: Frame #027 (select)
	Video Capture: Frame #028 (select)
	Video Capture: Frame #029 (select)
	Video Capture: Frame #030 (select)
	Video Capture: Frame #031 (select)
	Video Capture: Frame #032 (select)
	Video Capture: Frame #033 (select)
	Video Capture: Frame #034 (select)
	Video Capture: Frame #035 (select)
	Video Capture: Frame #036 (select)
	Video Capture: Frame #037 (select)
	Video Capture: Frame #038 (select)
	Video Capture: Frame #039 (select)
	Video Capture: Frame #040 (select)
	Video Capture: Frame #041 (select)
	Video Capture: Frame #042 (select)
	Video Capture: Frame #043 (select)
	Video Capture: Frame #044 (select)
	Video Capture: Frame #045 (select)
	Video Capture: Frame #046 (select)
	Video Capture: Frame #047 (select)
	Video Capture: Frame #048 (select)
	Video Capture: Frame #049 (select)
	Video Capture: Frame #050 (select)
	Video Capture: Frame #051 (select)
	Video Capture: Frame #052 (select)
	Video Capture: Frame #053 (select)
	Video Capture: Frame #054 (select)
	Video Capture: Frame #055 (select)
	Video Capture: Frame #056 (select)
	Video Capture: Frame #057 (select)
	Video Capture: Frame #058 (select)
	Video Capture: Frame #059 (select)

	test MMAP (select, CREATE_BUFS): OK

	Video Capture: Frame #000 (epoll)
	Video Capture: Frame #001 (epoll)
	Video Capture: Frame #002 (epoll)
	Video Capture: Frame #003 (epoll)
	Video Capture: Frame #004 (epoll)
	Video Capture: Frame #005 (epoll)
	Video Capture: Frame #006 (epoll)
	Video Capture: Frame #007 (epoll)
	Video Capture: Frame #008 (epoll)
	Video Capture: Frame #009 (epoll)
	Video Capture: Frame #010 (epoll)
	Video Capture: Frame #011 (epoll)
	Video Capture: Frame #012 (epoll)
	Video Capture: Frame #013 (epoll)
	Video Capture: Frame #014 (epoll)
	Video Capture: Frame #015 (epoll)
	Video Capture: Frame #016 (epoll)
	Video Capture: Frame #017 (epoll)
	Video Capture: Frame #018 (epoll)
	Video Capture: Frame #019 (epoll)
	Video Capture: Frame #020 (epoll)
	Video Capture: Frame #021 (epoll)
	Video Capture: Frame #022 (epoll)
	Video Capture: Frame #023 (epoll)
	Video Capture: Frame #024 (epoll)
	Video Capture: Frame #025 (epoll)
	Video Capture: Frame #026 (epoll)
	Video Capture: Frame #027 (epoll)
	Video Capture: Frame #028 (epoll)
	Video Capture: Frame #029 (epoll)
	Video Capture: Frame #030 (epoll)
	Video Capture: Frame #031 (epoll)
	Video Capture: Frame #032 (epoll)
	Video Capture: Frame #033 (epoll)
	Video Capture: Frame #034 (epoll)
	Video Capture: Frame #035 (epoll)
	Video Capture: Frame #036 (epoll)
	Video Capture: Frame #037 (epoll)
	Video Capture: Frame #038 (epoll)
	Video Capture: Frame #039 (epoll)
	Video Capture: Frame #040 (epoll)
	Video Capture: Frame #041 (epoll)
	Video Capture: Frame #042 (epoll)
	Video Capture: Frame #043 (epoll)
	Video Capture: Frame #044 (epoll)
	Video Capture: Frame #045 (epoll)
	Video Capture: Frame #046 (epoll)
	Video Capture: Frame #047 (epoll)
	Video Capture: Frame #048 (epoll)
	Video Capture: Frame #049 (epoll)
	Video Capture: Frame #050 (epoll)
	Video Capture: Frame #051 (epoll)
	Video Capture: Frame #052 (epoll)
	Video Capture: Frame #053 (epoll)
	Video Capture: Frame #054 (epoll)
	Video Capture: Frame #055 (epoll)
	Video Capture: Frame #056 (epoll)
	Video Capture: Frame #057 (epoll)
	Video Capture: Frame #058 (epoll)
	Video Capture: Frame #059 (epoll)

	test MMAP (epoll, CREATE_BUFS): OK

	Video Capture: Frame #000
	Video Capture: Frame #001
	Video Capture: Frame #002
	Video Capture: Frame #003
	Video Capture: Frame #004
	Video Capture: Frame #005
	Video Capture: Frame #006
	Video Capture: Frame #007
	Video Capture: Frame #008
	Video Capture: Frame #009
	Video Capture: Frame #010
	Video Capture: Frame #011
	Video Capture: Frame #012
	Video Capture: Frame #013
	Video Capture: Frame #014
	Video Capture: Frame #015
	Video Capture: Frame #016
	Video Capture: Frame #017
	Video Capture: Frame #018
	Video Capture: Frame #019
	Video Capture: Frame #020
	Video Capture: Frame #021
	Video Capture: Frame #022
	Video Capture: Frame #023
	Video Capture: Frame #024
	Video Capture: Frame #025
	Video Capture: Frame #026
	Video Capture: Frame #027
	Video Capture: Frame #028
	Video Capture: Frame #029
	Video Capture: Frame #030
	Video Capture: Frame #031
	Video Capture: Frame #032
	Video Capture: Frame #033
	Video Capture: Frame #034
	Video Capture: Frame #035
	Video Capture: Frame #036
	Video Capture: Frame #037
	Video Capture: Frame #038
	Video Capture: Frame #039
	Video Capture: Frame #040
	Video Capture: Frame #041
	Video Capture: Frame #042
	Video Capture: Frame #043
	Video Capture: Frame #044
	Video Capture: Frame #045
	Video Capture: Frame #046
	Video Capture: Frame #047
	Video Capture: Frame #048
	Video Capture: Frame #049
	Video Capture: Frame #050
	Video Capture: Frame #051
	Video Capture: Frame #052
	Video Capture: Frame #053
	Video Capture: Frame #054
	Video Capture: Frame #055
	Video Capture: Frame #056
	Video Capture: Frame #057
	Video Capture: Frame #058
	Video Capture: Frame #059

	test USERPTR (no poll): OK

	Video Capture: Frame #000 (select)
	Video Capture: Frame #001 (select)
	Video Capture: Frame #002 (select)
	Video Capture: Frame #003 (select)
	Video Capture: Frame #004 (select)
	Video Capture: Frame #005 (select)
	Video Capture: Frame #006 (select)
	Video Capture: Frame #007 (select)
	Video Capture: Frame #008 (select)
	Video Capture: Frame #009 (select)
	Video Capture: Frame #010 (select)
	Video Capture: Frame #011 (select)
	Video Capture: Frame #012 (select)
	Video Capture: Frame #013 (select)
	Video Capture: Frame #014 (select)
	Video Capture: Frame #015 (select)
	Video Capture: Frame #016 (select)
	Video Capture: Frame #017 (select)
	Video Capture: Frame #018 (select)
	Video Capture: Frame #019 (select)
	Video Capture: Frame #020 (select)
	Video Capture: Frame #021 (select)
	Video Capture: Frame #022 (select)
	Video Capture: Frame #023 (select)
	Video Capture: Frame #024 (select)
	Video Capture: Frame #025 (select)
	Video Capture: Frame #026 (select)
	Video Capture: Frame #027 (select)
	Video Capture: Frame #028 (select)
	Video Capture: Frame #029 (select)
	Video Capture: Frame #030 (select)
	Video Capture: Frame #031 (select)
	Video Capture: Frame #032 (select)
	Video Capture: Frame #033 (select)
	Video Capture: Frame #034 (select)
	Video Capture: Frame #035 (select)
	Video Capture: Frame #036 (select)
	Video Capture: Frame #037 (select)
	Video Capture: Frame #038 (select)
	Video Capture: Frame #039 (select)
	Video Capture: Frame #040 (select)
	Video Capture: Frame #041 (select)
	Video Capture: Frame #042 (select)
	Video Capture: Frame #043 (select)
	Video Capture: Frame #044 (select)
	Video Capture: Frame #045 (select)
	Video Capture: Frame #046 (select)
	Video Capture: Frame #047 (select)
	Video Capture: Frame #048 (select)
	Video Capture: Frame #049 (select)
	Video Capture: Frame #050 (select)
	Video Capture: Frame #051 (select)
	Video Capture: Frame #052 (select)
	Video Capture: Frame #053 (select)
	Video Capture: Frame #054 (select)
	Video Capture: Frame #055 (select)
	Video Capture: Frame #056 (select)
	Video Capture: Frame #057 (select)
	Video Capture: Frame #058 (select)
	Video Capture: Frame #059 (select)

	test USERPTR (select): OK
		warn: v4l2-test-buffers.cpp(2220): Cannot test DMABUF, specify --expbuf-device
	test DMABUF (no poll): OK (Not Supported)
	test DMABUF (select): OK (Not Supported)

Total for uvcvideo device /dev/video0: 60, Succeeded: 60, Failed: 0, Warnings: 1

As tested on the guest:

$ v4l2-compliance -d0 -s --is-uvc

v4l2-compliance 1.33.0-5523, 64 bits, 64-bit time_t
v4l2-compliance SHA: b3a7e9f866ed 2026-10-29 15:25:03

Compliance test for virtio-media device /dev/video0:

Driver Info:
	Driver name      : virtio-media
	Card type        : Logitech Webcam C925e
	Bus info         : platform:virtio-media
	Driver version   : 7.3.0
	Capabilities     : 0x84200001
		Video Capture
		Streaming
		Extended Pix Format
		Device Capabilities
	Device Caps      : 0x04200001
		Video Capture
		Streaming
		Extended Pix Format

Required ioctls:
	test VIDIOC_QUERYCAP: OK
	test invalid ioctls: OK

Allow for multiple opens:
	test second /dev/video0 open: OK
	test VIDIOC_QUERYCAP: OK
	test VIDIOC_G/S_PRIORITY: OK
	test for unlimited opens: OK

Debug ioctls:
	test VIDIOC_DBG_G/S_REGISTER: OK (Not Supported)
	test VIDIOC_LOG_STATUS: OK (Not Supported)

Input ioctls:
	test VIDIOC_G/S_TUNER/ENUM_FREQ_BANDS: OK (Not Supported)
	test VIDIOC_G/S_FREQUENCY: OK (Not Supported)
	test VIDIOC_S_HW_FREQ_SEEK: OK
	test VIDIOC_ENUMAUDIO: OK (Not Supported)
	test VIDIOC_G/S/ENUMINPUT: OK
	test VIDIOC_G/S_AUDIO: OK (Not Supported)
	Inputs: 1 Audio Inputs: 0 Tuners: 0

Output ioctls:
	test VIDIOC_G/S_MODULATOR: OK (Not Supported)
	test VIDIOC_G/S_FREQUENCY: OK (Not Supported)
	test VIDIOC_ENUMAUDOUT: OK (Not Supported)
	test VIDIOC_G/S/ENUMOUTPUT: OK (Not Supported)
	test VIDIOC_G/S_AUDOUT: OK (Not Supported)
	Outputs: 0 Audio Outputs: 0 Modulators: 0

Input/Output configuration ioctls:
	test VIDIOC_ENUM/G/S/QUERY_STD: OK (Not Supported)
	test VIDIOC_ENUM/G/S/QUERY_DV_TIMINGS: OK (Not Supported)
	test VIDIOC_DV_TIMINGS_CAP: OK (Not Supported)
	test VIDIOC_G/S_EDID: OK (Not Supported)

Control ioctls (Input 0):
	test VIDIOC_QUERY_EXT_CTRL/QUERYMENU: OK
	test VIDIOC_QUERYCTRL: OK
	test VIDIOC_G/S_CTRL: OK
	test VIDIOC_G/S/TRY_EXT_CTRLS: OK
	test VIDIOC_(UN)SUBSCRIBE_EVENT/DQEVENT: OK
	test VIDIOC_G/S_JPEGCOMP: OK (Not Supported)
	Standard Controls: 19 Private Controls: 0

Format ioctls (Input 0):
	test VIDIOC_ENUM_FMT/FRAMESIZES/FRAMEINTERVALS: OK
	test VIDIOC_G/S_PARM: OK
	test VIDIOC_G_FBUF: OK (Not Supported)
	test VIDIOC_G_FMT: OK
	test VIDIOC_TRY_FMT: OK
	test VIDIOC_S_FMT: OK
	test VIDIOC_G_SLICED_VBI_CAP: OK (Not Supported)
	test Cropping: OK (Not Supported)
	test Composing: OK (Not Supported)
	test Scaling: OK (Not Supported)

Codec ioctls (Input 0):
	test VIDIOC_(TRY_)ENCODER_CMD: OK (Not Supported)
	test VIDIOC_G_ENC_INDEX: OK (Not Supported)
	test VIDIOC_(TRY_)DECODER_CMD: OK (Not Supported)

Buffer ioctls (Input 0):
	test VIDIOC_REQBUFS/CREATE_BUFS/QUERYBUF: OK
	test CREATE_BUFS maximum buffers: OK
	test VIDIOC_REMOVE_BUFS: OK
	test VIDIOC_EXPBUF: OK (Not Supported)
	test Requests: OK (Not Supported)
	test blocking wait: OK

Test input 0:

Streaming ioctls:
	test read/write: OK (Not Supported)

	Video Capture: Frame #000
	Video Capture: Frame #001
	Video Capture: Frame #002
	Video Capture: Frame #003
	Video Capture: Frame #004
	Video Capture: Frame #005
	Video Capture: Frame #006
	Video Capture: Frame #007
	Video Capture: Frame #008
	Video Capture: Frame #009
	Video Capture: Frame #010
	Video Capture: Frame #011
	Video Capture: Frame #012
	Video Capture: Frame #013
	Video Capture: Frame #014
	Video Capture: Frame #015
	Video Capture: Frame #016
	Video Capture: Frame #017
	Video Capture: Frame #018
	Video Capture: Frame #019
	Video Capture: Frame #020
	Video Capture: Frame #021
	Video Capture: Frame #022
	Video Capture: Frame #023
	Video Capture: Frame #024
	Video Capture: Frame #025
	Video Capture: Frame #026
	Video Capture: Frame #027
	Video Capture: Frame #028
	Video Capture: Frame #029
	Video Capture: Frame #030
	Video Capture: Frame #031
	Video Capture: Frame #032
	Video Capture: Frame #033
	Video Capture: Frame #034
	Video Capture: Frame #035
	Video Capture: Frame #036
	Video Capture: Frame #037
	Video Capture: Frame #038
	Video Capture: Frame #039
	Video Capture: Frame #040
	Video Capture: Frame #041
	Video Capture: Frame #042
	Video Capture: Frame #043
	Video Capture: Frame #044
	Video Capture: Frame #045
	Video Capture: Frame #046
	Video Capture: Frame #047
	Video Capture: Frame #048
	Video Capture: Frame #049
	Video Capture: Frame #050
	Video Capture: Frame #051
	Video Capture: Frame #052
	Video Capture: Frame #053
	Video Capture: Frame #054
	Video Capture: Frame #055
	Video Capture: Frame #056
	Video Capture: Frame #057
	Video Capture: Frame #058
	Video Capture: Frame #059

	test MMAP (no poll, REQBUFS): OK

	Video Capture: Frame #000 (select)
	Video Capture: Frame #001 (select)
	Video Capture: Frame #002 (select)
	Video Capture: Frame #003 (select)
	Video Capture: Frame #004 (select)
	Video Capture: Frame #005 (select)
	Video Capture: Frame #006 (select)
	Video Capture: Frame #007 (select)
	Video Capture: Frame #008 (select)
	Video Capture: Frame #009 (select)
	Video Capture: Frame #010 (select)
	Video Capture: Frame #011 (select)
	Video Capture: Frame #012 (select)
	Video Capture: Frame #013 (select)
	Video Capture: Frame #014 (select)
	Video Capture: Frame #015 (select)
	Video Capture: Frame #016 (select)
	Video Capture: Frame #017 (select)
	Video Capture: Frame #018 (select)
	Video Capture: Frame #019 (select)
	Video Capture: Frame #020 (select)
	Video Capture: Frame #021 (select)
	Video Capture: Frame #022 (select)
	Video Capture: Frame #023 (select)
	Video Capture: Frame #024 (select)
	Video Capture: Frame #025 (select)
	Video Capture: Frame #026 (select)
	Video Capture: Frame #027 (select)
	Video Capture: Frame #028 (select)
	Video Capture: Frame #029 (select)
	Video Capture: Frame #030 (select)
	Video Capture: Frame #031 (select)
	Video Capture: Frame #032 (select)
	Video Capture: Frame #033 (select)
	Video Capture: Frame #034 (select)
	Video Capture: Frame #035 (select)
	Video Capture: Frame #036 (select)
	Video Capture: Frame #037 (select)
	Video Capture: Frame #038 (select)
	Video Capture: Frame #039 (select)
	Video Capture: Frame #040 (select)
	Video Capture: Frame #041 (select)
	Video Capture: Frame #042 (select)
	Video Capture: Frame #043 (select)
	Video Capture: Frame #044 (select)
	Video Capture: Frame #045 (select)
	Video Capture: Frame #046 (select)
	Video Capture: Frame #047 (select)
	Video Capture: Frame #048 (select)
	Video Capture: Frame #049 (select)
	Video Capture: Frame #050 (select)
	Video Capture: Frame #051 (select)
	Video Capture: Frame #052 (select)
	Video Capture: Frame #053 (select)
	Video Capture: Frame #054 (select)
	Video Capture: Frame #055 (select)
	Video Capture: Frame #056 (select)
	Video Capture: Frame #057 (select)
	Video Capture: Frame #058 (select)
	Video Capture: Frame #059 (select)

	test MMAP (select, REQBUFS): OK

	Video Capture: Frame #000 (epoll)
	Video Capture: Frame #001 (epoll)
	Video Capture: Frame #002 (epoll)
	Video Capture: Frame #003 (epoll)
	Video Capture: Frame #004 (epoll)
	Video Capture: Frame #005 (epoll)
	Video Capture: Frame #006 (epoll)
	Video Capture: Frame #007 (epoll)
	Video Capture: Frame #008 (epoll)
	Video Capture: Frame #009 (epoll)
	Video Capture: Frame #010 (epoll)
	Video Capture: Frame #011 (epoll)
	Video Capture: Frame #012 (epoll)
	Video Capture: Frame #013 (epoll)
	Video Capture: Frame #014 (epoll)
	Video Capture: Frame #015 (epoll)
	Video Capture: Frame #016 (epoll)
	Video Capture: Frame #017 (epoll)
	Video Capture: Frame #018 (epoll)
	Video Capture: Frame #019 (epoll)
	Video Capture: Frame #020 (epoll)
	Video Capture: Frame #021 (epoll)
	Video Capture: Frame #022 (epoll)
	Video Capture: Frame #023 (epoll)
	Video Capture: Frame #024 (epoll)
	Video Capture: Frame #025 (epoll)
	Video Capture: Frame #026 (epoll)
	Video Capture: Frame #027 (epoll)
	Video Capture: Frame #028 (epoll)
	Video Capture: Frame #029 (epoll)
	Video Capture: Frame #030 (epoll)
	Video Capture: Frame #031 (epoll)
	Video Capture: Frame #032 (epoll)
	Video Capture: Frame #033 (epoll)
	Video Capture: Frame #034 (epoll)
	Video Capture: Frame #035 (epoll)
	Video Capture: Frame #036 (epoll)
	Video Capture: Frame #037 (epoll)
	Video Capture: Frame #038 (epoll)
	Video Capture: Frame #039 (epoll)
	Video Capture: Frame #040 (epoll)
	Video Capture: Frame #041 (epoll)
	Video Capture: Frame #042 (epoll)
	Video Capture: Frame #043 (epoll)
	Video Capture: Frame #044 (epoll)
	Video Capture: Frame #045 (epoll)
	Video Capture: Frame #046 (epoll)
	Video Capture: Frame #047 (epoll)
	Video Capture: Frame #048 (epoll)
	Video Capture: Frame #049 (epoll)
	Video Capture: Frame #050 (epoll)
	Video Capture: Frame #051 (epoll)
	Video Capture: Frame #052 (epoll)
	Video Capture: Frame #053 (epoll)
	Video Capture: Frame #054 (epoll)
	Video Capture: Frame #055 (epoll)
	Video Capture: Frame #056 (epoll)
	Video Capture: Frame #057 (epoll)
	Video Capture: Frame #058 (epoll)
	Video Capture: Frame #059 (epoll)

	test MMAP (epoll, REQBUFS): OK

	Video Capture: Frame #000
	Video Capture: Frame #001
	Video Capture: Frame #002
	Video Capture: Frame #003
	Video Capture: Frame #004
	Video Capture: Frame #005
	Video Capture: Frame #006
	Video Capture: Frame #007
	Video Capture: Frame #008
	Video Capture: Frame #009
	Video Capture: Frame #010
	Video Capture: Frame #011
	Video Capture: Frame #012
	Video Capture: Frame #013
	Video Capture: Frame #014
	Video Capture: Frame #015
	Video Capture: Frame #016
	Video Capture: Frame #017
	Video Capture: Frame #018
	Video Capture: Frame #019
	Video Capture: Frame #020
	Video Capture: Frame #021
	Video Capture: Frame #022
	Video Capture: Frame #023
	Video Capture: Frame #024
	Video Capture: Frame #025
	Video Capture: Frame #026
	Video Capture: Frame #027
	Video Capture: Frame #028
	Video Capture: Frame #029
	Video Capture: Frame #030
	Video Capture: Frame #031
	Video Capture: Frame #032
	Video Capture: Frame #033
	Video Capture: Frame #034
	Video Capture: Frame #035
	Video Capture: Frame #036
	Video Capture: Frame #037
	Video Capture: Frame #038
	Video Capture: Frame #039
	Video Capture: Frame #040
	Video Capture: Frame #041
	Video Capture: Frame #042
	Video Capture: Frame #043
	Video Capture: Frame #044
	Video Capture: Frame #045
	Video Capture: Frame #046
	Video Capture: Frame #047
	Video Capture: Frame #048
	Video Capture: Frame #049
	Video Capture: Frame #050
	Video Capture: Frame #051
	Video Capture: Frame #052
	Video Capture: Frame #053
	Video Capture: Frame #054
	Video Capture: Frame #055
	Video Capture: Frame #056
	Video Capture: Frame #057
	Video Capture: Frame #058
	Video Capture: Frame #059

	test MMAP (no poll, CREATE_BUFS): OK

	Video Capture: Frame #000 (select)
	Video Capture: Frame #001 (select)
	Video Capture: Frame #002 (select)
	Video Capture: Frame #003 (select)
	Video Capture: Frame #004 (select)
	Video Capture: Frame #005 (select)
	Video Capture: Frame #006 (select)
	Video Capture: Frame #007 (select)
	Video Capture: Frame #008 (select)
	Video Capture: Frame #009 (select)
	Video Capture: Frame #010 (select)
	Video Capture: Frame #011 (select)
	Video Capture: Frame #012 (select)
	Video Capture: Frame #013 (select)
	Video Capture: Frame #014 (select)
	Video Capture: Frame #015 (select)
	Video Capture: Frame #016 (select)
	Video Capture: Frame #017 (select)
	Video Capture: Frame #018 (select)
	Video Capture: Frame #019 (select)
	Video Capture: Frame #020 (select)
	Video Capture: Frame #021 (select)
	Video Capture: Frame #022 (select)
	Video Capture: Frame #023 (select)
	Video Capture: Frame #024 (select)
	Video Capture: Frame #025 (select)
	Video Capture: Frame #026 (select)
	Video Capture: Frame #027 (select)
	Video Capture: Frame #028 (select)
	Video Capture: Frame #029 (select)
	Video Capture: Frame #030 (select)
	Video Capture: Frame #031 (select)
	Video Capture: Frame #032 (select)
	Video Capture: Frame #033 (select)
	Video Capture: Frame #034 (select)
	Video Capture: Frame #035 (select)
	Video Capture: Frame #036 (select)
	Video Capture: Frame #037 (select)
	Video Capture: Frame #038 (select)
	Video Capture: Frame #039 (select)
	Video Capture: Frame #040 (select)
	Video Capture: Frame #041 (select)
	Video Capture: Frame #042 (select)
	Video Capture: Frame #043 (select)
	Video Capture: Frame #044 (select)
	Video Capture: Frame #045 (select)
	Video Capture: Frame #046 (select)
	Video Capture: Frame #047 (select)
	Video Capture: Frame #048 (select)
	Video Capture: Frame #049 (select)
	Video Capture: Frame #050 (select)
	Video Capture: Frame #051 (select)
	Video Capture: Frame #052 (select)
	Video Capture: Frame #053 (select)
	Video Capture: Frame #054 (select)
	Video Capture: Frame #055 (select)
	Video Capture: Frame #056 (select)
	Video Capture: Frame #057 (select)
	Video Capture: Frame #058 (select)
	Video Capture: Frame #059 (select)

	test MMAP (select, CREATE_BUFS): OK

	Video Capture: Frame #000 (epoll)
	Video Capture: Frame #001 (epoll)
	Video Capture: Frame #002 (epoll)
	Video Capture: Frame #003 (epoll)
	Video Capture: Frame #004 (epoll)
	Video Capture: Frame #005 (epoll)
	Video Capture: Frame #006 (epoll)
	Video Capture: Frame #007 (epoll)
	Video Capture: Frame #008 (epoll)
	Video Capture: Frame #009 (epoll)
	Video Capture: Frame #010 (epoll)
	Video Capture: Frame #011 (epoll)
	Video Capture: Frame #012 (epoll)
	Video Capture: Frame #013 (epoll)
	Video Capture: Frame #014 (epoll)
	Video Capture: Frame #015 (epoll)
	Video Capture: Frame #016 (epoll)
	Video Capture: Frame #017 (epoll)
	Video Capture: Frame #018 (epoll)
	Video Capture: Frame #019 (epoll)
	Video Capture: Frame #020 (epoll)
	Video Capture: Frame #021 (epoll)
	Video Capture: Frame #022 (epoll)
	Video Capture: Frame #023 (epoll)
	Video Capture: Frame #024 (epoll)
	Video Capture: Frame #025 (epoll)
	Video Capture: Frame #026 (epoll)
	Video Capture: Frame #027 (epoll)
	Video Capture: Frame #028 (epoll)
	Video Capture: Frame #029 (epoll)
	Video Capture: Frame #030 (epoll)
	Video Capture: Frame #031 (epoll)
	Video Capture: Frame #032 (epoll)
	Video Capture: Frame #033 (epoll)
	Video Capture: Frame #034 (epoll)
	Video Capture: Frame #035 (epoll)
	Video Capture: Frame #036 (epoll)
	Video Capture: Frame #037 (epoll)
	Video Capture: Frame #038 (epoll)
	Video Capture: Frame #039 (epoll)
	Video Capture: Frame #040 (epoll)
	Video Capture: Frame #041 (epoll)
	Video Capture: Frame #042 (epoll)
	Video Capture: Frame #043 (epoll)
	Video Capture: Frame #044 (epoll)
	Video Capture: Frame #045 (epoll)
	Video Capture: Frame #046 (epoll)
	Video Capture: Frame #047 (epoll)
	Video Capture: Frame #048 (epoll)
	Video Capture: Frame #049 (epoll)
	Video Capture: Frame #050 (epoll)
	Video Capture: Frame #051 (epoll)
	Video Capture: Frame #052 (epoll)
	Video Capture: Frame #053 (epoll)
	Video Capture: Frame #054 (epoll)
	Video Capture: Frame #055 (epoll)
	Video Capture: Frame #056 (epoll)
	Video Capture: Frame #057 (epoll)
	Video Capture: Frame #058 (epoll)
	Video Capture: Frame #059 (epoll)

	test MMAP (epoll, CREATE_BUFS): OK
	test USERPTR (no poll): OK (Not Supported)
	test USERPTR (select): OK (Not Supported)
	test DMABUF (no poll): OK (Not Supported)
	test DMABUF (select): OK (Not Supported)

Total for virtio-media device /dev/video0: 59, Succeeded: 59, Failed: 0, Warnings: 0

---
Changes in v11:
- Initialize controls' size value to zero
  (https://lore.kernel.org/all/20260925080140.44696-1-nick@getfieldwork.ai)
- Framevec updated to work for multiple controls
- virtio_device_ready() is now called after early error paths
- Make g_input and g_output ioctls use _IOR version of cmd instead of _IOWR
- Fix behavior where poll does not report the CAPTURE queue readable after the LAST buffer
- Ensure event mutex is locked during probe
- Mmap returns EIO if the session error state is set
- Changed g_input and g_output ioctls to be _IOR instead of _IOWR to
  match the v4l2 specification and virtio-media virtual device
  implementation

Changes in v10:
- Rebased on top of v7.3-rc1
- Add missing padding in ``struct virtio_media_cmd_mmap``
- Add ``virtio_media_config`` to uapi header and use proper ``cread`` during init
- Remove redundant assignment of ``vfl_type``
- Fix tear down order of the video device and resources in
  ``virtio_media_remove()``
- Call ``virtio_device_ready()`` before starting device
- Move from ``devm`` to manual memory management to prevent potential use after
  free
- Detach unused buffers from the virtqueues during device remove
- Remove wait timeout during kick command
- Fix use after free in case of transport-level error
- Add additional validity check for scatterlist data buffer
- Ensure PFNs are not truncated
- Use dynamic ``shadow_buffer_size`` in ``scatterlist_builder`` instead of the
  ``VIRTIO_SHADOW_BUF_SIZE`` constant to guard against future modifications
- Fix case where exact fit into a shadow buffer was wrongly rejected
- Fail early if ``virtio_get_shm_region()`` fails
- Move guest allocation before host call in ``reqbufs`` and ``createbufs``
- Clean up host-side mmap if ``io_remap_pfn_range()`` fails
- Ensure command failure returns in ``ext_controls`` ioctls
- Replace array ``vmalloc`` allocations with ``vcalloc`` for overflow protection
- Add check in ``dqbuf`` ioctl if no buffer is in the queue in case multiple
  threads call ``VIDIOC_DQBUF``
- Change ``copy_from_user()``/``copy_to_user()`` failure return value from
  ``EINVAL`` to ``EFAULT``
- Ensure reserved fields are initialized to zero
- Ensure ``device_type`` from config area is valid
- Set ``done`` flag after ``resp_len`` to address a race in the condition check
  fast path
- Do not leave host session open if guest allocations fail
- Rename ``errno`` to ``error`` in ``virtio_media`` UAPI to prevent
  compilation errors in userspaces apps that include ``errno.h``
- Keep user pages pinned during ``ext_ctrls`` request

Changes in v9:
- Removed note from cover letter about the dependency on the VIRTIO_ID_MEDIA
  patch since this was merged.

Changes in v8:
- Fix usage of integer types in uapi
- Add uapi header test exemption due to depenency on currently exempt videodev2.h

Changes in v7:
- Removed USERPTR feature
- Updated Kconfig dependency to include little endian and 64bit platforms (not
  only ARM and x86)
- Fixed incorrect constant in vfl_dir detection
- Clarified that error codes returned by the host are positive integers

Changes in v6:
- Added missing "WITH Linux-syscall-note" for SPDX-License-Identifier in
  ``include/uapi/linux/virtio_media.h``
- Rebased on top of v7.2-rc1

Changes in v5:
- Add DMA buffer alignment and padding for commands, responses, and the event
  buffer
- Corrected styling of kernel-doc comments
- Removed the configurable ``driver_name`` module parameter
- Moved the protocol to ``include/uapi/linux/virtio_media.h``
- Link to v4: https://lore.kernel.org/all/20260622204343.1994418-1-briandaniels@google.com/

Changes in v4:
- Rebased on top of v7.1-rc1
- Replace usages of filep->private_data with file_to_v4l2_fh()
  throughout the driver
- Link to v3: https://lore.kernel.org/r/20250412-virtio-media-v3-1-97dc94c18398@gmail.com

Changes in v3:
- Rebased on top of v6.15-rc1 and removes obsolete control callbacks.
- Link to v2: https://lore.kernel.org/r/20250201-virtio-media-v2-1-ac840681452d@gmail.com

Changes in v2:
- Fixed kernel test robot and media CI warnings (ignored a few false
  positives).
- Changed in-driver email address to personal one since my Google one
  will soon become invalid.
- Link to v1: https://lore.kernel.org/r/20250123-virtio-media-v1-1-81e2549b86b9@gmail.com

Brian Daniels (5):
  media: virtio: Add core driver and session management
  media: virtio: Add V4L2 ioctl forwarding infrastructure
  media: virtio: Add extended controls support
  media: virtio: Add buffer streaming, event handling, and poll
  media: virtio: Add MMAP buffer mapping support

Nick Rogers (1):
  media: virtio: clear the size of legacy controls built on the stack

 MAINTAINERS                                |    8 +
 drivers/media/Kconfig                      |   13 +
 drivers/media/Makefile                     |    2 +
 drivers/media/virtio/Makefile              |    7 +
 drivers/media/virtio/scatterlist_builder.c |  596 +++++++++
 drivers/media/virtio/scatterlist_builder.h |  125 ++
 drivers/media/virtio/session.h             |  135 ++
 drivers/media/virtio/virtio_media.h        |   95 ++
 drivers/media/virtio/virtio_media_driver.c | 1071 +++++++++++++++
 drivers/media/virtio/virtio_media_ioctls.c | 1411 ++++++++++++++++++++
 include/uapi/linux/virtio_media.h          |  309 +++++
 usr/include/Makefile                       |    1 +
 12 files changed, 3773 insertions(+)
 create mode 100644 drivers/media/virtio/Makefile
 create mode 100644 drivers/media/virtio/scatterlist_builder.c
 create mode 100644 drivers/media/virtio/scatterlist_builder.h
 create mode 100644 drivers/media/virtio/session.h
 create mode 100644 drivers/media/virtio/virtio_media.h
 create mode 100644 drivers/media/virtio/virtio_media_driver.c
 create mode 100644 drivers/media/virtio/virtio_media_ioctls.c
 create mode 100644 include/uapi/linux/virtio_media.h


base-commit: d7e7bca7169873b46e857c025c10f3336c1258d8
-- 
2.56.1.750.gf70dc682cf-goog


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

* [PATCH v11 1/6] media: virtio: Add core driver and session management
  2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
@ 2026-11-20 21:59 ` Brian Daniels
  2026-11-20 22:19   ` sashiko-bot
  2026-11-20 21:59 ` [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure Brian Daniels
                   ` (4 subsequent siblings)
  5 siblings, 1 reply; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Brian Daniels

From: Alexandre Courbot <gnurou@gmail.com>

Add the initial virtio-media driver core, build system integration,
MAINTAINERS entry, and V4L2 session lifecycle management.

The driver binds to VIRTIO_ID_MEDIA devices, reads device capabilities
and device node type from the virtio configuration space, sets up the
command virtqueue for synchronous host requests, and registers the V4L2
and video devices. Opening and closing the video device creates and
destroys a host-backed session via VIRTIO_MEDIA_CMD_OPEN and
VIRTIO_MEDIA_CMD_CLOSE.

Protocol structures in the UAPI header include explicit __reserved
fields solely to guarantee 64-bit alignment rather than for future
protocol expansion. Because the UAPI header includes linux/videodev2.h,
which is currently excluded from standalone UAPI header compilation
checks (CONFIG_UAPI_HEADER_TEST=y), add linux/virtio_media.h to the same
exception list in usr/include/Makefile.

Signed-off-by: Alexandre Courbot <gnurou@gmail.com>
Assisted-by: LLM
Co-developed-by: Brian Daniels <briandaniels@google.com>
Signed-off-by: Brian Daniels <briandaniels@google.com>
---
 MAINTAINERS                                |   8 +
 drivers/media/Kconfig                      |  13 +
 drivers/media/Makefile                     |   2 +
 drivers/media/virtio/Makefile              |   7 +
 drivers/media/virtio/session.h             |  58 +++
 drivers/media/virtio/virtio_media.h        |  70 +++
 drivers/media/virtio/virtio_media_driver.c | 504 +++++++++++++++++++++
 include/uapi/linux/virtio_media.h          | 118 +++++
 usr/include/Makefile                       |   1 +
 9 files changed, 781 insertions(+)
 create mode 100644 drivers/media/virtio/Makefile
 create mode 100644 drivers/media/virtio/session.h
 create mode 100644 drivers/media/virtio/virtio_media.h
 create mode 100644 drivers/media/virtio/virtio_media_driver.c
 create mode 100644 include/uapi/linux/virtio_media.h

diff --git a/MAINTAINERS b/MAINTAINERS
index 760791e36..30c565537 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -28973,6 +28973,7 @@ F:	Documentation/devicetree/bindings/virtio/
 F:	Documentation/driver-api/virtio/
 F:	drivers/block/virtio_blk.c
 F:	drivers/crypto/virtio/
+F:	drivers/media/virtio/
 F:	drivers/vdpa/
 F:	drivers/virtio/
 F:	include/linux/vdpa.h
@@ -29085,6 +29086,13 @@ S:	Maintained
 F:	drivers/iommu/virtio-iommu.c
 F:	include/uapi/linux/virtio_iommu.h
 
+VIRTIO MEDIA DRIVER
+M:	Brian Daniels <briandaniels@google.com>
+L:	linux-media@vger.kernel.org
+S:	Maintained
+F:	drivers/media/virtio/
+F:	include/uapi/linux/virtio_media.h
+
 VIRTIO MEM DRIVER
 M:	David Hildenbrand <david@kernel.org>
 L:	virtualization@lists.linux.dev
diff --git a/drivers/media/Kconfig b/drivers/media/Kconfig
index 6abc9302c..ce7d088e7 100644
--- a/drivers/media/Kconfig
+++ b/drivers/media/Kconfig
@@ -136,6 +136,19 @@ config MEDIA_PLATFORM_SUPPORT
 
 	  Say Y when you want to be able to see such devices.
 
+config MEDIA_VIRTIO
+	tristate "Virtio-media Driver"
+	depends on VIRTIO && VIDEO_DEV && 64BIT && (X86 || CPU_LITTLE_ENDIAN)
+	select VIDEOBUF2_CORE
+	select VIDEOBUF2_MEMOPS
+	help
+	  Enables the virtio-media driver.
+
+	  This driver is used to virtualize media devices such as cameras or
+	  decoders from a host into a guest using the V4L2 protocol.
+
+	  If unsure, say N.
+
 config MEDIA_TEST_SUPPORT
 	bool
 	prompt "Test drivers" if MEDIA_SUPPORT_FILTER
diff --git a/drivers/media/Makefile b/drivers/media/Makefile
index 20fac24e4..357e786cc 100644
--- a/drivers/media/Makefile
+++ b/drivers/media/Makefile
@@ -23,6 +23,8 @@ obj-$(CONFIG_DVB_CORE) += dvb-core/
 # There are both core and drivers at RC subtree - merge before drivers
 obj-y += rc/
 
+obj-$(CONFIG_MEDIA_VIRTIO) += virtio/
+
 obj-$(CONFIG_CEC_CORE) += cec/
 
 #
diff --git a/drivers/media/virtio/Makefile b/drivers/media/virtio/Makefile
new file mode 100644
index 000000000..09d9834da
--- /dev/null
+++ b/drivers/media/virtio/Makefile
@@ -0,0 +1,7 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for the virtio-media device driver.
+
+virtio-media-objs := virtio_media_driver.o
+
+obj-$(CONFIG_MEDIA_VIRTIO) += virtio-media.o
diff --git a/drivers/media/virtio/session.h b/drivers/media/virtio/session.h
new file mode 100644
index 000000000..4ade7fb9c
--- /dev/null
+++ b/drivers/media/virtio/session.h
@@ -0,0 +1,58 @@
+/* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0+ */
+
+/*
+ * Definitions of virtio-media session related structures.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#ifndef __VIRTIO_MEDIA_SESSION_H
+#define __VIRTIO_MEDIA_SESSION_H
+
+#include <media/v4l2-fh.h>
+
+#include "uapi/linux/virtio_media.h"
+
+/**
+ * struct virtio_media_session - A session on a virtio_media device.
+ * @fh: file handler for the session.
+ * @file: file pointer associated with the session's file handler.
+ * @id: session ID used to communicate with the device.
+ * @cmd: union of session-level commands. A session can have one command
+ *       currently running.
+ * @list: link into the list of sessions for the device.
+ */
+struct virtio_media_session {
+	struct v4l2_fh fh;
+	struct file *file;
+	u32 id;
+
+	__dma_from_device_group_begin();
+	union {
+		struct virtio_media_cmd_close close;
+	} cmd;
+	__dma_from_device_group_end();
+
+	struct list_head list;
+};
+
+static inline struct virtio_media_session *fh_to_session(struct v4l2_fh *fh)
+{
+	return container_of(fh, struct virtio_media_session, fh);
+}
+
+static inline void
+virtio_media_session_fh_add(struct virtio_media_session *session,
+			    struct file *file)
+{
+	v4l2_fh_add(&session->fh, file);
+	session->file = file;
+}
+
+static inline void
+virtio_media_session_fh_del(struct virtio_media_session *session)
+{
+	v4l2_fh_del(&session->fh, session->file);
+}
+
+#endif // __VIRTIO_MEDIA_SESSION_H
diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/virtio_media.h
new file mode 100644
index 000000000..68299377a
--- /dev/null
+++ b/drivers/media/virtio/virtio_media.h
@@ -0,0 +1,70 @@
+/* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0+ */
+
+/*
+ * Virtio-media structures & functions declarations.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#ifndef __VIRTIO_MEDIA_H
+#define __VIRTIO_MEDIA_H
+
+#include <linux/virtio_config.h>
+#include <media/v4l2-device.h>
+
+#include "uapi/linux/virtio_media.h"
+
+#define VIRTIO_MEDIA_DEFAULT_DRIVER_NAME "virtio-media"
+
+/**
+ * struct virtio_media - Virtio-media device.
+ * @v4l2_dev: v4l2_device for the media device.
+ * @video_dev: video_device for the media device.
+ * @virtio_dev: virtio device for the media device.
+ * @commandq: virtio command queue.
+ * @sessions: list of active sessions on the device.
+ * @sessions_lock: protects @sessions and &struct virtio_media_session.list.
+ * @cmd: union of device-level commands. Session commands are handled by
+ *       &struct virtio_media_session.
+ * @resp: union of responses to device-level commands. Session responses are
+ *        handled by &struct virtio_media_session.
+ * @vlock: serializes access to the command queue.
+ * @wq: waitqueue for host responses on the command queue.
+ */
+struct virtio_media {
+	struct v4l2_device v4l2_dev;
+	struct video_device video_dev;
+
+	struct virtio_device *virtio_dev;
+	struct virtqueue *commandq;
+
+	struct list_head sessions;
+	struct mutex sessions_lock; /* protects sessions list */
+
+	__dma_from_device_group_begin();
+	union {
+		struct virtio_media_cmd_open open;
+	} cmd;
+
+	union {
+		struct virtio_media_resp_open open;
+	} resp;
+	__dma_from_device_group_end();
+
+	struct mutex vlock; /* serializes command queue access */
+	wait_queue_head_t wq;
+};
+
+static inline struct virtio_media *
+to_virtio_media(struct video_device *video_dev)
+{
+	return container_of(video_dev, struct virtio_media, video_dev);
+}
+
+/* virtio_media_driver.c */
+
+int virtio_media_send_command(struct virtio_media *vv, struct scatterlist **sgs,
+			      const size_t out_sgs, const size_t in_sgs,
+			      size_t minimum_resp_len, size_t *resp_len);
+#endif // __VIRTIO_MEDIA_H
+
diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
new file mode 100644
index 000000000..39c5a38d2
--- /dev/null
+++ b/drivers/media/virtio/virtio_media_driver.c
@@ -0,0 +1,504 @@
+// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0+
+
+/*
+ * Virtio-media driver.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#include <linux/device.h>
+#include <linux/dev_printk.h>
+#include <linux/mutex.h>
+#include <linux/types.h>
+#include <linux/module.h>
+#include <linux/virtio.h>
+#include <linux/virtio_config.h>
+#include <linux/virtio_ids.h>
+#include <linux/slab.h>
+#include <linux/scatterlist.h>
+
+#include <media/v4l2-dev.h>
+#include <media/v4l2-device.h>
+#include <media/v4l2-fh.h>
+
+#include "uapi/linux/virtio_media.h"
+#include "session.h"
+#include "virtio_media.h"
+
+/**
+ * virtio_media_session_alloc() - Allocate a new session.
+ * @vv: virtio-media device the session belongs to.
+ * @file: file associated with the session.
+ *
+ * The caller must initialize the ``id`` field before calling
+ * virtio_media_session_add().
+ */
+static struct virtio_media_session *
+virtio_media_session_alloc(struct virtio_media *vv, struct file *file)
+{
+	struct virtio_media_session *session;
+
+	session = kzalloc_obj(*session, GFP_KERNEL);
+	if (!session)
+		return ERR_PTR(-ENOMEM);
+
+	// The caller is expected to set the ID once the host assigns a value.
+	session->id = 0;
+
+	INIT_LIST_HEAD(&session->list);
+	v4l2_fh_init(&session->fh, &vv->video_dev);
+	virtio_media_session_fh_add(session, file);
+
+	return session;
+}
+
+/**
+ * virtio_media_session_add() - Add a session to a device.
+ * @vv: virtio-media device the session belongs to.
+ * @session: session to add to the device.
+ */
+static void virtio_media_session_add(struct virtio_media *vv,
+				     struct virtio_media_session *session)
+{
+	mutex_lock(&vv->sessions_lock);
+	list_add_tail(&session->list, &vv->sessions);
+	mutex_unlock(&vv->sessions_lock);
+}
+
+/**
+ * virtio_media_session_free() - Free all resources of a session.
+ * @session: session to destroy.
+ *
+ * All the resources of @session, as well as the backing memory of @session
+ * itself, are freed.
+ */
+static void virtio_media_session_free(struct virtio_media_session *session)
+{
+	virtio_media_session_fh_del(session);
+	v4l2_fh_exit(&session->fh);
+
+	kfree(session);
+}
+
+/**
+ * virtio_media_session_remove() - Remove a session from the device.
+ * @vv: virtio-media device the session belongs to.
+ * @session: session to remove.
+ *
+ * This only removes the session from the device. To free it, call
+ * virtio_media_session_free().
+ */
+static void virtio_media_session_remove(struct virtio_media *vv,
+					struct virtio_media_session *session)
+{
+	mutex_lock(&vv->sessions_lock);
+	list_del(&session->list);
+	mutex_unlock(&vv->sessions_lock);
+}
+
+/**
+ * virtio_media_session_close() - Close a session.
+ * @vv: virtio-media device the session belongs to.
+ * @session: session to close.
+ *
+ * This sends the ``VIRTIO_MEDIA_CMD_CLOSE`` command to the device. If @session
+ * is no longer used, it should be first removed by calling
+ * virtio_media_session_remove(), then freed by calling
+ * virtio_media_session_free().
+ */
+static int virtio_media_session_close(struct virtio_media *vv,
+				      struct virtio_media_session *session)
+{
+	struct virtio_media_cmd_close *cmd_close = &session->cmd.close;
+	struct scatterlist cmd_sg = {};
+	struct scatterlist *sgs[1] = { &cmd_sg };
+	int ret;
+
+	mutex_lock(&vv->vlock);
+
+	cmd_close->hdr.cmd = VIRTIO_MEDIA_CMD_CLOSE;
+	cmd_close->hdr.__reserved = 0;
+	cmd_close->session_id = session->id;
+	cmd_close->__reserved = 0;
+
+	sg_set_buf(&cmd_sg, cmd_close, sizeof(*cmd_close));
+	sg_mark_end(&cmd_sg);
+
+	ret = virtio_media_send_command(vv, sgs, 1, 0, 0, NULL);
+	mutex_unlock(&vv->vlock);
+	if (ret < 0)
+		return ret;
+
+	return 0;
+}
+
+/**
+ * struct virtio_media_cmd_callback_param - Callback parameters to the virtio
+ *                                          command queue.
+ * @vv: virtio-media device in use.
+ * @done: flag to be switched once the command is completed.
+ * @resp_len: length of the received response from the command. Only valid
+ *            after @done flag has switched to %true.
+ */
+struct virtio_media_cmd_callback_param {
+	struct virtio_media *vv;
+	bool done;
+	size_t resp_len;
+};
+
+/**
+ * commandq_callback() - Callback for the command queue.
+ * @queue: command virtqueue.
+ *
+ * This just wakes up the thread that was waiting on the command to complete.
+ */
+static void commandq_callback(struct virtqueue *queue)
+{
+	unsigned int len;
+	struct virtio_media_cmd_callback_param *param;
+
+process_bufs:
+	while ((param = virtqueue_get_buf(queue, &len))) {
+		param->resp_len = len;
+		param->done = true;
+		wake_up(&param->vv->wq);
+	}
+
+	if (!virtqueue_enable_cb(queue)) {
+		virtqueue_disable_cb(queue);
+		goto process_bufs;
+	}
+}
+
+/**
+ * virtio_media_kick_command() - send a command to the commandq.
+ * @vv: virtio-media device in use.
+ * @sgs: descriptor chain to send.
+ * @out_sgs: number of device-readable descriptors in @sgs.
+ * @in_sgs: number of device-writable descriptors in @sgs.
+ * @resp_len: output parameter. Upon success, contains the size of the response
+ *            in bytes.
+ */
+static int virtio_media_kick_command(struct virtio_media *vv,
+				     struct scatterlist **sgs,
+				     const size_t out_sgs, const size_t in_sgs,
+				     size_t *resp_len)
+{
+	struct virtio_media_cmd_callback_param cb_param = {
+		.vv = vv,
+		.done = false,
+		.resp_len = 0,
+	};
+	struct virtio_media_resp_header *resp_header;
+	int ret = virtqueue_add_sgs(vv->commandq, sgs, out_sgs, in_sgs,
+		  &cb_param, GFP_ATOMIC);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to add sgs to command virtqueue\n");
+		return ret;
+	}
+
+	if (!virtqueue_kick(vv->commandq)) {
+		v4l2_err(&vv->v4l2_dev, "failed to kick command virtqueue\n");
+		return -EINVAL;
+	}
+
+	/* Wait for the response. */
+	wait_event(vv->wq, cb_param.done);
+
+	if (resp_len)
+		*resp_len = cb_param.resp_len;
+
+	if (in_sgs > 0) {
+		/*
+		 * If we expect a response, make sure we have at least a
+		 * response header - anything shorter is invalid.
+		 */
+		if (cb_param.resp_len < sizeof(*resp_header)) {
+			v4l2_err(&vv->v4l2_dev,
+				 "received response header is too short\n");
+			return -EINVAL;
+		}
+
+		resp_header = sg_virt(sgs[out_sgs]);
+		if (resp_header->status)
+			/* Host returns a positive error code. */
+			return -resp_header->status;
+	}
+
+	return 0;
+}
+
+/**
+ * virtio_media_send_command() - Send a command to the device and wait for its
+ * response.
+ * @vv: virtio-media device in use.
+ * @sgs: descriptor chain to send.
+ * @out_sgs: number of device-readable descriptors in @sgs.
+ * @in_sgs: number of device-writable descriptors in @sgs.
+ * @minimum_resp_len: minimum length of the response expected by the caller
+ *                    when the command is successful. Anything shorter than
+ *                    that will result in %-EINVAL being returned.
+ * @resp_len: output parameter. Upon success, contains the size of the response
+ *            in bytes.
+ */
+int virtio_media_send_command(struct virtio_media *vv, struct scatterlist **sgs,
+			      const size_t out_sgs, const size_t in_sgs,
+			      size_t minimum_resp_len, size_t *resp_len)
+{
+	size_t local_resp_len = resp_len ? *resp_len : 0;
+	int ret = virtio_media_kick_command(vv, sgs, out_sgs, in_sgs,
+					    &local_resp_len);
+	if (resp_len)
+		*resp_len = local_resp_len;
+
+	/*
+	 * If the host could not process the command, there is no valid
+	 * response.
+	 */
+	if (ret < 0)
+		return ret;
+
+	/* Make sure the host wrote a complete reply. */
+	if (local_resp_len < minimum_resp_len) {
+		v4l2_err(&vv->v4l2_dev,
+			 "received response is too short: received %zu, expected at least %zu\n",
+			 local_resp_len, minimum_resp_len);
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+/**
+ * virtio_media_device_open() - Create a new session from an opened file.
+ * @file: opened file for the session.
+ */
+static int virtio_media_device_open(struct file *file)
+{
+	struct video_device *video_dev = video_devdata(file);
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_cmd_open *cmd_open = &vv->cmd.open;
+	struct virtio_media_resp_open *resp_open = &vv->resp.open;
+	struct scatterlist cmd_sg = {}, resp_sg = {};
+	struct scatterlist *sgs[2] = { &cmd_sg, &resp_sg };
+	struct virtio_media_session *session;
+	int ret;
+
+	session = virtio_media_session_alloc(vv, file);
+	if (IS_ERR(session))
+		return PTR_ERR(session);
+
+	mutex_lock(&vv->vlock);
+
+	sg_set_buf(&cmd_sg, cmd_open, sizeof(*cmd_open));
+	sg_mark_end(&cmd_sg);
+
+	sg_set_buf(&resp_sg, resp_open, sizeof(*resp_open));
+	sg_mark_end(&resp_sg);
+
+	cmd_open->hdr.cmd = VIRTIO_MEDIA_CMD_OPEN;
+	cmd_open->hdr.__reserved = 0;
+	ret = virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_open),
+					NULL);
+	session->id = resp_open->session_id;
+
+	mutex_unlock(&vv->vlock);
+
+	if (ret < 0) {
+		virtio_media_session_free(session);
+		return ret;
+	}
+
+	virtio_media_session_add(vv, session);
+	file->private_data = &session->fh;
+
+	return 0;
+}
+
+/**
+ * virtio_media_device_close() - Close a previously opened session.
+ * @file: file of the session to close.
+ *
+ * This sends the ``VIRTIO_MEDIA_CMD_CLOSE`` command to the device, closes the
+ * session on the driver side, and frees the session.
+ */
+static int virtio_media_device_close(struct file *file)
+{
+	struct video_device *video_dev = video_devdata(file);
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session =
+		fh_to_session(file->private_data);
+
+	int ret = virtio_media_session_close(vv, session);
+
+	virtio_media_session_remove(vv, session);
+	virtio_media_session_free(session);
+
+	return ret;
+}
+
+static const struct v4l2_file_operations virtio_media_fops = {
+	.owner = THIS_MODULE,
+	.open = virtio_media_device_open,
+	.release = virtio_media_device_close,
+};
+
+static void virtio_media_release(struct v4l2_device *v4l2_dev)
+{
+	struct virtio_media *vv =
+		container_of(v4l2_dev, struct virtio_media, v4l2_dev);
+
+	v4l2_device_unregister(&vv->v4l2_dev);
+	kfree(vv);
+}
+
+static int virtio_media_probe(struct virtio_device *virtio_dev)
+{
+	struct device *dev = &virtio_dev->dev;
+	struct virtqueue *vqs[1];
+	static struct virtqueue_info vq_info[1] = {
+		{
+			.name = "command",
+			.callback = commandq_callback,
+		},
+	};
+	struct virtio_media *vv;
+	struct video_device *vd;
+	int ret;
+
+	vv = kzalloc_obj(struct virtio_media);
+	if (!vv)
+		return -ENOMEM;
+
+	INIT_LIST_HEAD(&vv->sessions);
+	mutex_init(&vv->sessions_lock);
+	mutex_init(&vv->vlock);
+
+	vv->virtio_dev = virtio_dev;
+	virtio_dev->priv = vv;
+
+	init_waitqueue_head(&vv->wq);
+
+	ret = v4l2_device_register(dev, &vv->v4l2_dev);
+	if (ret)
+		goto err_free_virtio_media;
+
+	vv->v4l2_dev.release = virtio_media_release;
+
+	ret = virtio_find_vqs(virtio_dev, 1, vqs, vq_info, NULL);
+	if (ret)
+		goto err_v4l2_device_unregister;
+
+	vv->commandq = vqs[0];
+
+	vd = &vv->video_dev;
+	vd->v4l2_dev = &vv->v4l2_dev;
+	vd->fops = &virtio_media_fops;
+	vd->release = video_device_release_empty;
+	strscpy(vd->name, "virtio-media", sizeof(vd->name));
+
+	video_set_drvdata(vd, vv);
+
+	virtio_cread_le(virtio_dev, struct virtio_media_config, device_caps,
+			&vd->device_caps);
+	if (vd->device_caps & (V4L2_CAP_VIDEO_M2M | V4L2_CAP_VIDEO_M2M_MPLANE))
+		vd->vfl_dir = VFL_DIR_M2M;
+	else if (vd->device_caps &
+		 (V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OUTPUT_MPLANE))
+		vd->vfl_dir = VFL_DIR_TX;
+	else
+		vd->vfl_dir = VFL_DIR_RX;
+
+	__u32 device_type;
+
+	virtio_cread_le(virtio_dev, struct virtio_media_config, device_type,
+			&device_type);
+	if (device_type >= VFL_TYPE_MAX) {
+		dev_err(&virtio_dev->dev, "Invalid device_type: %u",
+			device_type);
+		ret = -EINVAL;
+		goto err_del_vqs;
+	}
+
+	virtio_device_ready(virtio_dev);
+
+	ret = video_register_device(vd, device_type, -1);
+	if (ret)
+		goto err_del_vqs;
+
+	return 0;
+
+err_del_vqs:
+	virtio_reset_device(virtio_dev);
+	virtio_dev->config->del_vqs(virtio_dev);
+err_v4l2_device_unregister:
+	v4l2_device_unregister(&vv->v4l2_dev);
+err_free_virtio_media:
+	kfree(vv);
+	return ret;
+}
+
+static void virtio_media_remove(struct virtio_device *virtio_dev)
+{
+	struct virtio_media *vv = virtio_dev->priv;
+	struct list_head *p, *n;
+
+	/* Remove the video device to stop accessing the commandq virtqueue */
+	video_unregister_device(&vv->video_dev);
+
+	/*
+	 * Acquire vlock to ensure no concurrent accesses to the commandq
+	 * virtqueue
+	 */
+	mutex_lock(&vv->vlock);
+
+	/* Stop all virtqueue callbacks */
+	virtio_reset_device(virtio_dev);
+
+	/*
+	 * Only detach the unused buffers to allow internal virtqueue clean up.
+	 * The actual buffers are freed in virtio_media_release()
+	 */
+	while (virtqueue_detach_unused_buf(vv->commandq))
+		;
+
+	/* Delete the virtqueues */
+	virtio_dev->config->del_vqs(virtio_dev);
+
+	mutex_unlock(&vv->vlock);
+
+	list_for_each_safe(p, n, &vv->sessions) {
+		struct virtio_media_session *s =
+			list_entry(p, struct virtio_media_session, list);
+
+		virtio_media_session_remove(vv, s);
+		virtio_media_session_free(s);
+	}
+
+	v4l2_device_put(&vv->v4l2_dev);
+}
+
+static struct virtio_device_id id_table[] = {
+	{ VIRTIO_ID_MEDIA, VIRTIO_DEV_ANY_ID },
+	{ 0 },
+};
+
+static unsigned int features[] = {};
+
+static struct virtio_driver virtio_media_driver = {
+	.feature_table = features,
+	.feature_table_size = ARRAY_SIZE(features),
+	.driver.name = VIRTIO_MEDIA_DEFAULT_DRIVER_NAME,
+	.driver.owner = THIS_MODULE,
+	.id_table = id_table,
+	.probe = virtio_media_probe,
+	.remove = virtio_media_remove,
+};
+
+module_virtio_driver(virtio_media_driver);
+
+MODULE_DEVICE_TABLE(virtio, id_table);
+MODULE_DESCRIPTION("virtio media driver");
+MODULE_AUTHOR("Alexandre Courbot <gnurou@gmail.com>");
+MODULE_LICENSE("Dual BSD/GPL");
diff --git a/include/uapi/linux/virtio_media.h b/include/uapi/linux/virtio_media.h
new file mode 100644
index 000000000..ad05d7421
--- /dev/null
+++ b/include/uapi/linux/virtio_media.h
@@ -0,0 +1,118 @@
+/* SPDX-License-Identifier: ((GPL-2.0+ WITH Linux-syscall-note) OR BSD-3-Clause) */
+
+/*
+ * Definitions of virtio-media protocol structures.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#ifndef _UAPI__LINUX_VIRTIO_MEDIA_H
+#define _UAPI__LINUX_VIRTIO_MEDIA_H
+
+#include <linux/types.h>
+#include <linux/videodev2.h>
+
+/*
+ * Virtio protocol definition.
+ */
+
+/**
+ * struct virtio_media_config - Video device configuration space.
+ * @device_caps: flags representing the device capabilities as used in &struct
+ *               v4l2_capability. It corresponds with the device_caps field in
+ *               the &struct video_device
+ * @ device_type: informs the driver of the type of the video device. It
+ *                corresponds to with the ``vfl_devnod_type`` field of the
+ *                device.
+ * @card: name of the device, a NUL-terminated UTF-8 string. It corresponds
+ *        with the card field of the struct v4l2_capability. If all the
+ *        characters of the field are used, it does not need to be
+ *        NUL-terminated.
+ */
+struct virtio_media_config {
+	__le32 device_caps;
+	__le32 device_type;
+	__u8 card[32];
+};
+
+/**
+ * struct virtio_media_cmd_header - Header for all virtio-media commands.
+ * @cmd: one of VIRTIO_MEDIA_CMD_*.
+ * @__reserved: must be set to zero by the driver.
+ *
+ * This header starts all commands from the driver to the device on the
+ * commandq.
+ */
+struct virtio_media_cmd_header {
+	__le32 cmd;
+	__le32 __reserved;
+};
+
+/**
+ * struct virtio_media_resp_header - Header for all virtio-media responses.
+ * @status: 0 if the command was successful, or one of the standard Linux error
+ *          codes as a positive integer.
+ * @__reserved: must be set to zero by the device.
+ *
+ * This header starts all responses from the device to the driver on the
+ * commandq.
+ */
+struct virtio_media_resp_header {
+	__le32 status;
+	__le32 __reserved;
+};
+
+/**
+ * VIRTIO_MEDIA_CMD_OPEN - Command for creating a new session.
+ *
+ * This is the equivalent of calling ``open`` on a V4L2 device node. Upon
+ * success, a session id is returned which can be used to perform other
+ * commands on the session, notably ioctls.
+ */
+#define VIRTIO_MEDIA_CMD_OPEN 1
+
+/**
+ * struct virtio_media_cmd_open - Driver command for VIRTIO_MEDIA_CMD_OPEN.
+ * @hdr: header with cmd member set to VIRTIO_MEDIA_CMD_OPEN.
+ */
+struct virtio_media_cmd_open {
+	struct virtio_media_cmd_header hdr;
+};
+
+/**
+ * struct virtio_media_resp_open - Device response for VIRTIO_MEDIA_CMD_OPEN.
+ * @hdr: header containing the status of the command.
+ * @session_id: if &struct virtio_media_resp_header.status == 0, contains the
+ *              id of the newly created session.
+ * @__reserved: must be set to zero by the device.
+ */
+struct virtio_media_resp_open {
+	struct virtio_media_resp_header hdr;
+	__le32 session_id;
+	__le32 __reserved;
+};
+
+/**
+ * VIRTIO_MEDIA_CMD_CLOSE - Command for closing an active session.
+ *
+ * This is the equivalent of calling ``close`` on a previously opened V4L2
+ * session. All resources associated with this session will be freed and the
+ * session ID shall not be used again after queueing this command.
+ *
+ * This command does not require a response from the device.
+ */
+#define VIRTIO_MEDIA_CMD_CLOSE 2
+
+/**
+ * struct virtio_media_cmd_close - Driver command for VIRTIO_MEDIA_CMD_CLOSE.
+ * @hdr: header with cmd member set to VIRTIO_MEDIA_CMD_CLOSE.
+ * @session_id: id of the session to close.
+ * @__reserved: must be set to zero by the driver.
+ */
+struct virtio_media_cmd_close {
+	struct virtio_media_cmd_header hdr;
+	__le32 session_id;
+	__le32 __reserved;
+};
+
+#endif // _UAPI__LINUX_VIRTIO_MEDIA_H
diff --git a/usr/include/Makefile b/usr/include/Makefile
index ee69dd9d9..df106b5d9 100644
--- a/usr/include/Makefile
+++ b/usr/include/Makefile
@@ -37,6 +37,7 @@ no-header-test += linux/usb/audio.h
 no-header-test += linux/v4l2-mediabus.h
 no-header-test += linux/v4l2-subdev.h
 no-header-test += linux/videodev2.h
+no-header-test += linux/virtio_media.h
 no-header-test += linux/vm_sockets.h
 no-header-test += sound/asequencer.h
 no-header-test += sound/asoc.h
-- 
2.56.1.750.gf70dc682cf-goog


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

* [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure
  2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
  2026-11-20 21:59 ` [PATCH v11 1/6] media: virtio: Add core driver and session management Brian Daniels
@ 2026-11-20 21:59 ` Brian Daniels
  2026-11-20 22:25   ` sashiko-bot
  2026-11-20 21:59 ` [PATCH v11 3/6] media: virtio: Add extended controls support Brian Daniels
                   ` (3 subsequent siblings)
  5 siblings, 1 reply; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Brian Daniels

From: Alexandre Courbot <gnurou@gmail.com>

Introduce the scatterlist builder and synchronous V4L2 ioctl forwarding
via VIRTIO_MEDIA_CMD_IOCTL.

The scatterlist builder constructs virtio descriptor chains for ioctl
commands and responses, mapping 1:1 kernel memory and vmalloc buffers
directly into scatterlists when possible while falling back to a
per-session shadow buffer otherwise.

Use this infrastructure to implement VIDIOC_QUERYCAP from the virtio
configuration space along with fixed-size read, write, and read-write
V4L2 ioctls covering format negotiation, frame sizes and intervals,
control and menu queries, inputs and outputs, audio, selection, video
standards, tuners, and DV timings.

Signed-off-by: Alexandre Courbot <gnurou@gmail.com>
Assisted-by: LLM
Co-developed-by: Brian Daniels <briandaniels@google.com>
Signed-off-by: Brian Daniels <briandaniels@google.com>
---
 drivers/media/virtio/Makefile              |   2 +-
 drivers/media/virtio/scatterlist_builder.c | 222 ++++++++
 drivers/media/virtio/scatterlist_builder.h |  90 +++
 drivers/media/virtio/session.h             |  28 +-
 drivers/media/virtio/virtio_media.h        |   9 +
 drivers/media/virtio/virtio_media_driver.c |  24 +-
 drivers/media/virtio/virtio_media_ioctls.c | 606 +++++++++++++++++++++
 include/uapi/linux/virtio_media.h          |  43 ++
 8 files changed, 1020 insertions(+), 4 deletions(-)
 create mode 100644 drivers/media/virtio/scatterlist_builder.c
 create mode 100644 drivers/media/virtio/scatterlist_builder.h
 create mode 100644 drivers/media/virtio/virtio_media_ioctls.c

diff --git a/drivers/media/virtio/Makefile b/drivers/media/virtio/Makefile
index 09d9834da..f1bc8a3ce 100644
--- a/drivers/media/virtio/Makefile
+++ b/drivers/media/virtio/Makefile
@@ -2,6 +2,6 @@
 #
 # Makefile for the virtio-media device driver.
 
-virtio-media-objs := virtio_media_driver.o
+virtio-media-objs := scatterlist_builder.o virtio_media_ioctls.o virtio_media_driver.o
 
 obj-$(CONFIG_MEDIA_VIRTIO) += virtio-media.o
diff --git a/drivers/media/virtio/scatterlist_builder.c b/drivers/media/virtio/scatterlist_builder.c
new file mode 100644
index 000000000..ae8ffee82
--- /dev/null
+++ b/drivers/media/virtio/scatterlist_builder.c
@@ -0,0 +1,222 @@
+// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0+
+
+/*
+ * Scatterlist builder helpers for virtio-media.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#include <linux/moduleparam.h>
+#include <linux/scatterlist.h>
+#include <linux/videodev2.h>
+#include <media/videobuf2-memops.h>
+
+#include "uapi/linux/virtio_media.h"
+#include "scatterlist_builder.h"
+#include "session.h"
+
+/*
+ * If set to %true, then the driver will always copy the data passed to the
+ * host into the shadow buffer (instead of trying to map the source memory into
+ * the SG table directly when possible).
+ */
+static bool always_use_shadow_buffer;
+module_param(always_use_shadow_buffer, bool, 0660);
+
+/* Convert a V4L2 IOCTL into the IOCTL code we can give to the host */
+#define VIRTIO_MEDIA_IOCTL_CODE(IOCTL) (((IOCTL) >> _IOC_NRSHIFT) & _IOC_NRMASK)
+
+/**
+ * scatterlist_builder_add_descriptor() - Add a descriptor to the chain.
+ * @builder: builder to use.
+ * @desc_index: index of the descriptor to add.
+ *
+ * Returns %-ENOSPC if @builder->sgs is already full.
+ */
+int scatterlist_builder_add_descriptor(struct scatterlist_builder *builder,
+				       size_t desc_index)
+{
+	if (builder->cur_sg >= builder->num_sgs)
+		return -ENOSPC;
+	builder->sgs[builder->cur_sg++] = &builder->descs[desc_index];
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_add_data() - Append arbitrary data to the descriptor
+ *                                  chain.
+ * @builder: builder to use.
+ * @data: pointer to the data to add to the descriptor chain.
+ * @len: length of the data to add.
+ *
+ * @data will either be directly referenced, or copied into the shadow buffer
+ * to be referenced from there.
+ */
+int scatterlist_builder_add_data(struct scatterlist_builder *builder,
+				 void *data, size_t len)
+{
+	const size_t cur_desc = builder->cur_desc;
+
+	if (len == 0)
+		return 0;
+
+	if (builder->cur_desc >= builder->num_descs)
+		return -ENOSPC;
+
+	if (!always_use_shadow_buffer && virt_addr_valid(data) &&
+	    virt_addr_valid(data + len)) {
+		/*
+		 * If "data" is in the 1:1 physical memory mapping then we can
+		 * use a single SG entry and avoid copying.
+		 */
+		struct page *page = virt_to_page(data);
+		size_t offset = (((size_t)data) & ~PAGE_MASK);
+		struct scatterlist *next_desc =
+			&builder->descs[builder->cur_desc];
+
+		memset(next_desc, 0, sizeof(*next_desc));
+		sg_set_page(next_desc, page, len, offset);
+		builder->cur_desc++;
+	} else if (!always_use_shadow_buffer && is_vmalloc_addr(data)) {
+		bool prev_pfn_valid = false;
+		unsigned long prev_pfn = 0;
+
+		/*
+		 * If "data" has been vmalloc'ed, we need at most one entry per
+		 * memory page but can avoid copying.
+		 */
+		while (len > 0) {
+			struct page *page = vmalloc_to_page(data);
+			unsigned long cur_pfn = page_to_pfn(page);
+			/* All pages but the first will start at offset 0. */
+			unsigned long offset =
+				(((unsigned long)data) & ~PAGE_MASK);
+			size_t len_in_page = min(PAGE_SIZE - offset, len);
+			struct scatterlist *next_desc =
+				&builder->descs[builder->cur_desc];
+
+			if (builder->cur_desc >= builder->num_descs)
+				return -ENOSPC;
+
+			/* Optimize contiguous pages */
+			if (prev_pfn_valid && (cur_pfn == prev_pfn + 1)) {
+				(next_desc - 1)->length += len_in_page;
+			} else {
+				memset(next_desc, 0, sizeof(*next_desc));
+				sg_set_page(next_desc, page, len_in_page,
+					    offset);
+				builder->cur_desc++;
+			}
+			data += len_in_page;
+			len -= len_in_page;
+			prev_pfn = cur_pfn;
+			prev_pfn_valid = true;
+		}
+	} else {
+		/*
+		 * As a last resort, copy into the shadow buffer and reference
+		 * it with a single SG entry. Calling
+		 * scatterlist_builder_retrieve_data() will be necessary to copy
+		 * the data written by the device back into @data.
+		 */
+		void *shadow_buffer =
+			builder->shadow_buffer + builder->shadow_buffer_pos;
+		struct page *page = virt_to_page(shadow_buffer);
+		unsigned long offset =
+			(((unsigned long)shadow_buffer) & ~PAGE_MASK);
+		struct scatterlist *next_desc =
+			&builder->descs[builder->cur_desc];
+
+		if (len >
+		    builder->shadow_buffer_size - builder->shadow_buffer_pos)
+			return -ENOSPC;
+
+		memcpy(shadow_buffer, data, len);
+		memset(next_desc, 0, sizeof(*next_desc));
+		sg_set_page(next_desc, page, len, offset);
+		builder->cur_desc++;
+		builder->shadow_buffer_pos += len;
+	}
+
+	sg_mark_end(&builder->descs[builder->cur_desc - 1]);
+	return scatterlist_builder_add_descriptor(builder, cur_desc);
+}
+
+/**
+ * scatterlist_builder_retrieve_data() - Retrieve a response written by the
+ *                                       device on the shadow buffer.
+ * @builder: builder to use.
+ * @sg_index: index of the descriptor to read from.
+ * @data: destination for the shadowed data.
+ *
+ * If the shadow buffer is pointed to by the descriptor at index @sg_index of
+ * the chain, then ``sg->length`` bytes are copied back from it into @data.
+ * Otherwise nothing is done since the device has written into @data directly.
+ *
+ * @data must have originally been added by scatterlist_builder_add_data() as
+ * the same size as passed to scatterlist_builder_add_data() will be copied
+ * back.
+ */
+int scatterlist_builder_retrieve_data(struct scatterlist_builder *builder,
+				      size_t sg_index, void *data)
+{
+	void *shadow_buf = builder->shadow_buffer;
+	struct scatterlist *sg;
+	void *kaddr;
+
+	/* We can only retrieve from the range of sgs currently set. */
+	if (sg_index >= builder->cur_sg)
+		return -ERANGE;
+
+	sg = builder->sgs[sg_index];
+	kaddr = pfn_to_kaddr(page_to_pfn(sg_page(sg))) + sg->offset;
+
+	if (kaddr >= shadow_buf &&
+	    kaddr < shadow_buf + builder->shadow_buffer_size) {
+		if (kaddr + sg->length >
+		    shadow_buf + builder->shadow_buffer_size)
+			return -EINVAL;
+
+		memcpy(data, kaddr, sg->length);
+	}
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_add_ioctl_cmd() - Add an ioctl command to the descriptor
+ *                                       chain.
+ * @builder: builder to use.
+ * @session: session on behalf of which the ioctl command is added.
+ * @ioctl_code: code of the ioctl to add (i.e. ``VIDIOC_*``).
+ */
+int scatterlist_builder_add_ioctl_cmd(struct scatterlist_builder *builder,
+				      struct virtio_media_session *session,
+				      u32 ioctl_code)
+{
+	struct virtio_media_cmd_ioctl *cmd_ioctl = &session->cmd.ioctl;
+
+	cmd_ioctl->hdr.cmd = VIRTIO_MEDIA_CMD_IOCTL;
+	cmd_ioctl->hdr.__reserved = 0;
+	cmd_ioctl->session_id = session->id;
+	cmd_ioctl->code = VIRTIO_MEDIA_IOCTL_CODE(ioctl_code);
+
+	return scatterlist_builder_add_data(builder, cmd_ioctl,
+					    sizeof(*cmd_ioctl));
+}
+
+/**
+ * scatterlist_builder_add_ioctl_resp() - Add storage to receive an ioctl
+ *                                        response to the descriptor chain.
+ * @builder: builder to use.
+ * @session: session on behalf of which the ioctl response is added.
+ */
+int scatterlist_builder_add_ioctl_resp(struct scatterlist_builder *builder,
+				       struct virtio_media_session *session)
+{
+	struct virtio_media_resp_ioctl *resp_ioctl = &session->resp.ioctl;
+
+	return scatterlist_builder_add_data(builder, resp_ioctl,
+					    sizeof(*resp_ioctl));
+}
diff --git a/drivers/media/virtio/scatterlist_builder.h b/drivers/media/virtio/scatterlist_builder.h
new file mode 100644
index 000000000..044ea409a
--- /dev/null
+++ b/drivers/media/virtio/scatterlist_builder.h
@@ -0,0 +1,90 @@
+/* SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0+ */
+
+/*
+ * Scatterlist builder helpers for virtio-media.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#ifndef __VIRTIO_MEDIA_SCATTERLIST_BUILDER_H
+#define __VIRTIO_MEDIA_SCATTERLIST_BUILDER_H
+
+#include <linux/scatterlist.h>
+
+#include "session.h"
+
+/**
+ * struct scatterlist_builder - helper to build a scatterlist from data.
+ * @descs: pool of descriptors to use.
+ * @num_descs: number of entries in descs.
+ * @cur_desc: next descriptor to be used in @descs.
+ * @shadow_buffer: pointer to a shadow buffer where elements that cannot be
+ * mapped directly into the scatterlist get copied.
+ * @shadow_buffer_size: size of @shadow_buffer.
+ * @shadow_buffer_pos: current position in @shadow_buffer.
+ * @sgs: descriptor chain to eventually pass to virtio functions.
+ * @num_sgs: total number of entries in @sgs.
+ * @cur_sg: next entry in @sgs to be used.
+ *
+ * Virtio passes data from the driver to the device (through e.g.
+ * virtqueue_add_sgs()) via a scatterlist that the device interprets as a
+ * linear view over scattered driver memory.
+ *
+ * In virtio-media, the payload of ioctls from user-space can for the most part
+ * be passed as-is, or after slight modification, which makes it tempting to
+ * just forward the ioctl payload received from user-space as-is instead of
+ * doing another copy into a dedicated buffer. This structure helps with this.
+ *
+ * virtio-media descriptor chains are typically made of the following parts:
+ *
+ * Device-readable:
+ * - A command structure, i.e. ``virtio_media_cmd_*``,
+ * - An ioctl payload (one of the regular ioctl parameters),
+ * - (optionally) arrays of &struct virtio_media_sg_entry describing the
+ *   content of buffers in guest memory.
+ *
+ * Device-writable:
+ * - A response structure, i.e. ``virtio_media_resp_*``,
+ * - An ioctl payload, that the device will write to.
+ *
+ * This structure helps laying out the descriptor chain into its @sgs member in
+ * an optimal way, by building a scatterlist adapted to the originating memory
+ * of the data we want to pass to the device while avoiding copies when
+ * possible.
+ *
+ * It is made of a pool of &struct scatterlist (@descs) that is used to
+ * build the final descriptor chain @sgs, and a @shadow_buffer where data that
+ * cannot (or should not) be mapped directly by the host can be temporarily
+ * copied.
+ */
+struct scatterlist_builder {
+	struct scatterlist *descs;
+	size_t num_descs;
+	size_t cur_desc;
+
+	void *shadow_buffer;
+	size_t shadow_buffer_size;
+	size_t shadow_buffer_pos;
+
+	struct scatterlist **sgs;
+	size_t num_sgs;
+	size_t cur_sg;
+};
+
+int scatterlist_builder_add_descriptor(struct scatterlist_builder *builder,
+				       size_t desc_index);
+
+int scatterlist_builder_add_data(struct scatterlist_builder *builder,
+				 void *data, size_t len);
+
+int scatterlist_builder_retrieve_data(struct scatterlist_builder *builder,
+				      size_t sg_index, void *data);
+
+int scatterlist_builder_add_ioctl_cmd(struct scatterlist_builder *builder,
+				      struct virtio_media_session *session,
+				      u32 ioctl_code);
+
+int scatterlist_builder_add_ioctl_resp(struct scatterlist_builder *builder,
+				       struct virtio_media_session *session);
+
+#endif // __VIRTIO_MEDIA_SCATTERLIST_BUILDER_H
diff --git a/drivers/media/virtio/session.h b/drivers/media/virtio/session.h
index 4ade7fb9c..6fe7ff5ae 100644
--- a/drivers/media/virtio/session.h
+++ b/drivers/media/virtio/session.h
@@ -9,17 +9,32 @@
 #ifndef __VIRTIO_MEDIA_SESSION_H
 #define __VIRTIO_MEDIA_SESSION_H
 
+#include <linux/scatterlist.h>
 #include <media/v4l2-fh.h>
 
 #include "uapi/linux/virtio_media.h"
 
+/*
+ * Size of the per-session virtio shadow and event buffers. 16K should be
+ * enough to contain everything we need.
+ */
+#define VIRTIO_SHADOW_BUF_SIZE 0x4000
+
 /**
  * struct virtio_media_session - A session on a virtio_media device.
  * @fh: file handler for the session.
  * @file: file pointer associated with the session's file handler.
  * @id: session ID used to communicate with the device.
- * @cmd: union of session-level commands. A session can have one command
- *       currently running.
+ * @cmd: union of session commands ``close`` and ``ioctl``. A session can have
+ *       one command currently running. The rest of the commands are handled by
+ *       &struct virtio_media.
+ * @resp: union of responses to session commands. A session can wait on one
+ *        command only. The rest of the responses are handled by
+ *        &struct virtio_media.
+ * @shadow_buf: shadow buffer where data to be added to the descriptor chain can
+ *              be staged before being sent to the device.
+ * @command_sgs: SG table gathering descriptors for a given command and its
+ *               response.
  * @list: link into the list of sessions for the device.
  */
 struct virtio_media_session {
@@ -30,9 +45,18 @@ struct virtio_media_session {
 	__dma_from_device_group_begin();
 	union {
 		struct virtio_media_cmd_close close;
+		struct virtio_media_cmd_ioctl ioctl;
 	} cmd;
+
+	union {
+		struct virtio_media_resp_ioctl ioctl;
+	} resp;
 	__dma_from_device_group_end();
 
+	void *shadow_buf;
+
+	struct sg_table command_sgs;
+
 	struct list_head list;
 };
 
diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/virtio_media.h
index 68299377a..a120c1014 100644
--- a/drivers/media/virtio/virtio_media.h
+++ b/drivers/media/virtio/virtio_media.h
@@ -14,6 +14,8 @@
 
 #include "uapi/linux/virtio_media.h"
 
+#define DESC_CHAIN_MAX_LEN SG_MAX_SINGLE_ALLOC
+
 #define VIRTIO_MEDIA_DEFAULT_DRIVER_NAME "virtio-media"
 
 /**
@@ -66,5 +68,12 @@ to_virtio_media(struct video_device *video_dev)
 int virtio_media_send_command(struct virtio_media *vv, struct scatterlist **sgs,
 			      const size_t out_sgs, const size_t in_sgs,
 			      size_t minimum_resp_len, size_t *resp_len);
+
+/* virtio_media_ioctls.c */
+
+long virtio_media_device_ioctl(struct file *file, unsigned int cmd,
+			       unsigned long arg);
+extern const struct v4l2_ioctl_ops virtio_media_ioctl_ops;
+
 #endif // __VIRTIO_MEDIA_H
 
diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
index 39c5a38d2..0fe20cf50 100644
--- a/drivers/media/virtio/virtio_media_driver.c
+++ b/drivers/media/virtio/virtio_media_driver.c
@@ -37,10 +37,20 @@ static struct virtio_media_session *
 virtio_media_session_alloc(struct virtio_media *vv, struct file *file)
 {
 	struct virtio_media_session *session;
+	int ret;
 
 	session = kzalloc_obj(*session, GFP_KERNEL);
 	if (!session)
-		return ERR_PTR(-ENOMEM);
+		goto err_session;
+
+	session->shadow_buf = kzalloc(VIRTIO_SHADOW_BUF_SIZE, GFP_KERNEL);
+	if (!session->shadow_buf)
+		goto err_shadow_buf;
+
+	ret = sg_alloc_table(&session->command_sgs, DESC_CHAIN_MAX_LEN,
+			     GFP_KERNEL);
+	if (ret)
+		goto err_payload_sgs;
 
 	// The caller is expected to set the ID once the host assigns a value.
 	session->id = 0;
@@ -50,6 +60,13 @@ virtio_media_session_alloc(struct virtio_media *vv, struct file *file)
 	virtio_media_session_fh_add(session, file);
 
 	return session;
+
+err_payload_sgs:
+	kfree(session->shadow_buf);
+err_shadow_buf:
+	kfree(session);
+err_session:
+	return ERR_PTR(-ENOMEM);
 }
 
 /**
@@ -77,6 +94,9 @@ static void virtio_media_session_free(struct virtio_media_session *session)
 	virtio_media_session_fh_del(session);
 	v4l2_fh_exit(&session->fh);
 
+	sg_free_table(&session->command_sgs);
+
+	kfree(session->shadow_buf);
 	kfree(session);
 }
 
@@ -342,6 +362,7 @@ static const struct v4l2_file_operations virtio_media_fops = {
 	.owner = THIS_MODULE,
 	.open = virtio_media_device_open,
 	.release = virtio_media_device_close,
+	.unlocked_ioctl = virtio_media_device_ioctl,
 };
 
 static void virtio_media_release(struct v4l2_device *v4l2_dev)
@@ -394,6 +415,7 @@ static int virtio_media_probe(struct virtio_device *virtio_dev)
 
 	vd = &vv->video_dev;
 	vd->v4l2_dev = &vv->v4l2_dev;
+	vd->ioctl_ops = &virtio_media_ioctl_ops;
 	vd->fops = &virtio_media_fops;
 	vd->release = video_device_release_empty;
 	strscpy(vd->name, "virtio-media", sizeof(vd->name));
diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/virtio/virtio_media_ioctls.c
new file mode 100644
index 000000000..e92032bce
--- /dev/null
+++ b/drivers/media/virtio/virtio_media_ioctls.c
@@ -0,0 +1,606 @@
+// SPDX-License-Identifier: BSD-3-Clause OR GPL-2.0+
+
+/*
+ * Ioctl implementations for the virtio-media driver.
+ *
+ * Copyright (c) 2024-2026 Google LLC.
+ */
+
+#include <linux/mutex.h>
+#include <linux/videodev2.h>
+#include <linux/virtio_config.h>
+#include <media/v4l2-ioctl.h>
+
+#include "scatterlist_builder.h"
+#include "virtio_media.h"
+
+/**
+ * virtio_media_send_r_ioctl() - Send a read-only ioctl to the device.
+ * @fh: file handler of the session doing the ioctl.
+ * @ioctl: ``VIDIOC_*`` ioctl code.
+ * @ioctl_data: pointer to the ioctl payload.
+ * @ioctl_data_len: length in bytes of the ioctl payload.
+ *
+ * Send an ioctl that has no driver payload, but expects a response from the
+ * host (i.e. an ioctl specified with ``_IOR``).
+ */
+static int virtio_media_send_r_ioctl(struct v4l2_fh *fh, u32 ioctl,
+				     void *ioctl_data, size_t ioctl_data_len)
+{
+	struct video_device *video_dev = fh->vdev;
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session = fh_to_session(fh);
+	struct scatterlist *sgs[3];
+	struct scatterlist_builder builder = {
+		.descs = session->command_sgs.sgl,
+		.num_descs = DESC_CHAIN_MAX_LEN,
+		.cur_desc = 0,
+		.shadow_buffer = session->shadow_buf,
+		.shadow_buffer_size = VIRTIO_SHADOW_BUF_SIZE,
+		.shadow_buffer_pos = 0,
+		.sgs = sgs,
+		.num_sgs = ARRAY_SIZE(sgs),
+		.cur_sg = 0,
+	};
+
+	/* Command descriptor */
+	int ret = scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl);
+
+	if (ret)
+		return ret;
+
+	/* Response descriptor */
+	ret = scatterlist_builder_add_ioctl_resp(&builder, session);
+	if (ret)
+		return ret;
+
+	/* Response payload */
+	ret = scatterlist_builder_add_data(&builder, ioctl_data,
+					   ioctl_data_len);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to prepare command descriptor chain\n");
+		return ret;
+	}
+
+	ret = virtio_media_send_command(vv, sgs, 1, 2,
+					sizeof(struct virtio_media_resp_ioctl) +
+					ioctl_data_len, NULL);
+	if (ret < 0)
+		return ret;
+
+	ret = scatterlist_builder_retrieve_data(&builder, 2, ioctl_data);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to retrieve response descriptor chain\n");
+		return ret;
+	}
+
+	return 0;
+}
+
+/**
+ * virtio_media_send_w_ioctl() - Send a write-only ioctl to the device.
+ * @fh: file handler of the session doing the ioctl.
+ * @ioctl: ``VIDIOC_*`` ioctl code.
+ * @ioctl_data: pointer to the ioctl payload.
+ * @ioctl_data_len: length in bytes of the ioctl payload.
+ *
+ * Send an ioctl that does not expect a reply beyond an error status (i.e. an
+ * ioctl specified with ``_IOW``) to the host.
+ */
+static int virtio_media_send_w_ioctl(struct v4l2_fh *fh, u32 ioctl,
+				     const void *ioctl_data,
+				     size_t ioctl_data_len)
+{
+	struct video_device *video_dev = fh->vdev;
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session = fh_to_session(fh);
+	struct scatterlist *sgs[3];
+	struct scatterlist_builder builder = {
+		.descs = session->command_sgs.sgl,
+		.num_descs = DESC_CHAIN_MAX_LEN,
+		.cur_desc = 0,
+		.shadow_buffer = session->shadow_buf,
+		.shadow_buffer_size = VIRTIO_SHADOW_BUF_SIZE,
+		.shadow_buffer_pos = 0,
+		.sgs = sgs,
+		.num_sgs = ARRAY_SIZE(sgs),
+		.cur_sg = 0,
+	};
+
+	/* Command descriptor */
+	int ret = scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl);
+
+	if (ret)
+		return ret;
+
+	/* Command payload */
+	ret = scatterlist_builder_add_data(&builder, (void *)ioctl_data,
+					   ioctl_data_len);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to prepare command descriptor chain\n");
+		return ret;
+	}
+
+	/* Response descriptor */
+	ret = scatterlist_builder_add_ioctl_resp(&builder, session);
+	if (ret)
+		return ret;
+
+	ret = virtio_media_send_command(vv, sgs, 2, 1,
+					sizeof(struct virtio_media_resp_ioctl),
+					NULL);
+	if (ret < 0)
+		return ret;
+
+	return 0;
+}
+
+/**
+ * virtio_media_send_wr_ioctl() - Send a read-write ioctl to the device.
+ * @fh: file handler of the session doing the ioctl.
+ * @ioctl: ``VIDIOC_*`` ioctl code.
+ * @ioctl_data: pointer to the ioctl payload.
+ * @ioctl_data_len: length in bytes of the ioctl payload.
+ * @minimum_resp_payload: minimum expected length of the response's payload.
+ *
+ * Sends an ioctl that expects a response of exactly the same size as the
+ * input (i.e. an ioctl specified with ``_IOWR``) to the host.
+ *
+ * This corresponds to what most V4L2 ioctls do. For instance
+ * ``VIDIOC_ENUM_FMT`` takes a partially-initialized &struct v4l2_fmtdesc
+ * and returns its filled version.
+ */
+static int virtio_media_send_wr_ioctl(struct v4l2_fh *fh, u32 ioctl,
+				      void *ioctl_data, size_t ioctl_data_len,
+				      size_t minimum_resp_payload)
+{
+	struct video_device *video_dev = fh->vdev;
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session = fh_to_session(fh);
+	struct scatterlist *sgs[4];
+	struct scatterlist_builder builder = {
+		.descs = session->command_sgs.sgl,
+		.num_descs = DESC_CHAIN_MAX_LEN,
+		.cur_desc = 0,
+		.shadow_buffer = session->shadow_buf,
+		.shadow_buffer_size = VIRTIO_SHADOW_BUF_SIZE,
+		.shadow_buffer_pos = 0,
+		.sgs = sgs,
+		.num_sgs = ARRAY_SIZE(sgs),
+		.cur_sg = 0,
+	};
+
+	/* Command descriptor */
+	int ret = scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl);
+
+	if (ret)
+		return ret;
+
+	/* Command payload */
+	ret = scatterlist_builder_add_data(&builder, ioctl_data,
+					   ioctl_data_len);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to prepare command descriptor chain\n");
+		return ret;
+	}
+
+	/* Response descriptor */
+	ret = scatterlist_builder_add_ioctl_resp(&builder, session);
+	if (ret)
+		return ret;
+
+	/* Response payload, same as command */
+	ret = scatterlist_builder_add_descriptor(&builder, 1);
+	if (ret)
+		return ret;
+
+	ret = virtio_media_send_command(vv, sgs, 2, 2,
+					sizeof(struct virtio_media_resp_ioctl) +
+						minimum_resp_payload,
+					NULL);
+	if (ret < 0)
+		return ret;
+
+	ret = scatterlist_builder_retrieve_data(&builder, 3, ioctl_data);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to retrieve response descriptor chain\n");
+		return ret;
+	}
+
+	return 0;
+}
+
+/*
+ * Macros suitable for defining ioctls with a constant size payload.
+ */
+
+#define SIMPLE_WR_IOCTL(name, ioctl, payload_t)                       \
+	static int virtio_media_##name(struct file *file, void *fh,   \
+				       payload_t *payload)            \
+	{                                                             \
+		struct v4l2_fh *vfh = file_to_v4l2_fh(file);          \
+		return virtio_media_send_wr_ioctl(vfh, ioctl, payload,\
+						  sizeof(*payload),   \
+						  sizeof(*payload));  \
+	}
+#define SIMPLE_R_IOCTL(name, ioctl, payload_t)                       \
+	static int virtio_media_##name(struct file *file, void *fh,  \
+				       payload_t *payload)           \
+	{                                                            \
+		struct v4l2_fh *vfh = file_to_v4l2_fh(file);         \
+		return virtio_media_send_r_ioctl(vfh, ioctl, payload,\
+						 sizeof(*payload));  \
+	}
+#define SIMPLE_W_IOCTL(name, ioctl, payload_t)                       \
+	static int virtio_media_##name(struct file *file, void *fh,  \
+				       payload_t *payload)           \
+	{                                                            \
+		struct v4l2_fh *vfh = file_to_v4l2_fh(file);         \
+		return virtio_media_send_w_ioctl(vfh, ioctl, payload,\
+						 sizeof(*payload));  \
+	}
+
+/*
+ * V4L2 ioctl handlers.
+ *
+ * Most of these functions just forward the ioctl to the host, for these we can
+ * use one of the SIMPLE_*_IOCTL macros. Exceptions that have their own
+ * standalone function follow.
+ */
+
+SIMPLE_WR_IOCTL(enum_fmt, VIDIOC_ENUM_FMT, struct v4l2_fmtdesc)
+SIMPLE_WR_IOCTL(g_fmt, VIDIOC_G_FMT, struct v4l2_format)
+SIMPLE_WR_IOCTL(s_fmt, VIDIOC_S_FMT, struct v4l2_format)
+SIMPLE_WR_IOCTL(try_fmt, VIDIOC_TRY_FMT, struct v4l2_format)
+SIMPLE_WR_IOCTL(enum_framesizes, VIDIOC_ENUM_FRAMESIZES,
+		struct v4l2_frmsizeenum)
+SIMPLE_WR_IOCTL(enum_frameintervals, VIDIOC_ENUM_FRAMEINTERVALS,
+		struct v4l2_frmivalenum)
+SIMPLE_WR_IOCTL(query_ext_ctrl, VIDIOC_QUERY_EXT_CTRL,
+		struct v4l2_query_ext_ctrl)
+SIMPLE_WR_IOCTL(s_dv_timings, VIDIOC_S_DV_TIMINGS, struct v4l2_dv_timings)
+SIMPLE_WR_IOCTL(g_dv_timings, VIDIOC_G_DV_TIMINGS, struct v4l2_dv_timings)
+SIMPLE_R_IOCTL(query_dv_timings, VIDIOC_QUERY_DV_TIMINGS,
+	       struct v4l2_dv_timings)
+SIMPLE_WR_IOCTL(enum_dv_timings, VIDIOC_ENUM_DV_TIMINGS,
+		struct v4l2_enum_dv_timings)
+SIMPLE_WR_IOCTL(dv_timings_cap, VIDIOC_DV_TIMINGS_CAP,
+		struct v4l2_dv_timings_cap)
+SIMPLE_WR_IOCTL(enuminput, VIDIOC_ENUMINPUT, struct v4l2_input)
+SIMPLE_WR_IOCTL(querymenu, VIDIOC_QUERYMENU, struct v4l2_querymenu)
+SIMPLE_WR_IOCTL(enumoutput, VIDIOC_ENUMOUTPUT, struct v4l2_output)
+SIMPLE_WR_IOCTL(enumaudio, VIDIOC_ENUMAUDIO, struct v4l2_audio)
+SIMPLE_R_IOCTL(g_audio, VIDIOC_G_AUDIO, struct v4l2_audio)
+SIMPLE_W_IOCTL(s_audio, VIDIOC_S_AUDIO, const struct v4l2_audio)
+SIMPLE_WR_IOCTL(enumaudout, VIDIOC_ENUMAUDOUT, struct v4l2_audioout)
+SIMPLE_R_IOCTL(g_audout, VIDIOC_G_AUDOUT, struct v4l2_audioout)
+SIMPLE_W_IOCTL(s_audout, VIDIOC_S_AUDOUT, const struct v4l2_audioout)
+SIMPLE_WR_IOCTL(g_modulator, VIDIOC_G_MODULATOR, struct v4l2_modulator)
+SIMPLE_W_IOCTL(s_modulator, VIDIOC_S_MODULATOR, const struct v4l2_modulator)
+SIMPLE_WR_IOCTL(g_selection, VIDIOC_G_SELECTION, struct v4l2_selection)
+SIMPLE_WR_IOCTL(s_selection, VIDIOC_S_SELECTION, struct v4l2_selection)
+SIMPLE_R_IOCTL(g_enc_index, VIDIOC_G_ENC_INDEX, struct v4l2_enc_idx)
+SIMPLE_WR_IOCTL(encoder_cmd, VIDIOC_ENCODER_CMD, struct v4l2_encoder_cmd)
+SIMPLE_WR_IOCTL(try_encoder_cmd, VIDIOC_TRY_ENCODER_CMD,
+		struct v4l2_encoder_cmd)
+SIMPLE_WR_IOCTL(try_decoder_cmd, VIDIOC_TRY_DECODER_CMD,
+		struct v4l2_decoder_cmd)
+SIMPLE_WR_IOCTL(g_parm, VIDIOC_G_PARM, struct v4l2_streamparm)
+SIMPLE_WR_IOCTL(s_parm, VIDIOC_S_PARM, struct v4l2_streamparm)
+SIMPLE_R_IOCTL(g_std, VIDIOC_G_STD, v4l2_std_id)
+SIMPLE_R_IOCTL(querystd, VIDIOC_QUERYSTD, v4l2_std_id)
+SIMPLE_WR_IOCTL(enumstd, VIDIOC_ENUMSTD, struct v4l2_standard)
+SIMPLE_WR_IOCTL(g_tuner, VIDIOC_G_TUNER, struct v4l2_tuner)
+SIMPLE_W_IOCTL(s_tuner, VIDIOC_S_TUNER, const struct v4l2_tuner)
+SIMPLE_WR_IOCTL(g_frequency, VIDIOC_G_FREQUENCY, struct v4l2_frequency)
+SIMPLE_W_IOCTL(s_frequency, VIDIOC_S_FREQUENCY, const struct v4l2_frequency)
+SIMPLE_WR_IOCTL(enum_freq_bands, VIDIOC_ENUM_FREQ_BANDS,
+		struct v4l2_frequency_band)
+SIMPLE_WR_IOCTL(g_sliced_vbi_cap, VIDIOC_G_SLICED_VBI_CAP,
+		struct v4l2_sliced_vbi_cap)
+SIMPLE_W_IOCTL(s_hw_freq_seek, VIDIOC_S_HW_FREQ_SEEK,
+	       const struct v4l2_hw_freq_seek)
+
+/*
+ * QUERYCAP is handled by reading the configuration area.
+ */
+
+static int virtio_media_querycap(struct file *file, void *fh,
+				 struct v4l2_capability *cap)
+{
+	struct video_device *video_dev = video_devdata(file);
+	struct virtio_media *vv = to_virtio_media(video_dev);
+
+	strscpy(cap->bus_info, "platform:virtio-media");
+	strscpy(cap->driver, VIRTIO_MEDIA_DEFAULT_DRIVER_NAME);
+
+	virtio_cread_bytes(vv->virtio_dev, 8, cap->card, sizeof(cap->card));
+
+	cap->capabilities = video_dev->device_caps | V4L2_CAP_DEVICE_CAPS;
+	cap->device_caps = video_dev->device_caps;
+
+	return 0;
+}
+
+/*
+ * s/g_input/output work with an unsigned int - recast this to a u32 so the
+ * size is unambiguous.
+ */
+
+static int virtio_media_g_input(struct file *file, void *fh, unsigned int *i)
+{
+	u32 input;
+
+	int ret = virtio_media_send_r_ioctl(file_to_v4l2_fh(file),
+					 VIDIOC_G_INPUT, &input,
+					 sizeof(input));
+	if (ret)
+		return ret;
+
+	*i = input;
+
+	return 0;
+}
+
+static int virtio_media_s_input(struct file *file, void *fh, unsigned int i)
+{
+	u32 input = i;
+
+	return virtio_media_send_wr_ioctl(file_to_v4l2_fh(file),
+					  VIDIOC_S_INPUT, &input,
+					  sizeof(input), sizeof(input));
+}
+
+static int virtio_media_g_output(struct file *file, void *fh, unsigned int *o)
+{
+	u32 output;
+
+	int ret = virtio_media_send_r_ioctl(file_to_v4l2_fh(file),
+					 VIDIOC_G_OUTPUT, &output,
+					 sizeof(output));
+	if (ret)
+		return ret;
+
+	*o = output;
+
+	return 0;
+}
+
+static int virtio_media_s_output(struct file *file, void *fh, unsigned int o)
+{
+	u32 output = o;
+
+	return virtio_media_send_wr_ioctl(file_to_v4l2_fh(file),
+					  VIDIOC_S_OUTPUT, &output,
+					  sizeof(output), sizeof(output));
+}
+
+/*
+ * s_std doesn't work with a pointer, so we cannot use SIMPLE_W_IOCTL.
+ */
+
+static int virtio_media_s_std(struct file *file, void *fh, v4l2_std_id s)
+{
+	int ret = virtio_media_send_w_ioctl(file_to_v4l2_fh(file), VIDIOC_S_STD,
+					&s, sizeof(s));
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
+const struct v4l2_ioctl_ops virtio_media_ioctl_ops = {
+	/* VIDIOC_QUERYCAP handler */
+	.vidioc_querycap = virtio_media_querycap,
+
+	/* VIDIOC_ENUM_FMT handlers */
+	.vidioc_enum_fmt_vid_cap = virtio_media_enum_fmt,
+	.vidioc_enum_fmt_vid_overlay = virtio_media_enum_fmt,
+	.vidioc_enum_fmt_vid_out = virtio_media_enum_fmt,
+	.vidioc_enum_fmt_sdr_cap = virtio_media_enum_fmt,
+	.vidioc_enum_fmt_sdr_out = virtio_media_enum_fmt,
+	.vidioc_enum_fmt_meta_cap = virtio_media_enum_fmt,
+	.vidioc_enum_fmt_meta_out = virtio_media_enum_fmt,
+
+	/* VIDIOC_G_FMT handlers */
+	.vidioc_g_fmt_vid_cap = virtio_media_g_fmt,
+	.vidioc_g_fmt_vid_overlay = virtio_media_g_fmt,
+	.vidioc_g_fmt_vid_out = virtio_media_g_fmt,
+	.vidioc_g_fmt_vid_out_overlay = virtio_media_g_fmt,
+	.vidioc_g_fmt_vbi_cap = virtio_media_g_fmt,
+	.vidioc_g_fmt_vbi_out = virtio_media_g_fmt,
+	.vidioc_g_fmt_sliced_vbi_cap = virtio_media_g_fmt,
+	.vidioc_g_fmt_sliced_vbi_out = virtio_media_g_fmt,
+	.vidioc_g_fmt_vid_cap_mplane = virtio_media_g_fmt,
+	.vidioc_g_fmt_vid_out_mplane = virtio_media_g_fmt,
+	.vidioc_g_fmt_sdr_cap = virtio_media_g_fmt,
+	.vidioc_g_fmt_sdr_out = virtio_media_g_fmt,
+	.vidioc_g_fmt_meta_cap = virtio_media_g_fmt,
+	.vidioc_g_fmt_meta_out = virtio_media_g_fmt,
+
+	/* VIDIOC_S_FMT handlers */
+	.vidioc_s_fmt_vid_cap = virtio_media_s_fmt,
+	.vidioc_s_fmt_vid_overlay = virtio_media_s_fmt,
+	.vidioc_s_fmt_vid_out = virtio_media_s_fmt,
+	.vidioc_s_fmt_vid_out_overlay = virtio_media_s_fmt,
+	.vidioc_s_fmt_vbi_cap = virtio_media_s_fmt,
+	.vidioc_s_fmt_vbi_out = virtio_media_s_fmt,
+	.vidioc_s_fmt_sliced_vbi_cap = virtio_media_s_fmt,
+	.vidioc_s_fmt_sliced_vbi_out = virtio_media_s_fmt,
+	.vidioc_s_fmt_vid_cap_mplane = virtio_media_s_fmt,
+	.vidioc_s_fmt_vid_out_mplane = virtio_media_s_fmt,
+	.vidioc_s_fmt_sdr_cap = virtio_media_s_fmt,
+	.vidioc_s_fmt_sdr_out = virtio_media_s_fmt,
+	.vidioc_s_fmt_meta_cap = virtio_media_s_fmt,
+	.vidioc_s_fmt_meta_out = virtio_media_s_fmt,
+
+	/* VIDIOC_TRY_FMT handlers */
+	.vidioc_try_fmt_vid_cap = virtio_media_try_fmt,
+	.vidioc_try_fmt_vid_overlay = virtio_media_try_fmt,
+	.vidioc_try_fmt_vid_out = virtio_media_try_fmt,
+	.vidioc_try_fmt_vid_out_overlay = virtio_media_try_fmt,
+	.vidioc_try_fmt_vbi_cap = virtio_media_try_fmt,
+	.vidioc_try_fmt_vbi_out = virtio_media_try_fmt,
+	.vidioc_try_fmt_sliced_vbi_cap = virtio_media_try_fmt,
+	.vidioc_try_fmt_sliced_vbi_out = virtio_media_try_fmt,
+	.vidioc_try_fmt_vid_cap_mplane = virtio_media_try_fmt,
+	.vidioc_try_fmt_vid_out_mplane = virtio_media_try_fmt,
+	.vidioc_try_fmt_sdr_cap = virtio_media_try_fmt,
+	.vidioc_try_fmt_sdr_out = virtio_media_try_fmt,
+	.vidioc_try_fmt_meta_cap = virtio_media_try_fmt,
+	.vidioc_try_fmt_meta_out = virtio_media_try_fmt,
+
+	/* Standard handling */
+	.vidioc_g_std = virtio_media_g_std,
+	.vidioc_s_std = virtio_media_s_std,
+	.vidioc_querystd = virtio_media_querystd,
+
+	/* Input handling */
+	.vidioc_enum_input = virtio_media_enuminput,
+	.vidioc_g_input = virtio_media_g_input,
+	.vidioc_s_input = virtio_media_s_input,
+
+	/* Output handling */
+	.vidioc_enum_output = virtio_media_enumoutput,
+	.vidioc_g_output = virtio_media_g_output,
+	.vidioc_s_output = virtio_media_s_output,
+
+	/* Control handling */
+	.vidioc_query_ext_ctrl = virtio_media_query_ext_ctrl,
+	.vidioc_querymenu = virtio_media_querymenu,
+
+	/* Audio ioctls */
+	.vidioc_enumaudio = virtio_media_enumaudio,
+	.vidioc_g_audio = virtio_media_g_audio,
+	.vidioc_s_audio = virtio_media_s_audio,
+
+	/* Audio out ioctls */
+	.vidioc_enumaudout = virtio_media_enumaudout,
+	.vidioc_g_audout = virtio_media_g_audout,
+	.vidioc_s_audout = virtio_media_s_audout,
+	.vidioc_g_modulator = virtio_media_g_modulator,
+	.vidioc_s_modulator = virtio_media_s_modulator,
+
+	/* Crop ioctls */
+	/*
+	 * Not directly an ioctl (part of VIDIOC_CROPCAP), so no need to
+	 * implement.
+	 */
+	.vidioc_g_pixelaspect = NULL,
+	.vidioc_g_selection = virtio_media_g_selection,
+	.vidioc_s_selection = virtio_media_s_selection,
+
+	/* Compression ioctls */
+	/* Deprecated in V4L2. */
+	.vidioc_g_jpegcomp = NULL,
+	/* Deprecated in V4L2. */
+	.vidioc_s_jpegcomp = NULL,
+	.vidioc_g_enc_index = virtio_media_g_enc_index,
+	.vidioc_encoder_cmd = virtio_media_encoder_cmd,
+	.vidioc_try_encoder_cmd = virtio_media_try_encoder_cmd,
+	.vidioc_try_decoder_cmd = virtio_media_try_decoder_cmd,
+
+	/* Stream type-dependent parameter ioctls */
+	.vidioc_g_parm = virtio_media_g_parm,
+	.vidioc_s_parm = virtio_media_s_parm,
+
+	/* Tuner ioctls */
+	.vidioc_g_tuner = virtio_media_g_tuner,
+	.vidioc_s_tuner = virtio_media_s_tuner,
+	.vidioc_g_frequency = virtio_media_g_frequency,
+	.vidioc_s_frequency = virtio_media_s_frequency,
+	.vidioc_enum_freq_bands = virtio_media_enum_freq_bands,
+
+	/* Sliced VBI cap */
+	.vidioc_g_sliced_vbi_cap = virtio_media_g_sliced_vbi_cap,
+
+	/* Log status ioctl */
+	/* Guest-only operation */
+	.vidioc_log_status = NULL,
+
+	.vidioc_s_hw_freq_seek = virtio_media_s_hw_freq_seek,
+
+	.vidioc_enum_framesizes = virtio_media_enum_framesizes,
+	.vidioc_enum_frameintervals = virtio_media_enum_frameintervals,
+
+	/* DV Timings IOCTLs */
+	.vidioc_s_dv_timings = virtio_media_s_dv_timings,
+	.vidioc_g_dv_timings = virtio_media_g_dv_timings,
+	.vidioc_query_dv_timings = virtio_media_query_dv_timings,
+	.vidioc_enum_dv_timings = virtio_media_enum_dv_timings,
+	.vidioc_dv_timings_cap = virtio_media_dv_timings_cap,
+	.vidioc_g_edid = NULL,
+	.vidioc_s_edid = NULL,
+
+	/* For other private ioctls */
+	.vidioc_default = NULL,
+};
+
+long virtio_media_device_ioctl(struct file *file, unsigned int cmd,
+			       unsigned long arg)
+{
+	struct video_device *video_dev = video_devdata(file);
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct v4l2_fh *vfh = NULL;
+	struct v4l2_standard standard;
+	v4l2_std_id std_id = 0;
+	int ret;
+
+	if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags))
+		vfh = file_to_v4l2_fh(file);
+
+	mutex_lock(&vv->vlock);
+
+	/*
+	 * We need to handle a few ioctls manually because their results
+	 * rely on vfd->tvnorms, which is normally updated by the driver
+	 * as S_INPUT is called. Since we want to just pass these ioctls
+	 * through, we have to hijack them from here.
+	 */
+	switch (cmd) {
+	case VIDIOC_S_STD:
+		ret = copy_from_user(&std_id, (void __user *)arg,
+				     sizeof(std_id));
+		if (ret) {
+			ret = -EFAULT;
+			break;
+		}
+		ret = virtio_media_s_std(file, vfh, std_id);
+		break;
+	case VIDIOC_ENUMSTD:
+		ret = copy_from_user(&standard, (void __user *)arg,
+				     sizeof(standard));
+		if (ret) {
+			ret = -EFAULT;
+			break;
+		}
+		ret = virtio_media_enumstd(file, vfh, &standard);
+		if (ret)
+			break;
+		ret = copy_to_user((void __user *)arg, &standard,
+				   sizeof(standard));
+		if (ret)
+			ret = -EFAULT;
+		break;
+	case VIDIOC_QUERYSTD:
+		ret = virtio_media_querystd(file, vfh, &std_id);
+		if (ret)
+			break;
+		ret = copy_to_user((void __user *)arg, &std_id, sizeof(std_id));
+		if (ret)
+			ret = -EFAULT;
+		break;
+	default:
+		ret = video_ioctl2(file, cmd, arg);
+		break;
+	}
+
+	mutex_unlock(&vv->vlock);
+
+	return ret;
+}
diff --git a/include/uapi/linux/virtio_media.h b/include/uapi/linux/virtio_media.h
index ad05d7421..c1e68d47c 100644
--- a/include/uapi/linux/virtio_media.h
+++ b/include/uapi/linux/virtio_media.h
@@ -115,4 +115,47 @@ struct virtio_media_cmd_close {
 	__le32 __reserved;
 };
 
+/**
+ * VIRTIO_MEDIA_CMD_IOCTL - Driver command for executing an ioctl.
+ *
+ * This command asks the device to run one of the ``VIDIOC_*`` ioctls on the
+ * active session.
+ *
+ * The code of the ioctl is extracted from the VIDIOC_* definitions in
+ * ``videodev2.h``, and consists of the second argument of the ``_IO*`` macro.
+ *
+ * Each ioctl has a payload, which is defined by the third argument of the
+ * ``_IO*`` macro defining it. It can be writable by the driver (``_IOW``), the
+ * device (``_IOR``), or both (``_IOWR``).
+ *
+ * If an ioctl is writable by the driver, it must be followed by a
+ * driver-writable descriptor containing the payload.
+ *
+ * If an ioctl is writable by the device, it must be followed by a
+ * device-writable descriptor of the size of the payload that the device will
+ * write into.
+ *
+ */
+#define VIRTIO_MEDIA_CMD_IOCTL 3
+
+/**
+ * struct virtio_media_cmd_ioctl - Driver command for VIRTIO_MEDIA_CMD_IOCTL.
+ * @hdr: header with cmd member set to VIRTIO_MEDIA_CMD_IOCTL.
+ * @session_id: id of the session to run the ioctl on.
+ * @code: code of the ioctl to run.
+ */
+struct virtio_media_cmd_ioctl {
+	struct virtio_media_cmd_header hdr;
+	__le32 session_id;
+	__le32 code;
+};
+
+/**
+ * struct virtio_media_resp_ioctl - Device response for VIRTIO_MEDIA_CMD_IOCTL.
+ * @hdr: header containing the status of the ioctl.
+ */
+struct virtio_media_resp_ioctl {
+	struct virtio_media_resp_header hdr;
+};
+
 #endif // _UAPI__LINUX_VIRTIO_MEDIA_H
-- 
2.56.1.750.gf70dc682cf-goog


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

* [PATCH v11 3/6] media: virtio: Add extended controls support
  2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
  2026-11-20 21:59 ` [PATCH v11 1/6] media: virtio: Add core driver and session management Brian Daniels
  2026-11-20 21:59 ` [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure Brian Daniels
@ 2026-11-20 21:59 ` Brian Daniels
  2026-11-20 22:23   ` sashiko-bot
  2026-11-20 21:59 ` [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll Brian Daniels
                   ` (2 subsequent siblings)
  5 siblings, 1 reply; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Brian Daniels

From: Alexandre Courbot <gnurou@gmail.com>

Add support for VIDIOC_G_EXT_CTRLS, VIDIOC_S_EXT_CTRLS, and
VIDIOC_TRY_EXT_CTRLS.

Extended controls carry an auxiliary array of struct v4l2_ext_control
entries and may reference userspace payload buffers. Pin userspace
control payloads using vb2_create_framevec() for the duration of the
virtio command and pass their physical memory segments to the host as an
array of struct virtio_media_sg_entry descriptors in the session shadow
buffer.

Signed-off-by: Alexandre Courbot <gnurou@gmail.com>
Assisted-by: LLM
Co-developed-by: Brian Daniels <briandaniels@google.com>
Signed-off-by: Brian Daniels <briandaniels@google.com>
---
 drivers/media/virtio/scatterlist_builder.c | 302 +++++++++++++++++++++
 drivers/media/virtio/scatterlist_builder.h |  27 ++
 drivers/media/virtio/virtio_media_ioctls.c | 164 +++++++++++
 include/uapi/linux/virtio_media.h          |  13 +
 4 files changed, 506 insertions(+)

diff --git a/drivers/media/virtio/scatterlist_builder.c b/drivers/media/virtio/scatterlist_builder.c
index ae8ffee82..63d50369f 100644
--- a/drivers/media/virtio/scatterlist_builder.c
+++ b/drivers/media/virtio/scatterlist_builder.c
@@ -220,3 +220,305 @@ int scatterlist_builder_add_ioctl_resp(struct scatterlist_builder *builder,
 	return scatterlist_builder_add_data(builder, resp_ioctl,
 					    sizeof(*resp_ioctl));
 }
+
+/**
+ * __scatterlist_builder_add_userptr() - Add user pages to @builder.
+ * @builder: builder to use.
+ * @userptr: pointer to userspace memory that we want to add.
+ * @length: length of the data to add.
+ * @sg_list: output parameter. Upon success, points to the area of the shadow
+ *           buffer containing the array of SG entries to be added to the
+ *           descriptor chain.
+ * @nents: output parameter. Upon success, contains the number of entries
+ *         pointed to by @sg_list.
+ *
+ * Data referenced by userspace pointers can be potentially large and very
+ * scattered, which could overwhelm the descriptor chain if added as-is. For
+ * these, we instead build an array of &struct virtio_media_sg_entry in the
+ * shadow buffer and reference it using a single descriptor.
+ *
+ * This function is a helper to perform that. Callers should then add the
+ * descriptor to the chain properly.
+ *
+ * Returns %-EFAULT if @userptr is not a valid user address, which is a case the
+ * driver should consider as "normal" operation. All other failures signal a
+ * problem with the driver.
+ */
+static int
+__scatterlist_builder_add_userptr(struct scatterlist_builder *builder,
+				  unsigned long userptr, unsigned long length,
+				  struct virtio_media_sg_entry **sg_list,
+				  int *nents)
+{
+	struct sg_table sg_table = {};
+	struct frame_vector *framevec;
+	struct scatterlist *sg_iter;
+	struct page **pages;
+	const unsigned int offset = userptr & ~PAGE_MASK;
+	unsigned int pages_count;
+	size_t entries_size;
+	size_t initial_cur_framevec = builder->cur_framevec;
+	int i;
+	int ret;
+
+	if (builder->cur_framevec >= builder->num_framevecs) {
+		pr_err("Ran out of framevecs (%zu/%zu)", builder->cur_framevec,
+		       builder->num_framevecs);
+		ret = -ENOMEM;
+	}
+
+	framevec = vb2_create_framevec(userptr, length, true);
+	if (IS_ERR(framevec)) {
+		if (PTR_ERR(framevec) != -EFAULT) {
+			pr_warn("error %ld creating frame vector for userptr 0x%lx, length 0x%lx\n",
+				PTR_ERR(framevec), userptr, length);
+		} else {
+			/* -EINVAL is expected in case of invalid userptr. */
+			framevec = ERR_PTR(-EINVAL);
+		}
+		return PTR_ERR(framevec);
+	}
+
+	pages = frame_vector_pages(framevec);
+	if (IS_ERR(pages)) {
+		pr_warn("error getting vector pages\n");
+		ret = PTR_ERR(pages);
+		goto free_framevec;
+	}
+	pages_count = frame_vector_count(framevec);
+	ret = sg_alloc_table_from_pages(&sg_table, pages, pages_count, offset,
+					length, 0);
+	if (ret) {
+		pr_warn("error creating sg table\n");
+		goto free_framevec;
+	}
+
+	/* Allocate our actual SG in the shadow buffer. */
+	*nents = sg_nents(sg_table.sgl);
+	entries_size = sizeof(**sg_list) * *nents;
+	if (builder->shadow_buffer_pos + entries_size >
+	    builder->shadow_buffer_size) {
+		ret = -ENOMEM;
+		goto free_sg;
+	}
+
+	*sg_list = builder->shadow_buffer + builder->shadow_buffer_pos;
+	builder->shadow_buffer_pos += entries_size;
+
+	for_each_sgtable_sg(&sg_table, sg_iter, i) {
+		struct virtio_media_sg_entry *sg_entry = &(*sg_list)[i];
+
+		sg_entry->start = sg_phys(sg_iter);
+		sg_entry->len = sg_iter->length;
+		sg_entry->__reserved = 0;
+	}
+
+	builder->framevecs[builder->cur_framevec++] = framevec;
+
+free_sg:
+	sg_free_table(&sg_table);
+free_framevec:
+	// Only destroy the framevec if we didn't save it
+	if (builder->cur_framevec == initial_cur_framevec && framevec)
+		vb2_destroy_framevec(framevec);
+	return ret;
+}
+
+/**
+ * scatterlist_builder_add_userptr() - Add a user-memory buffer using an array
+ *                                     of &struct virtio_media_sg_entry.
+ * @builder: builder to use.
+ * @userptr: pointer to userspace memory that we want to add.
+ * @length: length of the data to add.
+ *
+ * Upon success, an array of &struct virtio_media_sg_entry referencing
+ * @userptr has been built into the shadow buffer, and that array added to the
+ * descriptor chain.
+ */
+static int scatterlist_builder_add_userptr(struct scatterlist_builder *builder,
+					   unsigned long userptr,
+					   unsigned long length)
+{
+	int ret;
+	int nents;
+	struct virtio_media_sg_entry *sg_list;
+
+	ret = __scatterlist_builder_add_userptr(builder, userptr, length,
+						&sg_list, &nents);
+	if (ret)
+		return ret;
+
+	ret = scatterlist_builder_add_data(builder, sg_list,
+					   sizeof(*sg_list) * nents);
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_add_ext_ctrls() - Add a &struct v4l2_ext_controls and its
+ *                                       controls to @builder.
+ * @builder: builder to use.
+ * @ctrls: &struct v4l2_ext_controls to add.
+ *
+ * Add @ctrls and its array of &struct v4l2_ext_control to the descriptor
+ * chain.
+ */
+int scatterlist_builder_add_ext_ctrls(struct scatterlist_builder *builder,
+				      struct v4l2_ext_controls *ctrls)
+{
+	int ret;
+
+	/* v4l2_ext_controls */
+	ret = scatterlist_builder_add_data(builder, ctrls, sizeof(*ctrls));
+	if (ret)
+		return ret;
+
+	if (ctrls->count > 0) {
+		/* array of v4l2_controls */
+		ret = scatterlist_builder_add_data(builder, ctrls->controls,
+						   sizeof(ctrls->controls[0]) *
+							   ctrls->count);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_allocate_framevecs() - Allocate the pointers to store
+ *                                            framevecs during a request.
+ * @builder: builder to use.
+ * @ctrls: &struct v4l2_ext_controls from which we determine how many framevecs
+ *         are needed
+ *
+ * The framevecs are used to pin the user pages during the request. Once the
+ * request is completed, the allocated framevecs and pointers should be freed
+ * with scatterlist_builder_free_framevecs().
+ */
+int
+scatterlist_builder_allocate_framevecs(struct scatterlist_builder *builder,
+				       struct v4l2_ext_controls *ctrls)
+{
+	int i;
+
+	builder->cur_framevec = 0;
+
+	/* Count the pointers to user memory in individual controls */
+	for (i = 0; i < ctrls->count; i++) {
+		struct v4l2_ext_control *ctrl = &ctrls->controls[i];
+
+		if (ctrl->size > 0)
+			builder->num_framevecs += 1;
+	}
+
+	if (builder->num_framevecs > 0) {
+		builder->framevecs = kzalloc_objs(struct frame_vector*,
+						  builder->num_framevecs);
+		if (!builder->framevecs) {
+			builder->num_framevecs = 0;
+			return -ENOMEM;
+		}
+	}
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_free_framevecs() - Free the framevecs used during a
+ *                                        request.
+ * @builder: builder to use.
+ *
+ * Frees the framevecs allocated in scatterlist_builder_allocate_framevecs().
+ */
+void
+scatterlist_builder_free_framevecs(struct scatterlist_builder *builder)
+{
+	if (builder->cur_framevec && builder->framevecs) {
+		struct frame_vector *vec;
+
+		while (builder->cur_framevec--) {
+			vec = builder->framevecs[builder->cur_framevec];
+			vb2_destroy_framevec(vec);
+		}
+
+		kfree(builder->framevecs);
+	}
+
+	builder->framevecs = NULL;
+	builder->num_framevecs = 0;
+	builder->cur_framevec = 0;
+}
+
+/**
+ * scatterlist_builder_add_ext_ctrls_userptrs() - Add the userspace payloads of
+ *                                                a &struct v4l2_ext_controls
+ *                                                to the descriptor chain.
+ * @builder: builder to use.
+ * @ctrls: &struct v4l2_ext_controls from which we want to add the
+ *         userspace payload.
+ *
+ * Add the userspace payloads of @ctrls to the descriptor chain. This is split
+ * out of scatterlist_builder_add_ext_ctrls() because we only want to add
+ * these to the device-readable part of the descriptor chain.
+ */
+int
+scatterlist_builder_add_ext_ctrls_userptrs(struct scatterlist_builder *builder,
+					   struct v4l2_ext_controls *ctrls)
+{
+	int i;
+	int ret;
+
+	for (i = 0; i < ctrls->count; i++) {
+		struct v4l2_ext_control *ctrl = &ctrls->controls[i];
+
+		if (ctrl->size > 0) {
+			unsigned long uptr = (unsigned long)ctrl->ptr;
+
+			ret = scatterlist_builder_add_userptr(builder, uptr,
+							      ctrl->size);
+			if (ret)
+				return ret;
+		}
+	}
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_retrieve_ext_ctrls() - Retrieve controls written by the
+ *                                            device on the shadow buffer,
+ *                                            if needed.
+ * @builder: builder to use.
+ * @sg_index: index of the first SG entry of the controls in the builder's
+ *            descriptor chain.
+ * @ctrls: &struct v4l2_ext_controls to copy shadow buffer data into.
+ *
+ * If the shadow buffer is pointed to by @sg_index, copy its content back into
+ * @ctrls.
+ */
+int scatterlist_builder_retrieve_ext_ctrls(struct scatterlist_builder *builder,
+					   size_t sg_index,
+					   struct v4l2_ext_controls *ctrls)
+{
+	struct v4l2_ext_control *controls_backup = ctrls->controls;
+	int ret;
+
+	ret = scatterlist_builder_retrieve_data(builder, sg_index++, ctrls);
+
+	if (ret)
+		return ret;
+
+	ctrls->controls = controls_backup;
+
+	if (ctrls->count > 0 && ctrls->controls) {
+		ret = scatterlist_builder_retrieve_data(builder, sg_index++,
+							ctrls->controls);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
diff --git a/drivers/media/virtio/scatterlist_builder.h b/drivers/media/virtio/scatterlist_builder.h
index 044ea409a..bced1e030 100644
--- a/drivers/media/virtio/scatterlist_builder.h
+++ b/drivers/media/virtio/scatterlist_builder.h
@@ -25,6 +25,11 @@
  * @sgs: descriptor chain to eventually pass to virtio functions.
  * @num_sgs: total number of entries in @sgs.
  * @cur_sg: next entry in @sgs to be used.
+ * @framevecs: Array of *struct frame_vector that is allocated to keep user
+ *             pages pinned until after a response is received. It is allocated
+ *             in scatterlist_builder_add_ext_ctrls_userptrs() and freed in
+ *             scatterlist_builder_retrieve_ext_ctrls().
+ * @cur_framevec: next entry in @framevecs to be used.
  *
  * Virtio passes data from the driver to the device (through e.g.
  * virtqueue_add_sgs()) via a scatterlist that the device interprets as a
@@ -69,6 +74,10 @@ struct scatterlist_builder {
 	struct scatterlist **sgs;
 	size_t num_sgs;
 	size_t cur_sg;
+
+	struct frame_vector **framevecs;
+	size_t num_framevecs;
+	size_t cur_framevec;
 };
 
 int scatterlist_builder_add_descriptor(struct scatterlist_builder *builder,
@@ -87,4 +96,22 @@ int scatterlist_builder_add_ioctl_cmd(struct scatterlist_builder *builder,
 int scatterlist_builder_add_ioctl_resp(struct scatterlist_builder *builder,
 				       struct virtio_media_session *session);
 
+int scatterlist_builder_add_ext_ctrls(struct scatterlist_builder *builder,
+				      struct v4l2_ext_controls *ctrls);
+
+int
+scatterlist_builder_allocate_framevecs(struct scatterlist_builder *builder,
+				       struct v4l2_ext_controls *ctrls);
+
+void
+scatterlist_builder_free_framevecs(struct scatterlist_builder *builder);
+
+int
+scatterlist_builder_add_ext_ctrls_userptrs(struct scatterlist_builder *builder,
+					   struct v4l2_ext_controls *ctrls);
+
+int scatterlist_builder_retrieve_ext_ctrls(struct scatterlist_builder *builder,
+					   size_t sg_index,
+					   struct v4l2_ext_controls *ctrls);
+
 #endif // __VIRTIO_MEDIA_SCATTERLIST_BUILDER_H
diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/virtio/virtio_media_ioctls.c
index e92032bce..d0ea743e7 100644
--- a/drivers/media/virtio/virtio_media_ioctls.c
+++ b/drivers/media/virtio/virtio_media_ioctls.c
@@ -41,6 +41,8 @@ static int virtio_media_send_r_ioctl(struct v4l2_fh *fh, u32 ioctl,
 		.sgs = sgs,
 		.num_sgs = ARRAY_SIZE(sgs),
 		.cur_sg = 0,
+		.framevecs = NULL,
+		.cur_framevec = 0,
 	};
 
 	/* Command descriptor */
@@ -107,6 +109,8 @@ static int virtio_media_send_w_ioctl(struct v4l2_fh *fh, u32 ioctl,
 		.sgs = sgs,
 		.num_sgs = ARRAY_SIZE(sgs),
 		.cur_sg = 0,
+		.framevecs = NULL,
+		.cur_framevec = 0,
 	};
 
 	/* Command descriptor */
@@ -171,6 +175,8 @@ static int virtio_media_send_wr_ioctl(struct v4l2_fh *fh, u32 ioctl,
 		.sgs = sgs,
 		.num_sgs = ARRAY_SIZE(sgs),
 		.cur_sg = 0,
+		.framevecs = NULL,
+		.cur_framevec = 0,
 	};
 
 	/* Command descriptor */
@@ -215,6 +221,130 @@ static int virtio_media_send_wr_ioctl(struct v4l2_fh *fh, u32 ioctl,
 	return 0;
 }
 
+/**
+ * virtio_media_send_ext_controls_ioctl() - Send an ioctl taking extended
+ * controls as parameters to the device.
+ * @fh: file handler of the session doing the ioctl.
+ * @ioctl: ``VIDIOC_*`` ioctl code.
+ * @ctrls: &struct v4l2_ext_controls to be sent as the ioctl payload.
+ *
+ * Queues an ioctl that sends a &struct v4l2_ext_controls to the host and
+ * receives an updated version.
+ *
+ * &struct v4l2_ext_controls has a pointer to an array of
+ * &struct v4l2_ext_control, and also potentially pointers to user-space memory
+ * that we need to map properly, hence the dedicated function.
+ */
+static int virtio_media_send_ext_controls_ioctl(struct v4l2_fh *fh, u32 ioctl,
+						struct v4l2_ext_controls *ctrls)
+{
+	struct video_device *video_dev = fh->vdev;
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session = fh_to_session(fh);
+	size_t num_cmd_sgs;
+	size_t end_ctrls_sg;
+	struct v4l2_ext_control *controls_backup = ctrls->controls;
+	const u32 num_ctrls = ctrls->count;
+	struct scatterlist *sgs[64];
+	struct scatterlist_builder builder = {
+		.descs = session->command_sgs.sgl,
+		.num_descs = DESC_CHAIN_MAX_LEN,
+		.cur_desc = 0,
+		.shadow_buffer = session->shadow_buf,
+		.shadow_buffer_size = VIRTIO_SHADOW_BUF_SIZE,
+		.shadow_buffer_pos = 0,
+		.sgs = sgs,
+		.num_sgs = ARRAY_SIZE(sgs),
+		.cur_sg = 0,
+		.framevecs = NULL,
+		.cur_framevec = 0,
+	};
+	size_t resp_len = 0;
+	int i;
+
+	int ret = scatterlist_builder_allocate_framevecs(&builder, ctrls);
+
+	if (ret)
+		return ret;
+
+	/* Command descriptor */
+	ret = scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl);
+
+	if (ret)
+		goto free_framevecs;
+
+	/* v4l2_controls */
+	ret = scatterlist_builder_add_ext_ctrls(&builder, ctrls);
+	if (ret)
+		goto free_framevecs;
+
+	end_ctrls_sg = builder.cur_sg;
+
+	ret = scatterlist_builder_add_ext_ctrls_userptrs(&builder, ctrls);
+	if (ret)
+		goto free_framevecs;
+
+	num_cmd_sgs = builder.cur_sg;
+
+	/* Response descriptor */
+	ret = scatterlist_builder_add_ioctl_resp(&builder, session);
+	if (ret)
+		goto free_framevecs;
+
+	/* Response payload (same as input but without userptrs) */
+	for (i = 1; i < end_ctrls_sg; i++) {
+		ret = scatterlist_builder_add_descriptor(&builder, i);
+		if (ret < 0)
+			goto free_framevecs;
+	}
+
+	ret = virtio_media_send_command(vv, builder.sgs, num_cmd_sgs,
+					builder.cur_sg - num_cmd_sgs,
+					sizeof(struct virtio_media_resp_ioctl) +
+					sizeof(*ctrls),
+					&resp_len);
+
+	/* Just in case the host touched these. */
+	ctrls->controls = controls_backup;
+	if (ctrls->count != num_ctrls) {
+		v4l2_err(&vv->v4l2_dev,
+			 "device returned a number of controls different than the one submitted\n");
+	}
+	if (ctrls->count > num_ctrls)
+		return -ENOSPC;
+	if (ret < 0) {
+		/*
+		 * Even if we have received an error, we may need to read our
+		 * payloadback.
+		 */
+		if (resp_len >= sizeof(struct virtio_media_resp_ioctl) +
+		    sizeof(*ctrls)) {
+			/*
+			 * Deliberately ignore the error here as we want to
+			 * return the previous one.
+			 */
+			scatterlist_builder_retrieve_ext_ctrls(&builder,
+							       num_cmd_sgs + 1,
+							       ctrls);
+		}
+
+		goto free_framevecs;
+	}
+
+	resp_len -= sizeof(struct virtio_media_resp_ioctl);
+
+	/* Make sure that the reply's length covers our v4l2_ext_controls */
+	if (resp_len < sizeof(*ctrls))
+		return -EINVAL;
+
+	ret = scatterlist_builder_retrieve_ext_ctrls(&builder, num_cmd_sgs + 1,
+						     ctrls);
+
+free_framevecs:
+	scatterlist_builder_free_framevecs(&builder);
+	return ret;
+}
+
 /*
  * Macros suitable for defining ioctls with a constant size payload.
  */
@@ -327,6 +457,37 @@ static int virtio_media_querycap(struct file *file, void *fh,
 	return 0;
 }
 
+/*
+ * Extended control ioctls are handled mostly identically.
+ */
+
+static int virtio_media_g_ext_ctrls(struct file *file, void *fh,
+				    struct v4l2_ext_controls *ctrls)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+
+	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_G_EXT_CTRLS,
+						    ctrls);
+}
+
+static int virtio_media_s_ext_ctrls(struct file *file, void *fh,
+				    struct v4l2_ext_controls *ctrls)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+
+	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_S_EXT_CTRLS,
+						    ctrls);
+}
+
+static int virtio_media_try_ext_ctrls(struct file *file, void *fh,
+				      struct v4l2_ext_controls *ctrls)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+
+	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_TRY_EXT_CTRLS,
+						    ctrls);
+}
+
 /*
  * s/g_input/output work with an unsigned int - recast this to a u32 so the
  * size is unambiguous.
@@ -472,6 +633,9 @@ const struct v4l2_ioctl_ops virtio_media_ioctl_ops = {
 
 	/* Control handling */
 	.vidioc_query_ext_ctrl = virtio_media_query_ext_ctrl,
+	.vidioc_g_ext_ctrls = virtio_media_g_ext_ctrls,
+	.vidioc_s_ext_ctrls = virtio_media_s_ext_ctrls,
+	.vidioc_try_ext_ctrls = virtio_media_try_ext_ctrls,
 	.vidioc_querymenu = virtio_media_querymenu,
 
 	/* Audio ioctls */
diff --git a/include/uapi/linux/virtio_media.h b/include/uapi/linux/virtio_media.h
index c1e68d47c..f117b97fc 100644
--- a/include/uapi/linux/virtio_media.h
+++ b/include/uapi/linux/virtio_media.h
@@ -158,4 +158,17 @@ struct virtio_media_resp_ioctl {
 	struct virtio_media_resp_header hdr;
 };
 
+/**
+ * struct virtio_media_sg_entry - Description of part of a scattered guest
+ *                                memory.
+ * @start: start guest address of the memory segment.
+ * @len: length of this memory segment.
+ * @__reserved: must be set to zero by the driver.
+ */
+struct virtio_media_sg_entry {
+	__le64 start;
+	__le32 len;
+	__le32 __reserved;
+};
+
 #endif // _UAPI__LINUX_VIRTIO_MEDIA_H
-- 
2.56.1.750.gf70dc682cf-goog


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

* [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll
  2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
                   ` (2 preceding siblings ...)
  2026-11-20 21:59 ` [PATCH v11 3/6] media: virtio: Add extended controls support Brian Daniels
@ 2026-11-20 21:59 ` Brian Daniels
  2026-11-20 22:21   ` sashiko-bot
  2026-11-20 21:59 ` [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support Brian Daniels
  2026-11-20 21:59 ` [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack Brian Daniels
  5 siblings, 1 reply; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Brian Daniels

From: Alexandre Courbot <gnurou@gmail.com>

Add V4L2 buffer queue state tracking, streaming ioctls, asynchronous
event virtqueue processing, V4L2 event subscription, and poll support.

Set up the event virtqueue to receive VIRTIO_MEDIA_EVT_DQBUF,
VIRTIO_MEDIA_EVT_EVENT, and VIRTIO_MEDIA_EVT_ERROR notifications from
the host, dispatching dequeued buffers, V4L2 events, and unrecoverable
session errors to their respective sessions.

Implement buffer and streaming ioctls (VIDIOC_REQBUFS,
VIDIOC_CREATE_BUFS, VIDIOC_QUERYBUF, VIDIOC_PREPARE_BUF, VIDIOC_QBUF,
VIDIOC_DQBUF, VIDIOC_STREAMON, VIDIOC_STREAMOFF, and VIDIOC_DECODER_CMD)
as well as VIDIOC_SUBSCRIBE_EVENT, VIDIOC_UNSUBSCRIBE_EVENT, and the
poll file operation.

Signed-off-by: Alexandre Courbot <gnurou@gmail.com>
Assisted-by: LLM
Co-developed-by: Brian Daniels <briandaniels@google.com>
Signed-off-by: Brian Daniels <briandaniels@google.com>
---
 drivers/media/virtio/scatterlist_builder.c |  72 +++
 drivers/media/virtio/scatterlist_builder.h |   8 +
 drivers/media/virtio/session.h             |  51 ++
 drivers/media/virtio/virtio_media.h        |  11 +
 drivers/media/virtio/virtio_media_driver.c | 396 ++++++++++++-
 drivers/media/virtio/virtio_media_ioctls.c | 618 ++++++++++++++++++++-
 include/uapi/linux/virtio_media.h          |  68 +++
 7 files changed, 1218 insertions(+), 6 deletions(-)

diff --git a/drivers/media/virtio/scatterlist_builder.c b/drivers/media/virtio/scatterlist_builder.c
index 63d50369f..a4eabc932 100644
--- a/drivers/media/virtio/scatterlist_builder.c
+++ b/drivers/media/virtio/scatterlist_builder.c
@@ -356,6 +356,78 @@ static int scatterlist_builder_add_userptr(struct scatterlist_builder *builder,
 	return 0;
 }
 
+/**
+ * scatterlist_builder_add_buffer() - Add a &struct v4l2_buffer and its planes
+ *                                    to the descriptor chain.
+ * @builder: builder to use.
+ * @b: &struct v4l2_buffer to add.
+ */
+int scatterlist_builder_add_buffer(struct scatterlist_builder *builder,
+				   struct v4l2_buffer *b)
+{
+	int ret;
+
+	/* v4l2_buffer */
+	ret = scatterlist_builder_add_data(builder, b, sizeof(*b));
+	if (ret)
+		return ret;
+
+	if (V4L2_TYPE_IS_MULTIPLANAR(b->type) && b->length > 0) {
+		/* Array of v4l2_planes */
+		ret = scatterlist_builder_add_data(builder, b->m.planes,
+						   sizeof(struct v4l2_plane) *
+							   b->length);
+		if (ret)
+			return ret;
+	}
+
+	return 0;
+}
+
+/**
+ * scatterlist_builder_retrieve_buffer() - Retrieve a &struct v4l2_buffer
+ *                                         written by the device on the shadow
+ *                                         buffer, if needed.
+ * @builder: builder to use.
+ * @sg_index: index of the first SG entry of the buffer in the builder's
+ *            descriptor chain.
+ * @b: &struct v4l2_buffer to copy shadow buffer data into.
+ * @orig_planes: the original ``planes`` pointer, to be restored if the buffer
+ *               is multi-planar.
+ *
+ * If the &struct v4l2_buffer pointed to by @sg_index was copied into the
+ * shadow buffer, then its updated content is copied back into @b.
+ * Otherwise nothing is done as the device has written into @b directly.
+ *
+ * @orig_planes is used to restore the original ``planes`` pointer in case it
+ * gets modified by the host. The specification stipulates that the host should
+ * not modify it, but we enforce this for additional safety.
+ */
+int scatterlist_builder_retrieve_buffer(struct scatterlist_builder *builder,
+					size_t sg_index, struct v4l2_buffer *b,
+					struct v4l2_plane *orig_planes)
+{
+	int ret;
+
+	ret = scatterlist_builder_retrieve_data(builder, sg_index++, b);
+	if (ret)
+		return ret;
+
+	if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
+		b->m.planes = orig_planes;
+
+		if (orig_planes) {
+			ret = scatterlist_builder_retrieve_data(builder,
+								sg_index++,
+								b->m.planes);
+			if (ret)
+				return ret;
+		}
+	}
+
+	return 0;
+}
+
 /**
  * scatterlist_builder_add_ext_ctrls() - Add a &struct v4l2_ext_controls and its
  *                                       controls to @builder.
diff --git a/drivers/media/virtio/scatterlist_builder.h b/drivers/media/virtio/scatterlist_builder.h
index bced1e030..f63daca33 100644
--- a/drivers/media/virtio/scatterlist_builder.h
+++ b/drivers/media/virtio/scatterlist_builder.h
@@ -96,6 +96,14 @@ int scatterlist_builder_add_ioctl_cmd(struct scatterlist_builder *builder,
 int scatterlist_builder_add_ioctl_resp(struct scatterlist_builder *builder,
 				       struct virtio_media_session *session);
 
+int scatterlist_builder_add_buffer(struct scatterlist_builder *builder,
+				   struct v4l2_buffer *buffer);
+
+int scatterlist_builder_retrieve_buffer(struct scatterlist_builder *builder,
+					size_t sg_index,
+					struct v4l2_buffer *buffer,
+					struct v4l2_plane *orig_planes);
+
 int scatterlist_builder_add_ext_ctrls(struct scatterlist_builder *builder,
 				      struct v4l2_ext_controls *ctrls);
 
diff --git a/drivers/media/virtio/session.h b/drivers/media/virtio/session.h
index 6fe7ff5ae..16bb86bf4 100644
--- a/drivers/media/virtio/session.h
+++ b/drivers/media/virtio/session.h
@@ -14,17 +14,55 @@
 
 #include "uapi/linux/virtio_media.h"
 
+#define VIRTIO_MEDIA_LAST_QUEUE (V4L2_BUF_TYPE_META_OUTPUT)
+
 /*
  * Size of the per-session virtio shadow and event buffers. 16K should be
  * enough to contain everything we need.
  */
 #define VIRTIO_SHADOW_BUF_SIZE 0x4000
 
+/**
+ * struct virtio_media_buffer - Current state of a buffer.
+ * @buffer: &struct v4l2_buffer with current information about the buffer.
+ * @planes: backing planes array for @buffer.
+ * @list: link into the list of buffers pending dequeue.
+ */
+struct virtio_media_buffer {
+	struct v4l2_buffer buffer;
+	struct v4l2_plane planes[VIDEO_MAX_PLANES];
+	struct list_head list;
+};
+
+/**
+ * struct virtio_media_queue_state - Represents the state of a V4L2 queue.
+ * @streaming: Whether the queue is currently streaming.
+ * @allocated_bufs: How many buffers are currently allocated.
+ * @is_capture_last: set to true when the last buffer has been received on a
+ *                   capture queue, so we can return %-EPIPE on subsequent
+ *                   DQBUF requests.
+ * @buffers: Buffer state array of size @allocated_bufs.
+ * @queued_bufs: How many buffers are currently queued on the device.
+ * @pending_dqbufs: Buffers that are available for being dequeued.
+ */
+struct virtio_media_queue_state {
+	bool streaming;
+	size_t allocated_bufs;
+	bool is_capture_last;
+
+	struct virtio_media_buffer *buffers;
+	size_t queued_bufs;
+	struct list_head pending_dqbufs;
+};
+
 /**
  * struct virtio_media_session - A session on a virtio_media device.
  * @fh: file handler for the session.
  * @file: file pointer associated with the session's file handler.
  * @id: session ID used to communicate with the device.
+ * @nonblocking_dequeue: whether dequeue should block or not (nonblocking if
+ *                       file opened with O_NONBLOCK).
+ * @uses_mplane: whether the queues for this session use the MPLANE API or not.
  * @cmd: union of session commands ``close`` and ``ioctl``. A session can have
  *       one command currently running. The rest of the commands are handled by
  *       &struct virtio_media.
@@ -35,12 +73,19 @@
  *              be staged before being sent to the device.
  * @command_sgs: SG table gathering descriptors for a given command and its
  *               response.
+ * @queues: state of all the queues for this session.
+ * @queues_lock: protects all members for the queues for this session.
+ * @dqbuf_wait: waitqueue for dequeued buffers, if ``VIDIOC_DQBUF`` needs to
+ *              block or when polling.
+ * @error: true if the session has encountered an unrecoverable session error.
  * @list: link into the list of sessions for the device.
  */
 struct virtio_media_session {
 	struct v4l2_fh fh;
 	struct file *file;
 	u32 id;
+	bool nonblocking_dequeue;
+	bool uses_mplane;
 
 	__dma_from_device_group_begin();
 	union {
@@ -57,6 +102,12 @@ struct virtio_media_session {
 
 	struct sg_table command_sgs;
 
+	struct virtio_media_queue_state queues[VIRTIO_MEDIA_LAST_QUEUE + 1];
+	struct mutex queues_lock; /* protects queues array and states */
+	wait_queue_head_t dqbuf_wait;
+	bool error;
+	struct mutex error_lock; /* protects error */
+
 	struct list_head list;
 };
 
diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/virtio_media.h
index a120c1014..8b21c1941 100644
--- a/drivers/media/virtio/virtio_media.h
+++ b/drivers/media/virtio/virtio_media.h
@@ -24,8 +24,12 @@
  * @video_dev: video_device for the media device.
  * @virtio_dev: virtio device for the media device.
  * @commandq: virtio command queue.
+ * @eventq: virtio event queue.
+ * @eventq_work: work to run when events are received on @eventq.
+ * @event_buffer: buffer for event descriptors.
  * @sessions: list of active sessions on the device.
  * @sessions_lock: protects @sessions and &struct virtio_media_session.list.
+ * @events_lock: prevents concurrent processing of events.
  * @cmd: union of device-level commands. Session commands are handled by
  *       &struct virtio_media_session.
  * @resp: union of responses to device-level commands. Session responses are
@@ -39,10 +43,16 @@ struct virtio_media {
 
 	struct virtio_device *virtio_dev;
 	struct virtqueue *commandq;
+	struct virtqueue *eventq;
+	struct work_struct eventq_work;
+
+	void *event_buffer;
 
 	struct list_head sessions;
 	struct mutex sessions_lock; /* protects sessions list */
 
+	struct mutex events_lock; /* prevents concurrent event processing */
+
 	__dma_from_device_group_begin();
 	union {
 		struct virtio_media_cmd_open open;
@@ -68,6 +78,7 @@ to_virtio_media(struct video_device *video_dev)
 int virtio_media_send_command(struct virtio_media *vv, struct scatterlist **sgs,
 			      const size_t out_sgs, const size_t in_sgs,
 			      size_t minimum_resp_len, size_t *resp_len);
+void virtio_media_process_events(struct virtio_media *vv);
 
 /* virtio_media_ioctls.c */
 
diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
index 0fe20cf50..748357725 100644
--- a/drivers/media/virtio/virtio_media_driver.c
+++ b/drivers/media/virtio/virtio_media_driver.c
@@ -16,15 +16,22 @@
 #include <linux/virtio_ids.h>
 #include <linux/slab.h>
 #include <linux/scatterlist.h>
+#include <linux/vmalloc.h>
+#include <linux/workqueue.h>
+#include <linux/dma-mapping.h>
+#include <linux/poll.h>
 
 #include <media/v4l2-dev.h>
 #include <media/v4l2-device.h>
 #include <media/v4l2-fh.h>
+#include <media/v4l2-event.h>
 
 #include "uapi/linux/virtio_media.h"
 #include "session.h"
 #include "virtio_media.h"
 
+#define VIRTIO_MEDIA_NUM_EVENT_BUFS 16
+
 /**
  * virtio_media_session_alloc() - Allocate a new session.
  * @vv: virtio-media device the session belongs to.
@@ -37,6 +44,7 @@ static struct virtio_media_session *
 virtio_media_session_alloc(struct virtio_media *vv, struct file *file)
 {
 	struct virtio_media_session *session;
+	int i;
 	int ret;
 
 	session = kzalloc_obj(*session, GFP_KERNEL);
@@ -54,11 +62,20 @@ virtio_media_session_alloc(struct virtio_media *vv, struct file *file)
 
 	// The caller is expected to set the ID once the host assigns a value.
 	session->id = 0;
+	session->nonblocking_dequeue = file->f_flags & O_NONBLOCK;
 
 	INIT_LIST_HEAD(&session->list);
 	v4l2_fh_init(&session->fh, &vv->video_dev);
 	virtio_media_session_fh_add(session, file);
 
+	for (i = 0; i <= VIRTIO_MEDIA_LAST_QUEUE; i++)
+		INIT_LIST_HEAD(&session->queues[i].pending_dqbufs);
+	mutex_init(&session->queues_lock);
+
+	init_waitqueue_head(&session->dqbuf_wait);
+
+	mutex_init(&session->error_lock);
+
 	return session;
 
 err_payload_sgs:
@@ -91,11 +108,16 @@ static void virtio_media_session_add(struct virtio_media *vv,
  */
 static void virtio_media_session_free(struct virtio_media_session *session)
 {
+	int i;
+
 	virtio_media_session_fh_del(session);
 	v4l2_fh_exit(&session->fh);
 
 	sg_free_table(&session->command_sgs);
 
+	for (i = 0; i <= VIRTIO_MEDIA_LAST_QUEUE; i++)
+		vfree(session->queues[i].buffers);
+
 	kfree(session->shadow_buf);
 	kfree(session);
 }
@@ -152,6 +174,31 @@ static int virtio_media_session_close(struct virtio_media *vv,
 	return 0;
 }
 
+/**
+ * virtio_media_find_session() - Look up a session with a given ID.
+ * @vv: virtio-media device to lookup the session from.
+ * @id: ID of the session to lookup.
+ */
+static struct virtio_media_session *
+virtio_media_find_session(struct virtio_media *vv, u32 id)
+{
+	struct list_head *p;
+	struct virtio_media_session *session = NULL;
+
+	mutex_lock(&vv->sessions_lock);
+	list_for_each(p, &vv->sessions) {
+		struct virtio_media_session *s =
+			list_entry(p, struct virtio_media_session, list);
+		if (s->id == id) {
+			session = s;
+			break;
+		}
+	}
+	mutex_unlock(&vv->sessions_lock);
+
+	return session;
+}
+
 /**
  * struct virtio_media_cmd_callback_param - Callback parameters to the virtio
  *                                          command queue.
@@ -290,6 +337,234 @@ int virtio_media_send_command(struct virtio_media *vv, struct scatterlist **sgs,
 	return 0;
 }
 
+/**
+ * virtio_media_send_event_buffer() - Sends an event buffer to the host so it
+ * can return it with an event.
+ * @vv: virtio-media device in use.
+ * @event_buffer: pointer to the event buffer to send to the device.
+ */
+static int virtio_media_send_event_buffer(struct virtio_media *vv,
+					  void *event_buffer)
+{
+	struct scatterlist *sgs[1], vresp;
+	int ret;
+
+	sg_init_one(&vresp, event_buffer, VIRTIO_MEDIA_EVENT_MAX_SIZE);
+	sgs[0] = &vresp;
+
+	ret = virtqueue_add_sgs(vv->eventq, sgs, 0, 1, event_buffer,
+				GFP_ATOMIC);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to add sgs to event virtqueue\n");
+		return ret;
+	}
+
+	if (!virtqueue_kick(vv->eventq)) {
+		v4l2_err(&vv->v4l2_dev, "failed to kick event virtqueue\n");
+		return -EINVAL;
+	}
+
+	return 0;
+}
+
+/**
+ * eventq_callback() - Callback for the event queue.
+ * @queue: event virtqueue.
+ *
+ * This just schedules for event work to be run.
+ */
+static void eventq_callback(struct virtqueue *queue)
+{
+	struct virtio_media *vv = queue->vdev->priv;
+
+	schedule_work(&vv->eventq_work);
+}
+
+/**
+ * virtio_media_process_dqbuf_event() - Process a dequeued event for a session.
+ * @vv: virtio-media device in use.
+ * @session: session the event is addressed to.
+ * @dqbuf_evt: the dequeued event to process.
+ *
+ * Invalid events are ignored with an error log.
+ */
+static void
+virtio_media_process_dqbuf_event(struct virtio_media *vv,
+				 struct virtio_media_session *session,
+				 struct virtio_media_event_dqbuf *dqbuf_evt)
+{
+	struct virtio_media_buffer *dqbuf;
+	const enum v4l2_buf_type queue_type = dqbuf_evt->buffer.type;
+	struct virtio_media_queue_state *queue;
+	typeof(dqbuf->buffer.m) buffer_m;
+	typeof(dqbuf->buffer.m.planes[0].m) plane_m;
+	int i;
+
+	if (queue_type >= ARRAY_SIZE(session->queues)) {
+		v4l2_err(&vv->v4l2_dev,
+			 "unmanaged queue %d passed to dqbuf event",
+			 dqbuf_evt->buffer.type);
+		return;
+	}
+	queue = &session->queues[queue_type];
+
+	if (dqbuf_evt->buffer.index >= queue->allocated_bufs) {
+		v4l2_err(&vv->v4l2_dev,
+			 "invalid buffer ID %d for queue %d in dqbuf event",
+			 dqbuf_evt->buffer.index, dqbuf_evt->buffer.type);
+		return;
+	}
+
+	dqbuf = &queue->buffers[dqbuf_evt->buffer.index];
+
+	/*
+	 * Preserve the 'm' union that was passed to us during QBUF so userspace
+	 * gets back the information it submitted.
+	 */
+	buffer_m = dqbuf->buffer.m;
+	memcpy(&dqbuf->buffer, &dqbuf_evt->buffer, sizeof(dqbuf->buffer));
+	dqbuf->buffer.m = buffer_m;
+	if (V4L2_TYPE_IS_MULTIPLANAR(dqbuf->buffer.type)) {
+		if (dqbuf->buffer.length > VIDEO_MAX_PLANES) {
+			v4l2_err(&vv->v4l2_dev,
+				 "invalid number of planes received from host for a multiplanar buffer\n");
+			return;
+		}
+		for (i = 0; i < dqbuf->buffer.length; i++) {
+			plane_m = dqbuf->planes[i].m;
+			memcpy(&dqbuf->planes[i], &dqbuf_evt->planes[i],
+			       sizeof(struct v4l2_plane));
+			dqbuf->planes[i].m = plane_m;
+		}
+	}
+
+	/* Set the DONE flag as the buffer is waiting to be dequeued. */
+	dqbuf->buffer.flags |= V4L2_BUF_FLAG_DONE;
+
+	mutex_lock(&session->queues_lock);
+	list_add_tail(&dqbuf->list, &queue->pending_dqbufs);
+	queue->queued_bufs -= 1;
+	mutex_unlock(&session->queues_lock);
+
+	wake_up(&session->dqbuf_wait);
+}
+
+/**
+ * virtio_media_process_events() - Process all pending events on a device.
+ * @vv: device whose pending events we want to process.
+ *
+ * Retrieves all pending events on @vv's event queue and dispatches them to
+ * their corresponding session.
+ *
+ * Invalid events are ignored with an error log.
+ */
+void virtio_media_process_events(struct virtio_media *vv)
+{
+	struct virtio_media_event_error *error_evt;
+	struct virtio_media_event_dqbuf *dqbuf_evt;
+	struct virtio_media_event_event *event_evt;
+	struct virtio_media_session *session;
+	struct virtio_media_event_header *evt;
+	unsigned int len;
+
+	mutex_lock(&vv->events_lock);
+
+process_bufs:
+	while ((evt = virtqueue_get_buf(vv->eventq, &len))) {
+		/* Make sure we received enough data */
+		if (len < sizeof(*evt)) {
+			v4l2_err(&vv->v4l2_dev,
+				 "event is too short: got %u, expected at least %zu\n",
+				 len, sizeof(*evt));
+			goto end_of_event;
+		}
+
+		session = virtio_media_find_session(vv, evt->session_id);
+		if (!session) {
+			v4l2_err(&vv->v4l2_dev, "cannot find session %d\n",
+				 evt->session_id);
+			goto end_of_event;
+		}
+
+		switch (evt->event) {
+		case VIRTIO_MEDIA_EVT_ERROR:
+			if (len < sizeof(*error_evt)) {
+				v4l2_err(&vv->v4l2_dev,
+					 "error event is too short: got %u, expected %zu\n",
+					 len, sizeof(*error_evt));
+				break;
+			}
+			error_evt = (struct virtio_media_event_error *)evt;
+			v4l2_err(&vv->v4l2_dev,
+				 "received error %d for session %d",
+				 error_evt->error, error_evt->hdr.session_id);
+
+			mutex_lock(&session->error_lock);
+			session->error = true;
+			mutex_unlock(&session->error_lock);
+
+			virtio_media_session_close(vv, session);
+
+			/* Wake up any waiting dqbuf requests */
+			wake_up(&session->dqbuf_wait);
+
+			break;
+
+		/*
+		 * Dequeued buffer: put it into the right queue so user-space
+		 * can dequeue it.
+		 */
+		case VIRTIO_MEDIA_EVT_DQBUF:
+			if (len < sizeof(*dqbuf_evt)) {
+				v4l2_err(&vv->v4l2_dev,
+					 "dqbuf event is too short: got %u, expected %zu\n",
+					 len, sizeof(*dqbuf_evt));
+				break;
+			}
+			dqbuf_evt = (struct virtio_media_event_dqbuf *)evt;
+			virtio_media_process_dqbuf_event(vv, session,
+							 dqbuf_evt);
+			break;
+
+		case VIRTIO_MEDIA_EVT_EVENT:
+			if (len < sizeof(*event_evt)) {
+				v4l2_err(&vv->v4l2_dev,
+					 "session event is too short: got %u expected %zu\n",
+					 len, sizeof(*event_evt));
+				break;
+			}
+
+			event_evt = (struct virtio_media_event_event *)evt;
+			v4l2_event_queue_fh(&session->fh, &event_evt->event);
+			break;
+
+		default:
+			v4l2_err(&vv->v4l2_dev, "unknown event type %d\n",
+				 evt->event);
+			break;
+		}
+
+end_of_event:
+		virtio_media_send_event_buffer(vv, evt);
+	}
+
+	if (!virtqueue_enable_cb(vv->eventq)) {
+		virtqueue_disable_cb(vv->eventq);
+		goto process_bufs;
+	}
+
+	mutex_unlock(&vv->events_lock);
+}
+
+static void virtio_media_event_work(struct work_struct *work)
+{
+	struct virtio_media *vv =
+		container_of(work, struct virtio_media, eventq_work);
+
+	virtio_media_process_events(vv);
+}
+
 /**
  * virtio_media_device_open() - Create a new session from an opened file.
  * @file: opened file for the session.
@@ -350,7 +625,16 @@ static int virtio_media_device_close(struct file *file)
 	struct virtio_media_session *session =
 		fh_to_session(file->private_data);
 
-	int ret = virtio_media_session_close(vv, session);
+	mutex_lock(&session->error_lock);
+	bool session_error = session->error;
+
+	mutex_unlock(&session->error_lock);
+
+	int ret = 0;
+
+	/* If session is in an error state, then it has already been closed */
+	if (!session_error)
+		ret = virtio_media_session_close(vv, session);
 
 	virtio_media_session_remove(vv, session);
 	virtio_media_session_free(session);
@@ -358,10 +642,66 @@ static int virtio_media_device_close(struct file *file)
 	return ret;
 }
 
+/**
+ * virtio_media_device_poll() - Poll logic for a virtio-media device.
+ * @file: file of the session to poll.
+ * @wait: poll table to wait on.
+ */
+static __poll_t virtio_media_device_poll(struct file *file, poll_table *wait)
+{
+	struct virtio_media_session *session =
+		fh_to_session(file->private_data);
+	enum v4l2_buf_type capture_type =
+		session->uses_mplane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE :
+				       V4L2_BUF_TYPE_VIDEO_CAPTURE;
+	enum v4l2_buf_type output_type =
+		session->uses_mplane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE :
+				       V4L2_BUF_TYPE_VIDEO_OUTPUT;
+	struct virtio_media_queue_state *capture_queue =
+		&session->queues[capture_type];
+	struct virtio_media_queue_state *output_queue =
+		&session->queues[output_type];
+	__poll_t req_events = poll_requested_events(wait);
+	__poll_t rc = 0;
+
+	poll_wait(file, &session->dqbuf_wait, wait);
+	poll_wait(file, &session->fh.wait, wait);
+
+	mutex_lock(&session->error_lock);
+	if (session->error)
+		rc |= EPOLLERR;
+	mutex_unlock(&session->error_lock);
+
+	mutex_lock(&session->queues_lock);
+	if (req_events & (EPOLLIN | EPOLLRDNORM)) {
+		if (!capture_queue->streaming ||
+		    (capture_queue->queued_bufs == 0 &&
+		     list_empty(&capture_queue->pending_dqbufs)))
+			rc |= EPOLLERR;
+		else if (!list_empty(&capture_queue->pending_dqbufs) ||
+			 capture_queue->is_capture_last)
+			rc |= EPOLLIN | EPOLLRDNORM;
+	}
+	if (req_events & (EPOLLOUT | EPOLLWRNORM)) {
+		if (!output_queue->streaming)
+			rc |= EPOLLERR;
+		else if (output_queue->queued_bufs <
+			 output_queue->allocated_bufs)
+			rc |= EPOLLOUT | EPOLLWRNORM;
+	}
+	mutex_unlock(&session->queues_lock);
+
+	if (v4l2_event_pending(&session->fh))
+		rc |= EPOLLPRI;
+
+	return rc;
+}
+
 static const struct v4l2_file_operations virtio_media_fops = {
 	.owner = THIS_MODULE,
 	.open = virtio_media_device_open,
 	.release = virtio_media_device_close,
+	.poll = virtio_media_device_poll,
 	.unlocked_ioctl = virtio_media_device_ioctl,
 };
 
@@ -371,29 +711,47 @@ static void virtio_media_release(struct v4l2_device *v4l2_dev)
 		container_of(v4l2_dev, struct virtio_media, v4l2_dev);
 
 	v4l2_device_unregister(&vv->v4l2_dev);
+	kfree(vv->event_buffer);
 	kfree(vv);
 }
 
 static int virtio_media_probe(struct virtio_device *virtio_dev)
 {
 	struct device *dev = &virtio_dev->dev;
-	struct virtqueue *vqs[1];
-	static struct virtqueue_info vq_info[1] = {
+	struct virtqueue *vqs[2];
+	static struct virtqueue_info vq_info[2] = {
 		{
 			.name = "command",
 			.callback = commandq_callback,
 		},
+		{
+			.name = "event",
+			.callback = eventq_callback,
+		},
 	};
 	struct virtio_media *vv;
 	struct video_device *vd;
+	int i;
 	int ret;
 
 	vv = kzalloc_obj(struct virtio_media);
 	if (!vv)
 		return -ENOMEM;
 
+	const size_t virtio_media_event_aligned_size =
+		ALIGN(VIRTIO_MEDIA_EVENT_MAX_SIZE, dma_get_cache_alignment());
+
+	vv->event_buffer = kzalloc(virtio_media_event_aligned_size *
+				   VIRTIO_MEDIA_NUM_EVENT_BUFS,
+				   GFP_KERNEL);
+	if (!vv->event_buffer) {
+		ret = -ENOMEM;
+		goto err_free_virtio_media;
+	}
+
 	INIT_LIST_HEAD(&vv->sessions);
 	mutex_init(&vv->sessions_lock);
+	mutex_init(&vv->events_lock);
 	mutex_init(&vv->vlock);
 
 	vv->virtio_dev = virtio_dev;
@@ -403,15 +761,17 @@ static int virtio_media_probe(struct virtio_device *virtio_dev)
 
 	ret = v4l2_device_register(dev, &vv->v4l2_dev);
 	if (ret)
-		goto err_free_virtio_media;
+		goto err_free_event_buffer;
 
 	vv->v4l2_dev.release = virtio_media_release;
 
-	ret = virtio_find_vqs(virtio_dev, 1, vqs, vq_info, NULL);
+	ret = virtio_find_vqs(virtio_dev, 2, vqs, vq_info, NULL);
 	if (ret)
 		goto err_v4l2_device_unregister;
 
 	vv->commandq = vqs[0];
+	vv->eventq = vqs[1];
+	INIT_WORK(&vv->eventq_work, virtio_media_event_work);
 
 	vd = &vv->video_dev;
 	vd->v4l2_dev = &vv->v4l2_dev;
@@ -449,13 +809,34 @@ static int virtio_media_probe(struct virtio_device *virtio_dev)
 	if (ret)
 		goto err_del_vqs;
 
+	mutex_lock(&vv->events_lock);
+
+	for (i = 0; i < VIRTIO_MEDIA_NUM_EVENT_BUFS; i++) {
+		void *ebuf = vv->event_buffer +
+			     virtio_media_event_aligned_size * i;
+
+		ret = virtio_media_send_event_buffer(vv, ebuf);
+		if (ret)
+			break;
+	}
+
+	mutex_unlock(&vv->events_lock);
+
+	if (ret)
+		goto err_video_unregister_device;
+
 	return 0;
 
+err_video_unregister_device:
+	video_unregister_device(&vv->video_dev);
 err_del_vqs:
+	cancel_work_sync(&vv->eventq_work);
 	virtio_reset_device(virtio_dev);
 	virtio_dev->config->del_vqs(virtio_dev);
 err_v4l2_device_unregister:
 	v4l2_device_unregister(&vv->v4l2_dev);
+err_free_event_buffer:
+	kfree(vv->event_buffer);
 err_free_virtio_media:
 	kfree(vv);
 	return ret;
@@ -469,6 +850,9 @@ static void virtio_media_remove(struct virtio_device *virtio_dev)
 	/* Remove the video device to stop accessing the commandq virtqueue */
 	video_unregister_device(&vv->video_dev);
 
+	/* Stop event handling work queue from accessing eventq virtqueue */
+	cancel_work_sync(&vv->eventq_work);
+
 	/*
 	 * Acquire vlock to ensure no concurrent accesses to the commandq
 	 * virtqueue
@@ -484,6 +868,8 @@ static void virtio_media_remove(struct virtio_device *virtio_dev)
 	 */
 	while (virtqueue_detach_unused_buf(vv->commandq))
 		;
+	while (virtqueue_detach_unused_buf(vv->eventq))
+		;
 
 	/* Delete the virtqueues */
 	virtio_dev->config->del_vqs(virtio_dev);
diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/virtio/virtio_media_ioctls.c
index d0ea743e7..aa56efe9a 100644
--- a/drivers/media/virtio/virtio_media_ioctls.c
+++ b/drivers/media/virtio/virtio_media_ioctls.c
@@ -9,6 +9,8 @@
 #include <linux/mutex.h>
 #include <linux/videodev2.h>
 #include <linux/virtio_config.h>
+#include <linux/vmalloc.h>
+#include <media/v4l2-event.h>
 #include <media/v4l2-ioctl.h>
 
 #include "scatterlist_builder.h"
@@ -221,6 +223,101 @@ static int virtio_media_send_wr_ioctl(struct v4l2_fh *fh, u32 ioctl,
 	return 0;
 }
 
+/**
+ * virtio_media_send_buffer_ioctl() - Send an ioctl taking a buffer as
+ * parameter to the device.
+ * @fh: file handler of the session doing the ioctl.
+ * @ioctl: ``VIDIOC_*`` ioctl code.
+ * @b: &struct v4l2_buffer to be sent as the ioctl payload.
+ *
+ * Buffers can require an additional descriptor to send their planes array, and
+ * can have pointers to userspace memory hence this dedicated function.
+ */
+static int virtio_media_send_buffer_ioctl(struct v4l2_fh *fh, u32 ioctl,
+					  struct v4l2_buffer *b)
+{
+	struct video_device *video_dev = fh->vdev;
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session = fh_to_session(fh);
+	struct v4l2_plane *orig_planes = NULL;
+	struct scatterlist *sgs[64];
+	/*
+	 * End of the device-readable buffer SGs, to reuse in device-writable
+	 * section.
+	 */
+	size_t num_cmd_sgs;
+	size_t end_buf_sg;
+	struct scatterlist_builder builder = {
+		.descs = session->command_sgs.sgl,
+		.num_descs = DESC_CHAIN_MAX_LEN,
+		.cur_desc = 0,
+		.shadow_buffer = session->shadow_buf,
+		.shadow_buffer_size = VIRTIO_SHADOW_BUF_SIZE,
+		.shadow_buffer_pos = 0,
+		.sgs = sgs,
+		.num_sgs = ARRAY_SIZE(sgs),
+		.cur_sg = 0,
+		.framevecs = NULL,
+	};
+	size_t resp_len;
+	int ret;
+	int i;
+
+	if (b->type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	if (V4L2_TYPE_IS_MULTIPLANAR(b->type))
+		orig_planes = b->m.planes;
+
+	/* Command descriptor */
+	ret = scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl);
+	if (ret)
+		return ret;
+
+	/* Command payload (struct v4l2_buffer) */
+	ret = scatterlist_builder_add_buffer(&builder, b);
+	if (ret < 0)
+		return ret;
+
+	end_buf_sg = builder.cur_sg;
+	num_cmd_sgs = builder.cur_sg;
+
+	/* Response descriptor */
+	ret = scatterlist_builder_add_ioctl_resp(&builder, session);
+	if (ret)
+		return ret;
+
+	/* Response payload (same as input, but no userptr mapping) */
+	for (i = 1; i < end_buf_sg; i++) {
+		ret = scatterlist_builder_add_descriptor(&builder, i);
+		if (ret < 0)
+			return ret;
+	}
+
+	ret = virtio_media_send_command(vv, builder.sgs, num_cmd_sgs,
+					builder.cur_sg - num_cmd_sgs,
+					sizeof(struct virtio_media_resp_ioctl) +
+					sizeof(*b), &resp_len);
+	if (ret < 0)
+		return ret;
+
+	resp_len -= sizeof(struct virtio_media_resp_ioctl);
+
+	/* Make sure that the reply length covers our v4l2_buffer */
+	if (resp_len < sizeof(*b))
+		return -EINVAL;
+
+	ret = scatterlist_builder_retrieve_buffer(&builder, num_cmd_sgs + 1, b,
+						  orig_planes);
+	if (ret) {
+		v4l2_err(&vv->v4l2_dev,
+			 "failed to retrieve response descriptor chain\n");
+		return ret;
+	}
+
+	return 0;
+}
+
 /**
  * virtio_media_send_ext_controls_ioctl() - Send an ioctl taking extended
  * controls as parameters to the device.
@@ -345,6 +442,41 @@ static int virtio_media_send_ext_controls_ioctl(struct v4l2_fh *fh, u32 ioctl,
 	return ret;
 }
 
+/**
+ * virtio_media_clear_queue() - clear all pending buffers on a streamed-off
+ *                              queue.
+ * @session: session which the queue to clear belongs to.
+ * @queue: state of the queue to clear.
+ *
+ * Helper function to clear the list of buffers waiting to be dequeued on a
+ * queue that has just been streamed off.
+ */
+static void virtio_media_clear_queue(struct virtio_media_session *session,
+				     struct virtio_media_queue_state *queue)
+{
+	struct list_head *p, *n;
+	int i;
+
+	mutex_lock(&session->queues_lock);
+
+	list_for_each_safe(p, n, &queue->pending_dqbufs) {
+		struct virtio_media_buffer *dqbuf =
+			list_entry(p, struct virtio_media_buffer, list);
+
+		list_del(&dqbuf->list);
+	}
+
+	/* All buffers are now dequeued. */
+	for (i = 0; i < queue->allocated_bufs; i++)
+		queue->buffers[i].buffer.flags = 0;
+
+	queue->queued_bufs = 0;
+	queue->streaming = false;
+	queue->is_capture_last = false;
+
+	mutex_unlock(&session->queues_lock);
+}
+
 /*
  * Macros suitable for defining ioctls with a constant size payload.
  */
@@ -488,6 +620,431 @@ static int virtio_media_try_ext_ctrls(struct file *file, void *fh,
 						    ctrls);
 }
 
+/*
+ * Subscribe/unsubscribe from an event.
+ */
+
+static int
+virtio_media_subscribe_event(struct v4l2_fh *fh,
+			     const struct v4l2_event_subscription *sub)
+{
+	struct video_device *video_dev = fh->vdev;
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	int ret;
+
+	/* First subscribe to the event in the guest. */
+	switch (sub->type) {
+	case V4L2_EVENT_SOURCE_CHANGE:
+		ret = v4l2_src_change_event_subscribe(fh, sub);
+		break;
+	default:
+		ret = v4l2_event_subscribe(fh, sub, 1, NULL);
+		break;
+	}
+	if (ret)
+		return ret;
+
+	/* Then ask the host to signal us these events. */
+	ret = virtio_media_send_w_ioctl(fh, VIDIOC_SUBSCRIBE_EVENT, sub,
+					sizeof(*sub));
+	if (ret < 0) {
+		v4l2_event_unsubscribe(fh, sub);
+		return ret;
+	}
+
+	/*
+	 * Subscribing to an event may result in that event being signaled
+	 * immediately. Process all pending events to make sure we don't
+	 * miss it.
+	 */
+	if (sub->flags & V4L2_EVENT_SUB_FL_SEND_INITIAL)
+		virtio_media_process_events(vv);
+
+	return 0;
+}
+
+static int
+virtio_media_unsubscribe_event(struct v4l2_fh *fh,
+			       const struct v4l2_event_subscription *sub)
+{
+	int ret = virtio_media_send_w_ioctl(fh, VIDIOC_UNSUBSCRIBE_EVENT, sub,
+					sizeof(*sub));
+	if (ret < 0)
+		return ret;
+
+	ret = v4l2_event_unsubscribe(fh, sub);
+	if (ret)
+		return ret;
+
+	return 0;
+}
+
+/*
+ * Streamon/off affect the local queue state.
+ */
+
+static int virtio_media_streamon(struct file *file, void *fh,
+				 enum v4l2_buf_type i)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	int ret;
+
+	if (i > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	ret = virtio_media_send_w_ioctl(vfh, VIDIOC_STREAMON, &i, sizeof(i));
+	if (ret < 0)
+		return ret;
+
+	session->queues[i].streaming = true;
+
+	return 0;
+}
+
+static int virtio_media_streamoff(struct file *file, void *fh,
+				  enum v4l2_buf_type i)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	int ret;
+
+	if (i > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	ret = virtio_media_send_w_ioctl(vfh, VIDIOC_STREAMOFF, &i, sizeof(i));
+	if (ret < 0)
+		return ret;
+
+	virtio_media_clear_queue(session, &session->queues[i]);
+
+	return 0;
+}
+
+/*
+ * Buffer creation/queuing functions deal with the local driver state.
+ */
+
+static int virtio_media_reqbufs(struct file *file, void *fh,
+				struct v4l2_requestbuffers *b)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	struct virtio_media_buffer *buffers = NULL;
+	struct virtio_media_queue_state *queue;
+	int ret;
+
+	if (b->type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	if (b->memory == V4L2_MEMORY_USERPTR)
+		return -EINVAL;
+
+	if (b->count > 0) {
+		buffers =
+			vcalloc(b->count, sizeof(struct virtio_media_buffer));
+		if (!buffers)
+			return -ENOMEM;
+	}
+
+	ret = virtio_media_send_wr_ioctl(vfh, VIDIOC_REQBUFS, b, sizeof(*b),
+					 sizeof(*b));
+	if (ret) {
+		vfree(buffers);
+		return ret;
+	}
+
+	queue = &session->queues[b->type];
+
+	/* REQBUFS(0) is an implicit STREAMOFF. */
+	if (b->count == 0)
+		virtio_media_clear_queue(session, queue);
+
+	vfree(queue->buffers);
+	queue->buffers = buffers;
+
+	queue->allocated_bufs = b->count;
+
+	/*
+	 * If a multiplanar queue is successfully used here, this means
+	 * we are using the multiplanar interface.
+	 */
+	if (V4L2_TYPE_IS_MULTIPLANAR(b->type))
+		session->uses_mplane = true;
+
+	b->capabilities &= ~V4L2_BUF_CAP_SUPPORTS_USERPTR;
+
+	/* We do not support DMABUF yet. */
+	b->capabilities &= ~V4L2_BUF_CAP_SUPPORTS_DMABUF;
+
+	return 0;
+}
+
+static int virtio_media_querybuf(struct file *file, void *fh,
+				 struct v4l2_buffer *b)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	struct virtio_media_queue_state *queue;
+	struct virtio_media_buffer *buffer;
+
+	int ret = virtio_media_send_buffer_ioctl(vfh, VIDIOC_QUERYBUF, b);
+
+	if (ret)
+		return ret;
+
+	if (b->type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	queue = &session->queues[b->type];
+	if (b->index >= queue->allocated_bufs)
+		return -EINVAL;
+
+	buffer = &queue->buffers[b->index];
+	/*
+	 * Set the DONE flag if the buffer is waiting in our own dequeue
+	 * queue.
+	 */
+	b->flags |= (buffer->buffer.flags & V4L2_BUF_FLAG_DONE);
+
+	return 0;
+}
+
+static int virtio_media_create_bufs(struct file *file, void *fh,
+				    struct v4l2_create_buffers *b)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	struct virtio_media_queue_state *queue;
+	struct virtio_media_buffer *buffers = NULL;
+	u32 type = b->format.type;
+	int ret;
+
+	if (type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	queue = &session->queues[type];
+
+	if (b->count > 0) {
+		/*
+		 * This allocates a new buffer large enough for the existing
+		 * buffers (``queue->allocated_bufs``) as well as the newly
+		 * requested buffers (``b->count``). The host may allocate
+		 * fewer buffers than requested, as indicated by the final
+		 * value of ``b->count``. In this case, we do not re-allocate
+		 * to avoid the case where this new allocation fails and the
+		 * host buffers need to be freed. Instead we simply use the
+		 * larger buffer.
+		 */
+		buffers = vcalloc(queue->allocated_bufs + b->count,
+				  sizeof(*queue->buffers));
+		if (!buffers)
+			return -ENOMEM;
+	}
+
+	ret = virtio_media_send_wr_ioctl(vfh, VIDIOC_CREATE_BUFS, b, sizeof(*b),
+					 sizeof(*b));
+	if (ret) {
+		if (buffers)
+			vfree(buffers);
+
+		return ret;
+	}
+
+	/* If count is zero, we were just checking for format. */
+	if (b->count == 0)
+		return 0;
+
+	memcpy(buffers, queue->buffers,
+	       sizeof(*queue->buffers) * queue->allocated_bufs);
+	vfree(queue->buffers);
+	queue->buffers = buffers;
+
+	queue->allocated_bufs = b->index + b->count;
+
+	return 0;
+}
+
+static int virtio_media_prepare_buf(struct file *file, void *fh,
+				    struct v4l2_buffer *b)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	struct virtio_media_queue_state *queue;
+	struct virtio_media_buffer *buffer;
+	int i, ret;
+
+	if (b->type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+	queue = &session->queues[b->type];
+	if (b->index >= queue->allocated_bufs)
+		return -EINVAL;
+	buffer = &queue->buffers[b->index];
+
+	buffer->buffer.m = b->m;
+	if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
+		if (b->length > VIDEO_MAX_PLANES)
+			return -EINVAL;
+		for (i = 0; i < b->length; i++)
+			buffer->planes[i].m = b->m.planes[i].m;
+	}
+
+	ret = virtio_media_send_buffer_ioctl(vfh, VIDIOC_PREPARE_BUF, b);
+	if (ret)
+		return ret;
+
+	buffer->buffer.flags = V4L2_BUF_FLAG_PREPARED;
+
+	return 0;
+}
+
+static int virtio_media_qbuf(struct file *file, void *fh, struct v4l2_buffer *b)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+	struct virtio_media_queue_state *queue;
+	struct virtio_media_buffer *buffer;
+	bool prepared;
+	u32 old_flags;
+	int i, ret;
+
+	if (b->type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+	queue = &session->queues[b->type];
+	if (b->index >= queue->allocated_bufs)
+		return -EINVAL;
+	buffer = &queue->buffers[b->index];
+	prepared = buffer->buffer.flags & V4L2_BUF_FLAG_PREPARED;
+
+	/*
+	 * Store the buffer and plane `m` information so we can retrieve
+	 * it again when DQBUF occurs.
+	 */
+	if (!prepared) {
+		buffer->buffer.m = b->m;
+		if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) {
+			if (b->length > VIDEO_MAX_PLANES)
+				return -EINVAL;
+			for (i = 0; i < b->length; i++)
+				buffer->planes[i].m = b->m.planes[i].m;
+		}
+	}
+	old_flags = buffer->buffer.flags;
+	buffer->buffer.flags = V4L2_BUF_FLAG_QUEUED;
+
+	ret = virtio_media_send_buffer_ioctl(vfh, VIDIOC_QBUF, b);
+	if (ret) {
+		/* Rollback the previous flags as the buffer is not queued. */
+		buffer->buffer.flags = old_flags;
+		return ret;
+	}
+
+	queue->queued_bufs += 1;
+
+	return 0;
+}
+
+static int virtio_media_dqbuf(struct file *file, void *fh,
+			      struct v4l2_buffer *b)
+{
+	struct video_device *video_dev = video_devdata(file);
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session =
+		fh_to_session(file_to_v4l2_fh(file));
+	struct virtio_media_buffer *dqbuf;
+	struct virtio_media_queue_state *queue;
+	struct list_head *buffer_queue;
+	struct v4l2_plane *planes_backup = NULL;
+	const bool is_multiplanar = V4L2_TYPE_IS_MULTIPLANAR(b->type);
+	int ret;
+	bool error;
+
+	if (b->type > VIRTIO_MEDIA_LAST_QUEUE)
+		return -EINVAL;
+
+	queue = &session->queues[b->type];
+
+	/*
+	 * If a buffer with the LAST flag has been returned, subsequent
+	 * calls to DQBUF must return -EPIPE until the queue is cleared.
+	 */
+	if (queue->is_capture_last)
+		return -EPIPE;
+
+	buffer_queue = &queue->pending_dqbufs;
+
+	if (session->nonblocking_dequeue) {
+		if (list_empty(buffer_queue))
+			return -EAGAIN;
+	} else if (queue->allocated_bufs == 0) {
+		return -EINVAL;
+	} else if (!queue->streaming) {
+		return -EINVAL;
+	}
+
+	/*
+	 * vv->lock has been acquired by virtio_media_device_ioctl. Release it
+	 * while we wait so that other ioctls for this session can be processed
+	 * and potentially trigger dqbuf_wait.
+	 */
+	mutex_unlock(&vv->vlock);
+
+	/*
+	 * It's not possible to acquire ``session->error_lock`` during the
+	 * check, however this shouldn't cause issues because:
+	 *     - The lock is acquired when actually checking the value
+	 *     - The ``session->error`` flag is never reset once set
+	 */
+	ret = wait_event_interruptible(session->dqbuf_wait,
+				       !list_empty(buffer_queue) ||
+				       session->error);
+	mutex_lock(&vv->vlock);
+	if (ret)
+		return -EINTR;
+
+	mutex_lock(&session->error_lock);
+	error = session->error;
+	mutex_unlock(&session->error_lock);
+
+	if (error)
+		return -EIO;
+
+	mutex_lock(&session->queues_lock);
+	dqbuf = list_first_entry_or_null(buffer_queue,
+					 struct virtio_media_buffer, list);
+
+	if (dqbuf)
+		list_del(&dqbuf->list);
+
+	mutex_unlock(&session->queues_lock);
+
+	if (!dqbuf) {
+		v4l2_err(&vv->v4l2_dev, "No buffer found when dqbuf event triggered\n");
+		return -EIO;
+	}
+
+	/* Clear the DONE flag as the buffer is now being dequeued. */
+	dqbuf->buffer.flags &= ~V4L2_BUF_FLAG_DONE;
+
+	if (is_multiplanar) {
+		size_t nb_planes = min_t(u32, b->length, VIDEO_MAX_PLANES);
+
+		memcpy(b->m.planes, dqbuf->planes,
+		       nb_planes * sizeof(struct v4l2_plane));
+		planes_backup = b->m.planes;
+	}
+
+	memcpy(b, &dqbuf->buffer, sizeof(*b));
+
+	if (is_multiplanar)
+		b->m.planes = planes_backup;
+
+	if (V4L2_TYPE_IS_CAPTURE(b->type) && b->flags & V4L2_BUF_FLAG_LAST)
+		queue->is_capture_last = true;
+
+	return 0;
+}
+
 /*
  * s/g_input/output work with an unsigned int - recast this to a u32 so the
  * size is unambiguous.
@@ -541,6 +1098,32 @@ static int virtio_media_s_output(struct file *file, void *fh, unsigned int o)
 					  sizeof(output), sizeof(output));
 }
 
+/*
+ * decoder_cmd can affect the state of the CAPTURE queue.
+ */
+
+static int virtio_media_decoder_cmd(struct file *file, void *fh,
+				    struct v4l2_decoder_cmd *cmd)
+{
+	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
+	struct virtio_media_session *session = fh_to_session(vfh);
+
+	int ret = virtio_media_send_wr_ioctl(vfh, VIDIOC_DECODER_CMD, cmd,
+					 sizeof(*cmd), sizeof(*cmd));
+	if (ret)
+		return ret;
+
+	/* A START command makes the CAPTURE queue able to dequeue again. */
+	if (cmd->cmd == V4L2_DEC_CMD_START) {
+		session->queues[V4L2_BUF_TYPE_VIDEO_CAPTURE].is_capture_last =
+			false;
+		session->queues[V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE]
+			.is_capture_last = false;
+	}
+
+	return 0;
+}
+
 /*
  * s_std doesn't work with a pointer, so we cannot use SIMPLE_W_IOCTL.
  */
@@ -616,6 +1199,25 @@ const struct v4l2_ioctl_ops virtio_media_ioctl_ops = {
 	.vidioc_try_fmt_meta_cap = virtio_media_try_fmt,
 	.vidioc_try_fmt_meta_out = virtio_media_try_fmt,
 
+	/* Buffer handlers */
+	.vidioc_reqbufs = virtio_media_reqbufs,
+	.vidioc_querybuf = virtio_media_querybuf,
+	.vidioc_qbuf = virtio_media_qbuf,
+	.vidioc_expbuf = NULL,
+	.vidioc_dqbuf = virtio_media_dqbuf,
+	.vidioc_create_bufs = virtio_media_create_bufs,
+	.vidioc_prepare_buf = virtio_media_prepare_buf,
+	/* Overlay interface not supported yet */
+	.vidioc_overlay = NULL,
+	/* Overlay interface not supported yet */
+	.vidioc_g_fbuf = NULL,
+	/* Overlay interface not supported yet */
+	.vidioc_s_fbuf = NULL,
+
+	/* Stream on/off */
+	.vidioc_streamon = virtio_media_streamon,
+	.vidioc_streamoff = virtio_media_streamoff,
+
 	/* Standard handling */
 	.vidioc_g_std = virtio_media_g_std,
 	.vidioc_s_std = virtio_media_s_std,
@@ -667,6 +1269,7 @@ const struct v4l2_ioctl_ops virtio_media_ioctl_ops = {
 	.vidioc_g_enc_index = virtio_media_g_enc_index,
 	.vidioc_encoder_cmd = virtio_media_encoder_cmd,
 	.vidioc_try_encoder_cmd = virtio_media_try_encoder_cmd,
+	.vidioc_decoder_cmd = virtio_media_decoder_cmd,
 	.vidioc_try_decoder_cmd = virtio_media_try_decoder_cmd,
 
 	/* Stream type-dependent parameter ioctls */
@@ -701,6 +1304,9 @@ const struct v4l2_ioctl_ops virtio_media_ioctl_ops = {
 	.vidioc_g_edid = NULL,
 	.vidioc_s_edid = NULL,
 
+	.vidioc_subscribe_event = virtio_media_subscribe_event,
+	.vidioc_unsubscribe_event = virtio_media_unsubscribe_event,
+
 	/* For other private ioctls */
 	.vidioc_default = NULL,
 };
@@ -714,9 +1320,19 @@ long virtio_media_device_ioctl(struct file *file, unsigned int cmd,
 	struct v4l2_standard standard;
 	v4l2_std_id std_id = 0;
 	int ret;
+	bool error;
 
-	if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags))
+	if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags)) {
 		vfh = file_to_v4l2_fh(file);
+		struct virtio_media_session *session = fh_to_session(vfh);
+
+		mutex_lock(&session->error_lock);
+		error = session->error;
+		mutex_unlock(&session->error_lock);
+
+		if (error)
+			return -EIO;
+	}
 
 	mutex_lock(&vv->vlock);
 
diff --git a/include/uapi/linux/virtio_media.h b/include/uapi/linux/virtio_media.h
index f117b97fc..da5c5baf0 100644
--- a/include/uapi/linux/virtio_media.h
+++ b/include/uapi/linux/virtio_media.h
@@ -171,4 +171,72 @@ struct virtio_media_sg_entry {
 	__le32 __reserved;
 };
 
+/* The values for these events are set by the virtio-media specification. */
+#define VIRTIO_MEDIA_EVT_ERROR 0
+#define VIRTIO_MEDIA_EVT_DQBUF 1
+#define VIRTIO_MEDIA_EVT_EVENT 2
+
+/**
+ * struct virtio_media_event_header - Header for events on the eventq.
+ * @event: one of VIRTIO_MEDIA_EVT_*
+ * @session_id: ID of the session the event applies to.
+ */
+struct virtio_media_event_header {
+	__le32 event;
+	__le32 session_id;
+};
+
+/**
+ * struct virtio_media_event_error - Unrecoverable device-side error.
+ * @hdr: header for the event.
+ * @error: error code describing the kind of error that occurred.
+ * @__reserved: must be set to zero by the device.
+ *
+ * Upon receiving this event, the session mentioned in the header is considered
+ * corrupted and closed.
+ */
+struct virtio_media_event_error {
+	struct virtio_media_event_header hdr;
+	__le32 error;
+	__le32 __reserved;
+};
+
+/* This is set to VIDEO_MAX_PLANES defined in include/uapi/linux/videodev2.h.
+ * It is renamed here to match the constant that is defined in the virtio-media
+ * specification.
+ */
+#define VIRTIO_MEDIA_MAX_PLANES VIDEO_MAX_PLANES
+
+/**
+ * struct virtio_media_event_dqbuf - Dequeued buffer event.
+ * @hdr: header for the event.
+ * @buffer: &struct v4l2_buffer describing the buffer that has been dequeued.
+ * @planes: plane information for the dequeued buffer.
+ *
+ * This event is used to signal that a buffer is not being used anymore by the
+ * device and is returned to the driver.
+ */
+struct virtio_media_event_dqbuf {
+	struct virtio_media_event_header hdr;
+	struct v4l2_buffer buffer;
+	struct v4l2_plane planes[VIRTIO_MEDIA_MAX_PLANES];
+};
+
+/**
+ * struct virtio_media_event_event - V4L2 event.
+ * @hdr: header for the event.
+ * @event: description of the event that occurred.
+ *
+ * This event signals that a V4L2 event has been emitted for a session.
+ */
+struct virtio_media_event_event {
+	struct virtio_media_event_header hdr;
+	struct v4l2_event event;
+};
+
+/* Maximum size of an event. We will queue descriptors of this size on the
+ * eventq.
+ */
+#define VIRTIO_MEDIA_EVENT_MAX_SIZE sizeof(struct virtio_media_event_dqbuf)
+
 #endif // _UAPI__LINUX_VIRTIO_MEDIA_H
-- 
2.56.1.750.gf70dc682cf-goog


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

* [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support
  2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
                   ` (3 preceding siblings ...)
  2026-11-20 21:59 ` [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll Brian Daniels
@ 2026-11-20 21:59 ` Brian Daniels
  2026-11-20 22:16   ` sashiko-bot
  2026-11-20 21:59 ` [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack Brian Daniels
  5 siblings, 1 reply; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Brian Daniels

From: Alexandre Courbot <gnurou@gmail.com>

Support mapping V4L2_MEMORY_MMAP buffers into guest userspace through
virtio shared memory region 0.

Query the shared memory region during device probe and implement the
mmap file operation and VMA close callback using VIRTIO_MEDIA_CMD_MMAP
and VIRTIO_MEDIA_CMD_MUNMAP, remapping the host-provided shared memory
offset into userspace via io_remap_pfn_range().

Signed-off-by: Alexandre Courbot <gnurou@gmail.com>
Assisted-by: LLM
Co-developed-by: Brian Daniels <briandaniels@google.com>
Signed-off-by: Brian Daniels <briandaniels@google.com>
---
 drivers/media/virtio/session.h             |  14 +-
 drivers/media/virtio/virtio_media.h        |  13 +-
 drivers/media/virtio/virtio_media_driver.c | 159 +++++++++++++++++++++
 include/uapi/linux/virtio_media.h          |  67 +++++++++
 4 files changed, 243 insertions(+), 10 deletions(-)

diff --git a/drivers/media/virtio/session.h b/drivers/media/virtio/session.h
index 16bb86bf4..c074ffc2c 100644
--- a/drivers/media/virtio/session.h
+++ b/drivers/media/virtio/session.h
@@ -63,12 +63,12 @@ struct virtio_media_queue_state {
  * @nonblocking_dequeue: whether dequeue should block or not (nonblocking if
  *                       file opened with O_NONBLOCK).
  * @uses_mplane: whether the queues for this session use the MPLANE API or not.
- * @cmd: union of session commands ``close`` and ``ioctl``. A session can have
- *       one command currently running. The rest of the commands are handled by
- *       &struct virtio_media.
- * @resp: union of responses to session commands. A session can wait on one
- *        command only. The rest of the responses are handled by
- *        &struct virtio_media.
+ * @cmd: union of session commands ``close``, ``ioctl``, and ``mmap``. A
+ *       session can have one command currently running. The rest of the
+ *       commands are handled by &struct virtio_media.
+ * @resp: union of responses to session commands ``close``, ``ioctl``, and
+ *        ``mmap``. A session can wait on one command only. The rest of the
+ *        responses are handled by &struct virtio_media.
  * @shadow_buf: shadow buffer where data to be added to the descriptor chain can
  *              be staged before being sent to the device.
  * @command_sgs: SG table gathering descriptors for a given command and its
@@ -91,10 +91,12 @@ struct virtio_media_session {
 	union {
 		struct virtio_media_cmd_close close;
 		struct virtio_media_cmd_ioctl ioctl;
+		struct virtio_media_cmd_mmap mmap;
 	} cmd;
 
 	union {
 		struct virtio_media_resp_ioctl ioctl;
+		struct virtio_media_resp_mmap mmap;
 	} resp;
 	__dma_from_device_group_end();
 
diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/virtio_media.h
index 8b21c1941..7acb2b842 100644
--- a/drivers/media/virtio/virtio_media.h
+++ b/drivers/media/virtio/virtio_media.h
@@ -26,14 +26,15 @@
  * @commandq: virtio command queue.
  * @eventq: virtio event queue.
  * @eventq_work: work to run when events are received on @eventq.
+ * @mmap_region: region into which MMAP buffers are mapped by the host.
  * @event_buffer: buffer for event descriptors.
  * @sessions: list of active sessions on the device.
  * @sessions_lock: protects @sessions and &struct virtio_media_session.list.
  * @events_lock: prevents concurrent processing of events.
- * @cmd: union of device-level commands. Session commands are handled by
- *       &struct virtio_media_session.
- * @resp: union of responses to device-level commands. Session responses are
- *        handled by &struct virtio_media_session.
+ * @cmd: union of the device commands ``open`` and ``munmap``. The other
+ *       commands are handled by &struct virtio_media_session
+ * @resp: union of responses to device commands ``open`` and ``munmap``. The
+ *        other responses are handled by &struct virtio_media_session
  * @vlock: serializes access to the command queue.
  * @wq: waitqueue for host responses on the command queue.
  */
@@ -46,6 +47,8 @@ struct virtio_media {
 	struct virtqueue *eventq;
 	struct work_struct eventq_work;
 
+	struct virtio_shm_region mmap_region;
+
 	void *event_buffer;
 
 	struct list_head sessions;
@@ -56,10 +59,12 @@ struct virtio_media {
 	__dma_from_device_group_begin();
 	union {
 		struct virtio_media_cmd_open open;
+		struct virtio_media_cmd_munmap munmap;
 	} cmd;
 
 	union {
 		struct virtio_media_resp_open open;
+		struct virtio_media_resp_munmap munmap;
 	} resp;
 	__dma_from_device_group_end();
 
diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
index 748357725..eb6b31d7e 100644
--- a/drivers/media/virtio/virtio_media_driver.c
+++ b/drivers/media/virtio/virtio_media_driver.c
@@ -6,6 +6,7 @@
  * Copyright (c) 2024-2026 Google LLC.
  */
 
+#include <linux/bits.h>
 #include <linux/device.h>
 #include <linux/dev_printk.h>
 #include <linux/mutex.h>
@@ -20,6 +21,7 @@
 #include <linux/workqueue.h>
 #include <linux/dma-mapping.h>
 #include <linux/poll.h>
+#include <linux/mm.h>
 
 #include <media/v4l2-dev.h>
 #include <media/v4l2-device.h>
@@ -32,6 +34,12 @@
 
 #define VIRTIO_MEDIA_NUM_EVENT_BUFS 16
 
+/* ID of the SHM region into which MMAP buffer will be mapped. */
+#define VIRTIO_MEDIA_SHM_MMAP 0
+
+/* Bit mask for the VIRTIO_MEDIA_MMAP_FLAG_RW flag */
+#define VIRTIO_MEDIA_MMAP_FLAG_RW_MASK BIT(VIRTIO_MEDIA_MMAP_FLAG_RW)
+
 /**
  * virtio_media_session_alloc() - Allocate a new session.
  * @vv: virtio-media device the session belongs to.
@@ -697,12 +705,155 @@ static __poll_t virtio_media_device_poll(struct file *file, poll_table *wait)
 	return rc;
 }
 
+static void virtio_media_vma_close_locked(struct vm_area_struct *vma)
+{
+	struct virtio_media *vv = vma->vm_private_data;
+	struct virtio_media_cmd_munmap *cmd_munmap = &vv->cmd.munmap;
+	struct virtio_media_resp_munmap *resp_munmap = &vv->resp.munmap;
+	struct scatterlist cmd_sg = {}, resp_sg = {};
+	struct scatterlist *sgs[2] = { &cmd_sg, &resp_sg };
+	int ret;
+
+	sg_set_buf(&cmd_sg, cmd_munmap, sizeof(*cmd_munmap));
+	sg_mark_end(&cmd_sg);
+
+	sg_set_buf(&resp_sg, resp_munmap, sizeof(*resp_munmap));
+	sg_mark_end(&resp_sg);
+
+	cmd_munmap->hdr.cmd = VIRTIO_MEDIA_CMD_MUNMAP;
+	cmd_munmap->hdr.__reserved = 0;
+	cmd_munmap->driver_addr =
+		(vma->vm_pgoff << PAGE_SHIFT) - vv->mmap_region.addr;
+	ret = virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_munmap),
+					NULL);
+	if (ret < 0) {
+		v4l2_err(&vv->v4l2_dev, "host failed to unmap buffer: %d\n",
+			 ret);
+	}
+}
+
+/**
+ * virtio_media_vma_close() - Close a MMAP buffer mapping.
+ * @vma: VMA of the mapping to close.
+ *
+ * Inform the host that a previously created MMAP mapping is no longer needed
+ * and can be removed.
+ */
+static void virtio_media_vma_close(struct vm_area_struct *vma)
+{
+	struct virtio_media *vv = vma->vm_private_data;
+
+	mutex_lock(&vv->vlock);
+	virtio_media_vma_close_locked(vma);
+	mutex_unlock(&vv->vlock);
+}
+
+static const struct vm_operations_struct virtio_media_vm_ops = {
+	.close = virtio_media_vma_close,
+};
+
+/**
+ * virtio_media_device_mmap() - Perform a mmap request from userspace.
+ * @file: opened file of the session to map for.
+ * @vma: VM area struct describing the desired mapping.
+ *
+ * This requests the host to map a MMAP buffer for us, so we can then make that
+ * mapping visible into user-space address space.
+ */
+static int virtio_media_device_mmap(struct file *file,
+				    struct vm_area_struct *vma)
+{
+	struct video_device *video_dev = video_devdata(file);
+	struct virtio_media *vv = to_virtio_media(video_dev);
+	struct virtio_media_session *session =
+		fh_to_session(file->private_data);
+	struct virtio_media_cmd_mmap *cmd_mmap = &session->cmd.mmap;
+	struct virtio_media_resp_mmap *resp_mmap = &session->resp.mmap;
+	struct scatterlist cmd_sg = {}, resp_sg = {};
+	struct scatterlist *sgs[2] = { &cmd_sg, &resp_sg };
+	int ret;
+
+	mutex_lock(&session->error_lock);
+	bool session_error = session->error;
+
+	mutex_unlock(&session->error_lock);
+
+	if (session_error)
+		return -EIO;
+	if (!(vma->vm_flags & VM_SHARED))
+		return -EINVAL;
+	if (!(vma->vm_flags & (VM_READ | VM_WRITE)))
+		return -EINVAL;
+
+	mutex_lock(&vv->vlock);
+
+	cmd_mmap->hdr.cmd = VIRTIO_MEDIA_CMD_MMAP;
+	cmd_mmap->hdr.__reserved = 0;
+	cmd_mmap->session_id = session->id;
+	cmd_mmap->flags =
+		(vma->vm_flags & VM_WRITE) ? VIRTIO_MEDIA_MMAP_FLAG_RW_MASK : 0;
+	cmd_mmap->offset = vma->vm_pgoff << PAGE_SHIFT;
+	cmd_mmap->__reserved = 0;
+
+	sg_set_buf(&cmd_sg, cmd_mmap, sizeof(*cmd_mmap));
+	sg_mark_end(&cmd_sg);
+
+	sg_set_buf(&resp_sg, resp_mmap, sizeof(*resp_mmap));
+	sg_mark_end(&resp_sg);
+
+	/*
+	 * The host performs reference counting and is smart enough to return
+	 * the same guest physical address if this is called several times on
+	 * the same
+	 * buffer.
+	 */
+	ret = virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_mmap),
+					NULL);
+	if (ret < 0)
+		goto end;
+
+	vma->vm_private_data = vv;
+	/*
+	 * Keep the guest address at which the buffer is mapped since we will
+	 * use that to unmap.
+	 */
+	vma->vm_pgoff = (resp_mmap->driver_addr + vv->mmap_region.addr) >>
+			PAGE_SHIFT;
+
+	/*
+	 * We cannot let the mapping be larger than the buffer.
+	 */
+	if (vma->vm_end - vma->vm_start > PAGE_ALIGN(resp_mmap->len)) {
+		dev_dbg(&video_dev->dev,
+			"invalid MMAP, as it would overflow buffer length\n");
+		ret = -EINVAL;
+		goto cleanup;
+	}
+
+	ret = io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
+				 vma->vm_end - vma->vm_start,
+				 vma->vm_page_prot);
+	if (ret) {
+		dev_dbg(&video_dev->dev, "io_remap_pfn_range() failed\n");
+		goto cleanup;
+	}
+
+	vma->vm_ops = &virtio_media_vm_ops;
+	goto end;
+cleanup:
+	virtio_media_vma_close_locked(vma);
+end:
+	mutex_unlock(&vv->vlock);
+	return ret;
+}
+
 static const struct v4l2_file_operations virtio_media_fops = {
 	.owner = THIS_MODULE,
 	.open = virtio_media_device_open,
 	.release = virtio_media_device_close,
 	.poll = virtio_media_device_poll,
 	.unlocked_ioctl = virtio_media_device_ioctl,
+	.mmap = virtio_media_device_mmap,
 };
 
 static void virtio_media_release(struct v4l2_device *v4l2_dev)
@@ -773,6 +924,14 @@ static int virtio_media_probe(struct virtio_device *virtio_dev)
 	vv->eventq = vqs[1];
 	INIT_WORK(&vv->eventq_work, virtio_media_event_work);
 
+	/* Get MMAP buffer mapping SHM region */
+	if (!virtio_get_shm_region(virtio_dev, &vv->mmap_region,
+				   VIRTIO_MEDIA_SHM_MMAP)) {
+		dev_err(&virtio_dev->dev, "Failed to get shared memory region");
+		ret = -ENOMEM;
+		goto err_del_vqs;
+	}
+
 	vd = &vv->video_dev;
 	vd->v4l2_dev = &vv->v4l2_dev;
 	vd->ioctl_ops = &virtio_media_ioctl_ops;
diff --git a/include/uapi/linux/virtio_media.h b/include/uapi/linux/virtio_media.h
index da5c5baf0..2ea28770e 100644
--- a/include/uapi/linux/virtio_media.h
+++ b/include/uapi/linux/virtio_media.h
@@ -171,6 +171,73 @@ struct virtio_media_sg_entry {
 	__le32 __reserved;
 };
 
+/**
+ * VIRTIO_MEDIA_MMAP_FLAG_RW - Bit position of the VIRTIO_MEDIA_MMAP_FLAG_RW
+ *                             flag.
+ */
+#define VIRTIO_MEDIA_MMAP_FLAG_RW 0
+
+/**
+ * VIRTIO_MEDIA_CMD_MMAP - Command for mapping a MMAP buffer into the driver's
+ *                         address space.
+ */
+#define VIRTIO_MEDIA_CMD_MMAP 4
+
+/**
+ * struct virtio_media_cmd_mmap - Driver command for VIRTIO_MEDIA_CMD_MMAP.
+ * @hdr: header with cmd member set to VIRTIO_MEDIA_CMD_MMAP.
+ * @session_id: ID of the session we are mapping for.
+ * @flags: combination of VIRTIO_MEDIA_MMAP_FLAG_*.
+ * @offset: mem_offset field of the plane to map, as returned by
+ *          VIDIOC_QUERYBUF.
+ * @__reserved: must be set to zero by the driver.
+ */
+struct virtio_media_cmd_mmap {
+	struct virtio_media_cmd_header hdr;
+	__le32 session_id;
+	__le32 flags;
+	__le32 offset;
+	__le32 __reserved;
+};
+
+/**
+ * struct virtio_media_resp_mmap - Device response for VIRTIO_MEDIA_CMD_MMAP.
+ * @hdr: header containing the status of the command.
+ * @driver_addr: offset into SHM region 0 of the start of the mapping.
+ * @len: length of the mapping.
+ */
+struct virtio_media_resp_mmap {
+	struct virtio_media_resp_header hdr;
+	__le64 driver_addr;
+	__le64 len;
+};
+
+/**
+ * VIRTIO_MEDIA_CMD_MUNMAP - Unmap a MMAP buffer previously mapped using
+ *                           VIRTIO_MEDIA_CMD_MMAP.
+ */
+#define VIRTIO_MEDIA_CMD_MUNMAP 5
+
+/**
+ * struct virtio_media_cmd_munmap - Driver command for VIRTIO_MEDIA_CMD_MUNMAP.
+ * @hdr: header with cmd member set to VIRTIO_MEDIA_CMD_MUNMAP.
+ * @driver_addr: offset into SHM region 0 at which the buffer has been
+ *               previously mapped.
+ */
+struct virtio_media_cmd_munmap {
+	struct virtio_media_cmd_header hdr;
+	__le64 driver_addr;
+};
+
+/**
+ * struct virtio_media_resp_munmap - Device response for
+ *                                   VIRTIO_MEDIA_CMD_MUNMAP.
+ * @hdr: header containing the status of the command.
+ */
+struct virtio_media_resp_munmap {
+	struct virtio_media_resp_header hdr;
+};
+
 /* The values for these events are set by the virtio-media specification. */
 #define VIRTIO_MEDIA_EVT_ERROR 0
 #define VIRTIO_MEDIA_EVT_DQBUF 1
-- 
2.56.1.750.gf70dc682cf-goog


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

* [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack
  2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
                   ` (4 preceding siblings ...)
  2026-11-20 21:59 ` [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support Brian Daniels
@ 2026-11-20 21:59 ` Brian Daniels
  2026-11-20 22:25   ` sashiko-bot
  5 siblings, 1 reply; 13+ messages in thread
From: Brian Daniels @ 2026-11-20 21:59 UTC (permalink / raw)
  To: Mauro Carvalho Chehab
  Cc: adelva, aesteve, changyeon, daniel.almeida, eperezma, gnurou,
	gurchetansingh, hverkuil, linux-kernel, linux-media, mst,
	nicolas.dufresne, virtualization, xuanzhuo, dbassey,
	laurent.pinchart, Nick Rogers

From: Nick Rogers <nick@getfieldwork.ai>

A driver without a control handler receives VIDIOC_G_CTRL and
VIDIOC_S_CTRL from the V4L2 core as a single extended control that the
core builds on its own stack, with the control's size left
uninitialized. virtio_media_send_ext_controls_ioctl() takes a nonzero
size as a payload to copy from userspace, so these ioctls fail with
-EINVAL whenever the stack is dirty. GStreamer's V4L2 encoders set their
profile with VIDIOC_S_CTRL and cannot negotiate, and v4l2-ctl cannot
read the MIN_BUFFERS controls.

Legacy controls carry a 32-bit value and never a payload, and an array
that comes from userspace is copied into an allocation, never onto the
stack. Clear the size of each control when the array is on the stack.

The core is being fixed to zero the structure [1]; this keeps the driver
working on kernels without that fix.

[1] https://lore.kernel.org/all/20260923160936.33445-1-nick@getfieldwork.ai/

Assisted-by: LLM
Signed-off-by: Nick Rogers <nick@getfieldwork.ai>
---
 drivers/media/virtio/virtio_media_ioctls.c | 25 ++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/virtio/virtio_media_ioctls.c
index aa56efe9a..ad240073a 100644
--- a/drivers/media/virtio/virtio_media_ioctls.c
+++ b/drivers/media/virtio/virtio_media_ioctls.c
@@ -6,6 +6,7 @@
  * Copyright (c) 2024-2026 Google LLC.
  */
 
+#include <linux/sched/task_stack.h>
 #include <linux/mutex.h>
 #include <linux/videodev2.h>
 #include <linux/virtio_config.h>
@@ -593,11 +594,31 @@ static int virtio_media_querycap(struct file *file, void *fh,
  * Extended control ioctls are handled mostly identically.
  */
 
+/*
+ * VIDIOC_G_CTRL and VIDIOC_S_CTRL reach a driver without a control handler
+ * as one extended control the V4L2 core builds on its own stack, with its
+ * size left uninitialized. They carry a 32-bit value and never a payload,
+ * so a size there is stack garbage, which would be sent as a user pointer
+ * to copy and fail the ioctl. An array from userspace is never on the
+ * stack: the core copies it into an allocation.
+ */
+static void virtio_media_legacy_ctrl(struct v4l2_ext_controls *ctrls)
+{
+	u32 i;
+
+	if (!ctrls->count || !object_is_on_stack(ctrls->controls))
+		return;
+	for (i = 0; i < ctrls->count; i++)
+		ctrls->controls[i].size = 0;
+}
+
 static int virtio_media_g_ext_ctrls(struct file *file, void *fh,
 				    struct v4l2_ext_controls *ctrls)
 {
 	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
 
+	virtio_media_legacy_ctrl(ctrls);
+
 	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_G_EXT_CTRLS,
 						    ctrls);
 }
@@ -607,6 +628,8 @@ static int virtio_media_s_ext_ctrls(struct file *file, void *fh,
 {
 	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
 
+	virtio_media_legacy_ctrl(ctrls);
+
 	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_S_EXT_CTRLS,
 						    ctrls);
 }
@@ -616,6 +639,8 @@ static int virtio_media_try_ext_ctrls(struct file *file, void *fh,
 {
 	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
 
+	virtio_media_legacy_ctrl(ctrls);
+
 	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_TRY_EXT_CTRLS,
 						    ctrls);
 }
-- 
2.56.1.750.gf70dc682cf-goog


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

* Re: [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support
  2026-11-20 21:59 ` [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support Brian Daniels
@ 2026-11-20 22:16   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-11-20 22:16 UTC (permalink / raw)
  To: Brian Daniels; +Cc: virtualization, media-ci, Michael S. Tsirkin, Eugenio Perez

Thank you for your contribution! Sashiko AI review found 8 potential
issues to consider:
- [High] media: virtio: missing vm_ops->open() and pgoff corruption in
  vma close
- [High] media: virtio: use-after-free of commandq in
  virtio_media_vma_close()
- [High] media: virtio: mmap_lock and vlock inversion in
  virtio_media_device_mmap()
- [High] media: virtio: use-after-free in virtio_media_vma_close() after
  remove
- [Medium] media: virtio: missing SHM bounds check in
  virtio_media_device_mmap()
- [Medium] media: virtio: VM_MAYWRITE left set on RO mapping in
  virtio_media_device_mmap()
- [Medium] media: virtio: TOCTOU race on session->error in
  virtio_media_device_mmap()
- [Low] media: virtio: 32-bit offset truncation in
  virtio_media_device_mmap()
--

commit ca0abfda91649fedfc5e57137d16c8a739721fdb
Author: Alexandre Courbot <gnurou@gmail.com>

media: virtio: Add MMAP buffer mapping support

This commit adds V4L2_MEMORY_MMAP buffer mapping support to the virtio-media
driver by querying shared memory region 0 during probe and implementing mmap
and VMA close callbacks using VIRTIO_MEDIA_CMD_MMAP and
VIRTIO_MEDIA_CMD_MUNMAP.

> diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
> index 7483577256bd0..eb6b31d7e370c 100644
> --- a/drivers/media/virtio/virtio_media_driver.c
> +++ b/drivers/media/virtio/virtio_media_driver.c
[ ... ]
> @@ -697,12 +705,155 @@ static __poll_t virtio_media_device_poll(struct file *file, poll_table *wait)
>  	return rc;
>  }
>  
> +static void virtio_media_vma_close_locked(struct vm_area_struct *vma)
> +{
> +	struct virtio_media *vv = vma->vm_private_data;
> +	struct virtio_media_cmd_munmap *cmd_munmap = &vv->cmd.munmap;
> +	struct virtio_media_resp_munmap *resp_munmap = &vv->resp.munmap;
> +	struct scatterlist cmd_sg = {}, resp_sg = {};
> +	struct scatterlist *sgs[2] = { &cmd_sg, &resp_sg };
> +	int ret;
> +
> +	sg_set_buf(&cmd_sg, cmd_munmap, sizeof(*cmd_munmap));
> +	sg_mark_end(&cmd_sg);
> +
> +	sg_set_buf(&resp_sg, resp_munmap, sizeof(*resp_munmap));
> +	sg_mark_end(&resp_sg);
> +
> +	cmd_munmap->hdr.cmd = VIRTIO_MEDIA_CMD_MUNMAP;
> +	cmd_munmap->hdr.__reserved = 0;
> +	cmd_munmap->driver_addr =
> +		(vma->vm_pgoff << PAGE_SHIFT) - vv->mmap_region.addr;
> +	ret = virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_munmap),
> +					NULL);
> +	if (ret < 0) {
> +		v4l2_err(&vv->v4l2_dev, "host failed to unmap buffer: %d\n",
> +			 ret);
> +	}
> +}

[Severity: High]
Can virtio_media_vma_close_locked() cause a use-after-free on vv->commandq if
a mapping is unmapped after virtio_media_remove()?

An active VMA holds a reference on vma->vm_file, which keeps vv alive until
all mappings are unmapped.  If the device is removed while a buffer is mapped,
virtio_media_remove() calls virtio_dev->config->del_vqs(virtio_dev), freeing
vv->commandq.  Unlike V4L2 file operations gated by video_is_registered(), the
MM subsystem invokes vma->vm_ops->close() directly on munmap() or process
exit, so virtio_media_send_command() dereferences the freed vv->commandq.

> +
> +/**
> + * virtio_media_vma_close() - Close a MMAP buffer mapping.
> + * @vma: VMA of the mapping to close.
> + *
> + * Inform the host that a previously created MMAP mapping is no longer needed
> + * and can be removed.
> + */
> +static void virtio_media_vma_close(struct vm_area_struct *vma)
> +{
> +	struct virtio_media *vv = vma->vm_private_data;
> +
> +	mutex_lock(&vv->vlock);
> +	virtio_media_vma_close_locked(vma);
> +	mutex_unlock(&vv->vlock);
> +}

[Severity: High]
When a mapped VMA outlives virtio_media_remove(), can closing that VMA trigger
both a use-after-free on vv->commandq and a use-after-free and double free of
the session?

drivers/media/virtio/virtio_media_driver.c:virtio_media_remove() {
	...
	/* Delete the virtqueues */
	virtio_dev->config->del_vqs(virtio_dev);

	mutex_unlock(&vv->vlock);

	list_for_each_safe(p, n, &vv->sessions) {
		struct virtio_media_session *s =
			list_entry(p, struct virtio_media_session, list);

		virtio_media_session_remove(vv, s);
		virtio_media_session_free(s);
	}
}

Because vma->vm_file pins the open struct file while the VMA exists, unmapping
the VMA after virtio_media_remove() first calls virtio_media_vma_close(),
which accesses the deleted vv->commandq, and then drops the final file
reference via fput(vma->vm_file).  That invokes v4l2_release() ->
virtio_media_device_close(), which dereferences and frees the session in
file->private_data that virtio_media_remove() already freed.

> +
> +static const struct vm_operations_struct virtio_media_vm_ops = {
> +	.close = virtio_media_vma_close,
> +};

[Severity: High]
Does omitting .open in virtio_media_vm_ops cause premature host unmapping and
corrupted VIRTIO_MEDIA_CMD_MUNMAP offsets when a VMA is duplicated or split?

When a process with a mapped buffer calls fork(), moves the mapping with
mremap(), or splits the VMA via partial munmap() or mprotect(), the kernel
duplicates the VMA and calls vm_ops->open() without calling
virtio_media_device_mmap().  With no .open callback or reference-counted
mapping state in vma->vm_private_data (such as struct vb2_vmarea_handler),
closing one VMA sends VIRTIO_MEDIA_CMD_MUNMAP to the host while the remaining
VMA still maps those shared memory pages in guest userspace.

In addition, __split_vma() advances the upper VMA's vm_pgoff by the split
offset, so when the upper half is later closed,
(vma->vm_pgoff << PAGE_SHIFT) - vv->mmap_region.addr computes an offset inside
the buffer rather than the base driver_addr returned by VIRTIO_MEDIA_CMD_MMAP.

> +
> +/**
> + * virtio_media_device_mmap() - Perform a mmap request from userspace.
> + * @file: opened file of the session to map for.
> + * @vma: VM area struct describing the desired mapping.
> + *
> + * This requests the host to map a MMAP buffer for us, so we can then make that
> + * mapping visible into user-space address space.
> + */
> +static int virtio_media_device_mmap(struct file *file,
> +				    struct vm_area_struct *vma)
> +{
> +	struct video_device *video_dev = video_devdata(file);
> +	struct virtio_media *vv = to_virtio_media(video_dev);
> +	struct virtio_media_session *session =
> +		fh_to_session(file->private_data);
> +	struct virtio_media_cmd_mmap *cmd_mmap = &session->cmd.mmap;
> +	struct virtio_media_resp_mmap *resp_mmap = &session->resp.mmap;
> +	struct scatterlist cmd_sg = {}, resp_sg = {};
> +	struct scatterlist *sgs[2] = { &cmd_sg, &resp_sg };
> +	int ret;
> +
> +	mutex_lock(&session->error_lock);
> +	bool session_error = session->error;
> +
> +	mutex_unlock(&session->error_lock);
> +
> +	if (session_error)
> +		return -EIO;

[Severity: Medium]
Can a VIRTIO_MEDIA_EVT_ERROR event arriving before mutex_lock(&vv->vlock)
cause virtio_media_device_mmap() to send VIRTIO_MEDIA_CMD_MMAP for an already
closed session?

CPU0 (virtio_media_device_mmap)   CPU1 (virtio_media_process_events)
mutex_lock(&session->error_lock)
session_error = session->error
mutex_unlock(&session->error_lock)
                                  mutex_lock(&session->error_lock)
                                  session->error = true
                                  mutex_unlock(&session->error_lock)
                                  virtio_media_session_close(vv, session)
                                    mutex_lock(&vv->vlock)
                                    /* sends VIRTIO_MEDIA_CMD_CLOSE */
                                    mutex_unlock(&vv->vlock)
mutex_lock(&vv->vlock)
/* sends VIRTIO_MEDIA_CMD_MMAP
   on closed session->id */

Re-checking session->error after acquiring vv->vlock (or holding vv->vlock
across the check) would prevent using session->id after
VIRTIO_MEDIA_CMD_CLOSE.

> +	if (!(vma->vm_flags & VM_SHARED))
> +		return -EINVAL;
> +	if (!(vma->vm_flags & (VM_READ | VM_WRITE)))
> +		return -EINVAL;
> +
> +	mutex_lock(&vv->vlock);

[Severity: High]
Does acquiring vv->vlock inside virtio_media_device_mmap() and
virtio_media_vma_close() create an ABBA deadlock with mm->mmap_lock?

CPU0                              CPU1
----                              ----
lock(&mm->mmap_lock)
                                  lock(&vv->vlock)
lock(&vv->vlock)
                                  lock(&mm->mmap_lock)

 *** DEADLOCK ***

CPU0: mmap_region() -> v4l2_mmap() -> virtio_media_device_mmap()
      (or remove_vma() -> virtio_media_vma_close())
CPU1: virtio_media_device_ioctl() -> copy_from_user() / video_ioctl2() /
      pin_user_pages_fast()

virtio_media_device_ioctl() holds vv->vlock across user memory copies and
pin_user_pages_fast(), which acquire mm->mmap_lock on page faults or the GUP
slowpath, while mmap() and munmap() invoke virtio_media_device_mmap() and
virtio_media_vma_close() with mm->mmap_lock already write-locked.

> +
> +	cmd_mmap->hdr.cmd = VIRTIO_MEDIA_CMD_MMAP;
> +	cmd_mmap->hdr.__reserved = 0;
> +	cmd_mmap->session_id = session->id;
> +	cmd_mmap->flags =
> +		(vma->vm_flags & VM_WRITE) ? VIRTIO_MEDIA_MMAP_FLAG_RW_MASK : 0;

[Severity: Medium]
When a buffer is mapped read-only on an O_RDWR file descriptor, can userspace
later gain write access via mprotect() despite the host mapping being created
without VIRTIO_MEDIA_MMAP_FLAG_RW_MASK?

For a shared mapping on an O_RDWR file, do_mmap() sets VM_MAYWRITE in
vma->vm_flags even when PROT_WRITE was not requested.  Because VM_MAYWRITE is
left set when VM_WRITE is clear, a subsequent mprotect(..., PROT_READ |
PROT_WRITE) installs writable guest PTEs backed by a read-only host shared
memory mapping.  Clearing VM_MAYWRITE via vm_flags_clear(vma, VM_MAYWRITE) on
read-only mappings (or checking VM_MAYWRITE when setting cmd_mmap->flags)
would prevent this mismatch.

> +	cmd_mmap->offset = vma->vm_pgoff << PAGE_SHIFT;

[Severity: Low]
Can a 64-bit file offset >= 4 GiB be silently truncated when assigned to the
32-bit cmd_mmap->offset?

On 64-bit kernels, vma->vm_pgoff << PAGE_SHIFT is 64 bits wide while
cmd_mmap->offset is __le32, so an out-of-range mmap() offset wraps modulo 4
GiB and can alias a valid 32-bit plane mem_offset instead of failing with
-EINVAL.

> +	cmd_mmap->__reserved = 0;
> +
> +	sg_set_buf(&cmd_sg, cmd_mmap, sizeof(*cmd_mmap));
> +	sg_mark_end(&cmd_sg);
> +
> +	sg_set_buf(&resp_sg, resp_mmap, sizeof(*resp_mmap));
> +	sg_mark_end(&resp_sg);
> +
> +	/*
> +	 * The host performs reference counting and is smart enough to return
> +	 * the same guest physical address if this is called several times on
> +	 * the same
> +	 * buffer.
> +	 */
> +	ret = virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_mmap),
> +					NULL);
> +	if (ret < 0)
> +		goto end;
> +
> +	vma->vm_private_data = vv;
> +	/*
> +	 * Keep the guest address at which the buffer is mapped since we will
> +	 * use that to unmap.
> +	 */
> +	vma->vm_pgoff = (resp_mmap->driver_addr + vv->mmap_region.addr) >>
> +			PAGE_SHIFT;
> +
> +	/*
> +	 * We cannot let the mapping be larger than the buffer.
> +	 */
> +	if (vma->vm_end - vma->vm_start > PAGE_ALIGN(resp_mmap->len)) {
> +		dev_dbg(&video_dev->dev,
> +			"invalid MMAP, as it would overflow buffer length\n");
> +		ret = -EINVAL;
> +		goto cleanup;
> +	}
> +
> +	ret = io_remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff,
> +				 vma->vm_end - vma->vm_start,
> +				 vma->vm_page_prot);

[Severity: Medium]
Can an invalid or out-of-bounds resp_mmap->driver_addr cause
io_remap_pfn_range() to remap guest physical memory outside vv->mmap_region?

virtio_media_device_mmap() does not check that resp_mmap->driver_addr and the
mapped range fit within vv->mmap_region.len (without overflow), nor that
resp_mmap->driver_addr is page-aligned before shifting it into vma->vm_pgoff.
If the host returns an unaligned or out-of-range offset, io_remap_pfn_range()
can map arbitrary guest physical addresses outside the shared memory region or
lose the sub-page bits needed to pass the matching driver_addr back in
VIRTIO_MEDIA_CMD_MUNMAP.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261120215916.3149345-1-briandaniels@google.com?part=5

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

* Re: [PATCH v11 1/6] media: virtio: Add core driver and session management
  2026-11-20 21:59 ` [PATCH v11 1/6] media: virtio: Add core driver and session management Brian Daniels
@ 2026-11-20 22:19   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-11-20 22:19 UTC (permalink / raw)
  To: Brian Daniels; +Cc: virtualization, media-ci, Michael S. Tsirkin, Eugenio Perez

Thank you for your contribution! Sashiko AI review found 6 potential
issues to consider:
- [High] media: virtio: UAF and NULL deref on close after
  virtio_media_remove()
- [High] media: virtio: unsynchronized commandq access and stack UAF on
  cb_param
- [High] media: virtio: stack cb_param left queued if virtqueue_kick()
  fails
- [Medium] media: virtio: unsigned status negation in
  virtio_media_kick_command()
- [Low] media: virtio: MEDIA_VIRTIO misplaced in device types Kconfig
  menu
- [Low] media: virtio: malformed kernel-doc and missing include in
  headers
--

commit c335528a6819af8be1759670843febeb88a66360
Author: Alexandre Courbot <gnurou@gmail.com>

media: virtio: Add core driver and session management

This commit adds the initial virtio-media driver core, build system
integration, V4L2 device registration, and session open/close lifecycle
handling over the command virtqueue.

> diff --git a/drivers/media/Kconfig b/drivers/media/Kconfig
> index 6abc9302cd84d..ce7d088e74418 100644
> --- a/drivers/media/Kconfig
> +++ b/drivers/media/Kconfig
> @@ -136,6 +136,19 @@ config MEDIA_PLATFORM_SUPPORT
>  
>  	  Say Y when you want to be able to see such devices.
>  
> +config MEDIA_VIRTIO
> +	tristate "Virtio-media Driver"
> +	depends on VIRTIO && VIDEO_DEV && 64BIT && (X86 || CPU_LITTLE_ENDIAN)
> +	select VIDEOBUF2_CORE
> +	select VIDEOBUF2_MEMOPS
> +	help
> +	  Enables the virtio-media driver.
> +
> +	  This driver is used to virtualize media devices such as cameras or
> +	  decoders from a host into a guest using the V4L2 protocol.
> +
> +	  If unsure, say N.
> +
>  config MEDIA_TEST_SUPPORT
>  	bool
>  	prompt "Test drivers" if MEDIA_SUPPORT_FILTER

[Severity: Low]
Should MEDIA_VIRTIO be placed under the "Media drivers" menu instead of
"Media device types"?  When MEDIA_SUPPORT_FILTER is enabled, VIDEO_DEV is
hidden and only defaults to y if one of the device-type filter options
(such as MEDIA_CAMERA_SUPPORT or MEDIA_PLATFORM_SUPPORT) is selected, so
MEDIA_VIRTIO cannot be seen or enabled on its own.

> diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
> new file mode 100644
> index 0000000000000..39c5a38d20b1b
> --- /dev/null
> +++ b/drivers/media/virtio/virtio_media_driver.c
[ ... ]
> +static void commandq_callback(struct virtqueue *queue)
> +{
> +	unsigned int len;
> +	struct virtio_media_cmd_callback_param *param;
> +
> +process_bufs:
> +	while ((param = virtqueue_get_buf(queue, &len))) {
> +		param->resp_len = len;
> +		param->done = true;
> +		wake_up(&param->vv->wq);
> +	}
> +
> +	if (!virtqueue_enable_cb(queue)) {
> +		virtqueue_disable_cb(queue);
> +		goto process_bufs;
> +	}
> +}
> +
> +/**
> + * virtio_media_kick_command() - send a command to the commandq.
> + * @vv: virtio-media device in use.
> + * @sgs: descriptor chain to send.
> + * @out_sgs: number of device-readable descriptors in @sgs.
> + * @in_sgs: number of device-writable descriptors in @sgs.
> + * @resp_len: output parameter. Upon success, contains the size of the response
> + *            in bytes.
> + */
> +static int virtio_media_kick_command(struct virtio_media *vv,
> +				     struct scatterlist **sgs,
> +				     const size_t out_sgs, const size_t in_sgs,
> +				     size_t *resp_len)
> +{
> +	struct virtio_media_cmd_callback_param cb_param = {
> +		.vv = vv,
> +		.done = false,
> +		.resp_len = 0,
> +	};
> +	struct virtio_media_resp_header *resp_header;
> +	int ret = virtqueue_add_sgs(vv->commandq, sgs, out_sgs, in_sgs,
> +		  &cb_param, GFP_ATOMIC);
> +	if (ret) {
> +		v4l2_err(&vv->v4l2_dev,
> +			 "failed to add sgs to command virtqueue\n");
> +		return ret;
> +	}
> +
> +	if (!virtqueue_kick(vv->commandq)) {
> +		v4l2_err(&vv->v4l2_dev, "failed to kick command virtqueue\n");
> +		return -EINVAL;
> +	}
> +
> +	/* Wait for the response. */
> +	wait_event(vv->wq, cb_param.done);

[Severity: High]
Can commandq_callback() race with virtio_media_kick_command() on both
cb_param and vv->commandq?

CPU0                                  CPU1 (<hardirq>)
virtio_media_kick_command()
  virtqueue_add_sgs(..., &cb_param)
  virtqueue_kick(vv->commandq)
                                      commandq_callback()
                                        param = virtqueue_get_buf(...)
                                        param->done = true;
  wait_event(vv->wq, cb_param.done)
  return 0;                           /* cb_param stack frame popped */
                                        wake_up(&param->vv->wq);
                                          <-- stack use-after-return
  mutex_unlock(&vv->vlock)
  /* next command on CPU0 */
  mutex_lock(&vv->vlock)
  virtqueue_add_sgs(vv->commandq, ...)
                                        virtqueue_enable_cb(queue)
                                          <-- concurrent vq access

Virtqueue operations are not internally locked, and vv->vlock only
serializes process-context callers.  Once param->done is set to true, the
waiter on CPU0 can return from virtio_media_kick_command() before
commandq_callback() reads param->vv, and a subsequent command can call
virtqueue_add_sgs() or virtqueue_kick() concurrently with
virtqueue_get_buf() and virtqueue_enable_cb() in the interrupt handler.

In addition, wait_event() waits in TASK_UNINTERRUPTIBLE with no timeout
while holding vv->vlock, so an unresponsive device will hang the calling
task indefinitely and block virtio_media_remove().

[Severity: High]
What happens to the queued &cb_param token if virtqueue_kick() fails in
virtio_media_kick_command()?

At that point virtqueue_add_sgs() and virtqueue_kick_prepare() have
already published the descriptor chain and the stack-allocated &cb_param
pointer into vv->commandq.  Returning -EINVAL immediately pops the stack
frame (and in virtio_media_device_close() also frees session->cmd.close)
while the buffer remains queued, so a later completion on vv->commandq
will write to the popped stack frame in commandq_callback().

> +
> +	if (resp_len)
> +		*resp_len = cb_param.resp_len;
> +
> +	if (in_sgs > 0) {
> +		/*
> +		 * If we expect a response, make sure we have at least a
> +		 * response header - anything shorter is invalid.
> +		 */
> +		if (cb_param.resp_len < sizeof(*resp_header)) {
> +			v4l2_err(&vv->v4l2_dev,
> +				 "received response header is too short\n");
> +			return -EINVAL;
> +		}
> +
> +		resp_header = sg_virt(sgs[out_sgs]);
> +		if (resp_header->status)
> +			/* Host returns a positive error code. */\n> +			return -resp_header->status;
> +	}
> +
> +	return 0;
> +}

[Severity: Medium]
Can negating resp_header->status return a positive int or an invalid
errno?

resp_header->status is an unsigned 32-bit __le32.  If the device writes a
value with bit 31 set (for example, a negative 32-bit errno such as
0xffffffea), -resp_header->status evaluates in unsigned arithmetic and
converts to a positive int, which virtio_media_send_command() treats as
success because it only checks for ret < 0.  If resp_header->status is
between MAX_ERRNO + 1 (4096) and 0x80000000, the negative return value
propagates out of virtio_media_device_open() to VFS open, where
ERR_PTR(ret) does not satisfy IS_ERR() and is treated as a valid file
pointer.

Also, protocol fields marked __le32 in resp_header, cmd_open, resp_open,
and cmd_close are accessed directly without cpu_to_le32() and
le32_to_cpu(), which will trigger Sparse endianness warnings.

[ ... ]

> +static int virtio_media_device_close(struct file *file)
> +{
> +	struct video_device *video_dev = video_devdata(file);
> +	struct virtio_media *vv = to_virtio_media(video_dev);
> +	struct virtio_media_session *session =
> +		fh_to_session(file->private_data);
> +
> +	int ret = virtio_media_session_close(vv, session);
> +
> +	virtio_media_session_remove(vv, session);
> +	virtio_media_session_free(session);
> +
> +	return ret;
> +}
[ ... ]
> +static void virtio_media_remove(struct virtio_device *virtio_dev)
> +{
> +	struct virtio_media *vv = virtio_dev->priv;
> +	struct list_head *p, *n;
> +
> +	/* Remove the video device to stop accessing the commandq virtqueue */
> +	video_unregister_device(&vv->video_dev);
> +
> +	/*
> +	 * Acquire vlock to ensure no concurrent accesses to the commandq
> +	 * virtqueue
> +	 */
> +	mutex_lock(&vv->vlock);
> +
> +	/* Stop all virtqueue callbacks */
> +	virtio_reset_device(virtio_dev);
> +
> +	/*
> +	 * Only detach the unused buffers to allow internal virtqueue clean up.
> +	 * The actual buffers are freed in virtio_media_release()
> +	 */
> +	while (virtqueue_detach_unused_buf(vv->commandq))
> +		;
> +
> +	/* Delete the virtqueues */
> +	virtio_dev->config->del_vqs(virtio_dev);
> +
> +	mutex_unlock(&vv->vlock);
> +
> +	list_for_each_safe(p, n, &vv->sessions) {
> +		struct virtio_media_session *s =
> +			list_entry(p, struct virtio_media_session, list);
> +
> +		virtio_media_session_remove(vv, s);
> +		virtio_media_session_free(s);
> +	}
> +
> +	v4l2_device_put(&vv->v4l2_dev);
> +}

[Severity: High]
What happens when an open V4L2 file descriptor is closed after
virtio_media_remove() runs?

CPU0                                  CPU1
virtio_media_remove()
  video_unregister_device()
  ...
  virtio_dev->config->del_vqs()
  list_for_each_safe(..., &vv->sessions)
    virtio_media_session_remove(vv, s)
    virtio_media_session_free(s)
      v4l2_fh_del(&s->fh, s->file)
        /* sets file->private_data = NULL */
      kfree(s)
                                      v4l2_release(file)
                                        virtio_media_device_close(file)
                                          session = fh_to_session(NULL)
                                          virtio_media_session_close(vv, NULL)
                                            cmd_close->hdr.cmd = ...
                                              <-- NULL pointer dereference

video_unregister_device() prevents new opens, but existing open file
descriptors still invoke virtio_media_device_close() when closed.  Because
virtio_media_remove() already destroyed vv->commandq, cleared
file->private_data via v4l2_fh_del(), and freed each session (while
iterating vv->sessions without holding vv->sessions_lock), closing the fd
afterward dereferences a NULL or freed session and accesses the deleted
vv->commandq virtqueue.

> diff --git a/include/uapi/linux/virtio_media.h b/include/uapi/linux/virtio_media.h
> new file mode 100644
> index 0000000000000..ad05d742165c7
> --- /dev/null
> +++ b/include/uapi/linux/virtio_media.h
> @@ -0,0 +1,118 @@
[ ... ]
> +/**
> + * struct virtio_media_config - Video device configuration space.
> + * @device_caps: flags representing the device capabilities as used in &struct
> + *               v4l2_capability. It corresponds with the device_caps field in
> + *               the &struct video_device
> + * @ device_type: informs the driver of the type of the video device. It
> + *                corresponds to with the ``vfl_devnod_type`` field of the
> + *                device.
[ ... ]
> +#endif // _UAPI__LINUX_VIRTIO_MEDIA_H

[Severity: Low]
The space in "@ device_type:" prevents kernel-doc from recognizing the
member description, and the trailing "//" comment on #endif violates C90
comment rules for exported UAPI headers.  In addition,
drivers/media/virtio/session.h and drivers/media/virtio/virtio_media.h use
__dma_from_device_group_begin() and __dma_from_device_group_end() without
including <linux/dma-mapping.h>, and kernel-doc warns on those macros
inside kernel-doc annotated structs.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261120215916.3149345-1-briandaniels@google.com?part=1

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

* Re: [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll
  2026-11-20 21:59 ` [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll Brian Daniels
@ 2026-11-20 22:21   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-11-20 22:21 UTC (permalink / raw)
  To: Brian Daniels; +Cc: virtualization, media-ci, Michael S. Tsirkin, Eugenio Perez

Thank you for your contribution! Sashiko AI review found 17 potential
issues to consider:
- [High] media: virtio: avoid DMA mapping kernel stack buffers in
  add_data()
- [High] media: virtio: deadlock between vlock and events_lock in event
  processing
- [High] media: virtio: session use-after-free in
  virtio_media_process_events()
- [High] media: virtio: use-after-free and OOB in reqbufs and
  create_bufs
- [High] media: virtio: unsynchronized queue state in
  virtio_media_process_dqbuf_event()
- [High] media: virtio: broken EPOLLIN EOS and EPOLLOUT checks in poll()
- [High] media: virtio: cancel_work_sync() before reset in remove and
  probe
- [High] media: virtio: OOB queue->buffers and leak in
  reqbufs()/create_bufs()
- [High] media: virtio: O_NONBLOCK bugs and STREAMOFF hang in
  virtio_media_dqbuf()
- [High] media: virtio: session UAF in virtio_media_dqbuf() on
  virtio_media_remove()
- [High] media: virtio: unchecked multiplanar b->length in dqbuf and
  buffer ioctls
- [Medium] media: virtio: skip plane retrieval when b->length is 0 in
  buffer ioctls
- [Medium] media: virtio: video_register_device() called before
  populating eventq
- [Medium] media: virtio: SG index used as descriptor index in
  send_buffer_ioctl()
- [Medium] media: virtio: missing uses_mplane and cap checks in
  create_bufs()
- [Low] media: virtio: missing @error_lock kernel-doc in
  virtio_media_session
- [Low] media: virtio: uninitialized resp_len read in
  virtio_media_send_command()
--

commit befde615c261fefaf68e4ecec85b8fcfd0ccacb0
Author: Alexandre Courbot <gnurou@gmail.com>

media: virtio: Add buffer streaming, event handling, and poll

This commit adds V4L2 buffer queue state tracking, streaming and event
subscription ioctls, asynchronous event virtqueue processing, and poll
support to the virtio-media driver.

[Severity: High]
In drivers/media/virtio/scatterlist_builder.c (scatterlist_builder_add_data(),
lines 67 and 81; scatterlist_builder_add_buffer(), line 371) and
drivers/media/virtio/virtio_media_ioctls.c (virtio_media_streamon(), line 696),
does scatterlist_builder_add_data() map kernel stack buffers directly into
virtqueue scatterlists for DMA instead of staging them through the shadow
buffer?

video_usercopy() places ioctl arguments up to 128 bytes (such as struct
v4l2_buffer, struct v4l2_requestbuffers, struct v4l2_decoder_cmd, and struct
v4l2_event_subscription) into its stack buffer sbuf[128], and
virtio_media_streamon() and virtio_media_streamoff() pass the address of their
stack parameter i. When always_use_shadow_buffer is false,
scatterlist_builder_add_data() checks virt_addr_valid(data) and
is_vmalloc_addr(data) without checking !object_is_on_stack(data), mapping stack
pages directly via sg_set_page(). DMA-mapping the kernel stack violates the
DMA API, triggers CONFIG_DMA_API_DEBUG warnings, and risks stack corruption on
non-coherent architectures or with VIRTIO_F_ACCESS_PLATFORM.

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c (scatterlist_builder_add_buffer(),
line 375; scatterlist_builder_retrieve_buffer(), line 416) and
drivers/media/virtio/virtio_media_ioctls.c (virtio_media_send_buffer_ioctl(),
line 269), can scatterlist_builder_retrieve_buffer() fail with -ERANGE when
b->length is 0 on a multiplanar buffer?

In drivers/media/v4l2-core/v4l2-ioctl.c, check_array_args() only replaces
b->m.planes with a kernel buffer when b->length > 0, leaving the raw userspace
pointer in b->m.planes when b->length is 0. scatterlist_builder_add_buffer()
only adds a plane descriptor when b->length > 0, whereas
virtio_media_send_buffer_ioctl() saves orig_planes = b->m.planes unconditionally
for multiplanar types and scatterlist_builder_retrieve_buffer() calls
scatterlist_builder_retrieve_data() whenever orig_planes is non-NULL. Calling
VIDIOC_QBUF with b->length == 0 and a non-NULL b->m.planes pointer therefore
fails with -ERANGE after the host has already executed the ioctl, leaving the
guest and host queue states out of sync.

[Severity: Low]
In drivers/media/virtio/session.h (struct virtio_media_session, line 109), this
isn't a bug, but struct virtio_media_session adds the error_lock member without
a corresponding @error_lock entry in its kernel-doc comment block, which
triggers a scripts/kernel-doc warning under W=1 builds.

[Severity: High]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_process_dqbuf_event(),
lines 412 and 445) and drivers/media/virtio/virtio_media_ioctls.c
(virtio_media_qbuf(), line 935), is queue state accessed without consistent
synchronization between virtio_media_process_dqbuf_event() and the buffer
ioctls?

virtio_media_process_dqbuf_event() runs on vv->eventq_work holding
vv->events_lock (not vv->vlock) and reads queue->allocated_bufs and writes into
queue->buffers[dqbuf_evt->buffer.index] before acquiring session->queues_lock,
while virtio_media_reqbufs() and virtio_media_create_bufs() free and replace
queue->buffers under vv->vlock without holding session->queues_lock, allowing a
concurrent DQBUF event to write into freed memory.

In addition, virtio_media_qbuf() increments queue->queued_bufs without holding
session->queues_lock after virtio_media_send_buffer_ioctl() has already
submitted the buffer to the host, while virtio_media_process_dqbuf_event()
decrements queue->queued_bufs under session->queues_lock without holding
vv->vlock; if the host signals VIRTIO_MEDIA_EVT_DQBUF before virtio_media_qbuf()
increments queue->queued_bufs, queue->queued_bufs underflows to SIZE_MAX.
Finally, virtio_media_process_dqbuf_event() does not check under
session->queues_lock that the buffer is currently queued before calling
list_add_tail(&dqbuf->list, &queue->pending_dqbufs), so a duplicate or stale
DQBUF event corrupts the pending_dqbufs list.

[Severity: High]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_session_close(),
line 159; virtio_media_process_events(), line 471) and
drivers/media/virtio/virtio_media_ioctls.c (virtio_media_subscribe_event(),
line 660; virtio_media_device_ioctl(), line 1337), can
virtio_media_process_events() deadlock on vv->vlock and vv->events_lock when
handling VIRTIO_MEDIA_EVT_ERROR?

virtio_media_device_ioctl() holds vv->vlock across video_ioctl2(). When
virtio_media_subscribe_event() is called with V4L2_EVENT_SUB_FL_SEND_INITIAL,
it calls virtio_media_process_events(), which acquires vv->events_lock (lock
order vv->vlock -> vv->events_lock). If a VIRTIO_MEDIA_EVT_ERROR event is
processed, virtio_media_process_events() calls virtio_media_session_close(),
which tries to acquire vv->vlock (lock order vv->events_lock -> vv->vlock):

CPU0                              CPU1
----                              ----
lock(&vv->vlock)
                                  lock(&vv->events_lock)
lock(&vv->events_lock)
                                  lock(&vv->vlock)

 *** DEADLOCK ***

CPU0: virtio_media_device_ioctl() -> ... -> virtio_media_subscribe_event() ->
      virtio_media_process_events()
CPU1: virtio_media_event_work() -> virtio_media_process_events() ->
      virtio_media_session_close()

If VIRTIO_MEDIA_EVT_ERROR is processed directly inside the
virtio_media_subscribe_event() call, the same thread attempts to lock vv->vlock
a second time and self-deadlocks immediately.

[Severity: High]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_find_session(),
line 188; virtio_media_process_events(), line 483; virtio_media_device_close(),
line 628), can virtio_media_process_events() access a freed session when racing
with virtio_media_device_close()?

virtio_media_find_session() drops vv->sessions_lock before returning the session
pointer, and virtio_media_device_close() removes and frees the session without
acquiring vv->events_lock. In the VIRTIO_MEDIA_EVT_ERROR case,
virtio_media_process_events() also sets session->error = true before calling
virtio_media_session_close(), causing a racing virtio_media_device_close() to
skip virtio_media_session_close() (and its vv->vlock serialization) and free the
session immediately:

CPU0 (eventq_work)                CPU1 (close)
virtio_media_process_events()
  virtio_media_find_session()
  session->error = true
                                  virtio_media_device_close()
                                    if (!session_error) // false
                                    virtio_media_session_remove()
                                    virtio_media_session_free(session)
  virtio_media_session_close()
    ...                           <-- use-after-free
  wake_up(&session->dqbuf_wait)   <-- use-after-free

The same race applies to VIRTIO_MEDIA_EVT_DQBUF and VIRTIO_MEDIA_EVT_EVENT if
virtio_media_device_close() finishes between virtio_media_find_session() and the
event handler body.

[Severity: High]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_device_poll(),
line 676), do the EPOLLIN and EPOLLOUT checks in virtio_media_device_poll()
mishandle end-of-stream, output buffer readiness, and single-direction
streaming?

For EPOLLIN, once the last capture buffer (V4L2_BUF_FLAG_LAST) is dequeued,
capture_queue->is_capture_last is true while queued_bufs is 0 and
pending_dqbufs is empty. Because the first branch checks
(capture_queue->queued_bufs == 0 && list_empty(&capture_queue->pending_dqbufs))
without checking !capture_queue->is_capture_last, poll() returns EPOLLERR at
EOS instead of reaching the else-if branch to return EPOLLIN | EPOLLRDNORM.

For EPOLLOUT, checking output_queue->queued_bufs < output_queue->allocated_bufs
instead of !list_empty(&output_queue->pending_dqbufs) causes poll() to report
EPOLLOUT | EPOLLWRNORM whenever not all allocated output buffers are queued,
even when no completed output buffer is available in pending_dqbufs for
VIDIOC_DQBUF, causing non-blocking callers to spin in a busy loop receiving
-EAGAIN.

Furthermore, when an application polls for both events (or when wait is NULL on
a re-poll pass where poll_requested_events() has all bits set) while only one
queue is streaming, the non-streaming queue unconditionally sets EPOLLERR.

[Severity: Medium]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_probe(), line 808),
should the event buffers be queued on vv->eventq before calling
video_register_device()?

video_register_device() exposes the character device node to userspace
immediately, creating a window where userspace can open the device and trigger
host events before the virtio_media_send_event_buffer() loop has populated
vv->eventq.

[Severity: High]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_probe(), line 830;
virtio_media_remove(), line 854), can eventq_callback() re-schedule
vv->eventq_work after cancel_work_sync() in virtio_media_remove() and
virtio_media_probe()?

Both teardown paths call cancel_work_sync(&vv->eventq_work) before calling
virtio_reset_device(virtio_dev):

CPU0                              CPU1 (<hardirq>)
virtio_media_remove()
  cancel_work_sync(&vv->eventq_work)
                                  eventq_callback()
                                    schedule_work(&vv->eventq_work)
  mutex_lock(&vv->vlock)
  virtio_reset_device()
  del_vqs()
  v4l2_device_put() -> kfree(vv)
                                  virtio_media_event_work()
                                    ... <-- use-after-free

In addition, if virtio_media_send_event_buffer() fails partway through the loop
in virtio_media_probe(), the error path calls del_vqs() without draining the
already-queued event buffers via virtqueue_detach_unused_buf(vv->eventq).

[Severity: High]
In drivers/media/virtio/virtio_media_driver.c (virtio_media_remove(), line 879)
and drivers/media/virtio/virtio_media_ioctls.c (virtio_media_dqbuf(), line 989),
can virtio_media_remove() free an active session while virtio_media_dqbuf() is
sleeping on session->dqbuf_wait?

virtio_media_dqbuf() unlocks vv->vlock before sleeping in
wait_event_interruptible(session->dqbuf_wait, ...). Because
video_unregister_device() does not wait for in-flight ioctls on open file
descriptors to complete, virtio_media_remove() can acquire and release
vv->vlock, iterate over vv->sessions, and call virtio_media_session_free(s)
while a thread is still blocked in wait_event_interruptible() on
session->dqbuf_wait, causing a use-after-free when that thread wakes or is
interrupted.

[Severity: Low]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_send_buffer_ioctl(),
line 262) and drivers/media/virtio/virtio_media_driver.c
(virtio_media_send_command(), line 316), is resp_len read uninitialized when
virtio_media_send_buffer_ioctl() calls virtio_media_send_command()?

virtio_media_send_buffer_ioctl() declares size_t resp_len without initializing
it (unlike virtio_media_send_ext_controls_ioctl(), which initializes
resp_len = 0), and virtio_media_send_command() evaluates
size_t local_resp_len = resp_len ? *resp_len : 0 before writing to *resp_len.

[Severity: Medium]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_send_buffer_ioctl(),
line 282), does the response loop in virtio_media_send_buffer_ioctl() pass an
SG pointer index to scatterlist_builder_add_descriptor() where a descriptor
table index is expected?

end_buf_sg is initialized from builder.cur_sg (an index into builder.sgs), but
scatterlist_builder_add_descriptor(&builder, i) indexes builder->descs[i]. If a
vmalloc-backed buffer added by scatterlist_builder_add_data() spans two
non-contiguous physical pages, it consumes two entries in builder->descs while
advancing builder->cur_sg by one, so passing i to
scatterlist_builder_add_descriptor() attaches the wrong descriptor to the
device-writable response chain.

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_reqbufs(), line 743;
virtio_media_create_bufs(), line 839), can virtio_media_create_bufs() and
virtio_media_reqbufs() leave dangling list pointers in queue->pending_dqbufs?

Each struct virtio_media_buffer in queue->buffers has a list_head linked into
queue->pending_dqbufs while waiting to be dequeued. virtio_media_create_bufs()
shallow-copies queue->buffers into a newly allocated buffers array via memcpy()
and calls vfree(queue->buffers) without updating the list pointers in
queue->pending_dqbufs. Similarly, virtio_media_reqbufs() only calls
virtio_media_clear_queue() when b->count == 0, so calling VIDIOC_REQBUFS with
b->count > 0 while completed buffers are pending frees queue->buffers while
leaving them linked in queue->pending_dqbufs. Any subsequent VIDIOC_DQBUF,
VIDIOC_STREAMOFF, or VIRTIO_MEDIA_EVT_DQBUF will dereference the freed
queue->buffers allocation.

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_reqbufs(), line 743;
virtio_media_create_bufs(), line 839), can queue->allocated_bufs exceed the size
of the queue->buffers allocation in virtio_media_reqbufs() and
virtio_media_create_bufs()?

Both functions allocate buffers with vcalloc() using the caller's requested
b->count before sending the ioctl to the host, and afterwards set
queue->allocated_bufs = b->count (in virtio_media_reqbufs()) or
queue->allocated_bufs = b->index + b->count (in virtio_media_create_bufs()). In
V4L2, drivers and devices may increase count to meet minimum buffer requirements;
if the host returns a larger b->count (or a larger b->index + b->count),
queue->allocated_bufs will be larger than the allocated array, leading to
out-of-bounds accesses on queue->buffers.

Also, in virtio_media_create_bufs(), if b->count > 0 on entry and the host
returns b->count == 0 with status 0, the early return on b->count == 0 leaks
the pre-allocated buffers array.

[Severity: Medium]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_create_bufs(),
line 813) and drivers/media/virtio/virtio_media_driver.c
(virtio_media_device_poll(), line 654), should virtio_media_create_bufs() update
session->uses_mplane, reject V4L2_MEMORY_USERPTR, and mask unsupported
b->capabilities flags like virtio_media_reqbufs() does?

When a multiplanar session allocates buffers via VIDIOC_CREATE_BUFS instead of
VIDIOC_REQBUFS, session->uses_mplane remains false, causing
virtio_media_device_poll() to check the unallocated single-planar queues and
return EPOLLERR.

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_clear_queue(),
line 473; virtio_media_dqbuf(), line 976) and
drivers/media/virtio/virtio_media_driver.c (virtio_media_session_alloc(),
line 65), can a thread blocked in virtio_media_dqbuf() hang indefinitely when
streaming is stopped, or block unexpectedly in non-blocking mode?

When virtio_media_clear_queue() stops streaming on VIDIOC_STREAMOFF or
VIDIOC_REQBUFS(0), it sets queue->streaming = false and clears pending_dqbufs,
but it does not call wake_up(&session->dqbuf_wait), and wait_event_interruptible()
in virtio_media_dqbuf() only checks !list_empty(buffer_queue) || session->error
(not !queue->streaming), leaving blocked VIDIOC_DQBUF callers asleep forever.

In addition, when session->nonblocking_dequeue is true in virtio_media_dqbuf():
- the else-if chain skips the queue->allocated_bufs == 0 and !queue->streaming
  checks, returning -EAGAIN instead of -EINVAL;
- if buffer_queue is non-empty, virtio_media_dqbuf() still drops vv->vlock and
  enters wait_event_interruptible(), where a racing consumer can empty the
  queue and cause a non-blocking call to sleep (or return -EIO if another thread
  dequeues the buffer before vv->vlock is re-acquired);
- session->nonblocking_dequeue is only snapshotted at open() time in
  virtio_media_session_alloc(), ignoring later fcntl(F_SETFL, O_NONBLOCK)
  changes to file->f_flags.

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c (virtio_media_send_buffer_ioctl(),
line 269; virtio_media_dqbuf(), line 1029) and
drivers/media/virtio/scatterlist_builder.c (scatterlist_builder_retrieve_buffer(),
line 416), can overwriting b->length in virtio_media_dqbuf() and
virtio_media_send_buffer_ioctl() trigger an out-of-bounds kernel read when
copying planes back to userspace?

In drivers/media/v4l2-core/v4l2-ioctl.c, check_array_args() allocates the kernel
plane array b->m.planes (array_buf) sized to the caller's input b->length.
virtio_media_dqbuf() copies min_t(u32, b->length, VIDEO_MAX_PLANES) planes into
b->m.planes, and then memcpy(b, &dqbuf->buffer, sizeof(*b)) overwrites b->length
with dqbuf->buffer.length (and virtio_media_send_buffer_ioctl() similarly lets
the host response overwrite b->length). If the caller passed a smaller
b->length (for example, 1 plane on a 2-plane format) via a 32-bit compat ioctl,
v4l2_compat_put_array_args() in drivers/media/v4l2-core/v4l2-compat-ioctl32.c
iterates over the overwritten b->length and reads past the end of array_buf,
leaking adjacent kernel heap memory to userspace.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261120215916.3149345-1-briandaniels@google.com?part=4

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

* Re: [PATCH v11 3/6] media: virtio: Add extended controls support
  2026-11-20 21:59 ` [PATCH v11 3/6] media: virtio: Add extended controls support Brian Daniels
@ 2026-11-20 22:23   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-11-20 22:23 UTC (permalink / raw)
  To: Brian Daniels; +Cc: virtualization, media-ci, Michael S. Tsirkin, Eugenio Perez

Thank you for your contribution! Sashiko AI review found 15 potential
issues to consider:
- [High] media: virtio: framevecs array leak in
  scatterlist_builder_free_framevecs()
- [High] media: virtio: pinned page and framevec leak on error in
  virtio_media_send_ext_controls_ioctl()
- [High] media: virtio: unchecked and unrestored ctrls->count in
  virtio_media_send_ext_controls_ioctl()
- [High] media: virtio: sgs index passed as desc_index in
  virtio_media_send_ext_controls_ioctl()
- [High] media: virtio: stack buffers mapped for DMA in
  scatterlist_builder_add_data()
- [Medium] media: virtio: missing return on framevec exhaustion in
  __scatterlist_builder_add_userptr()
- [Medium] media: virtio: unpinned writable user pages not marked dirty
  in scatterlist_builder_free_framevecs()
- [Medium] media: virtio: __scatterlist_builder_add_userptr() converts
  -EFAULT to -EINVAL for control pointers
- [Medium] media: virtio: gfp_mask = 0 passed to
  sg_alloc_table_from_pages() in __scatterlist_builder_add_userptr()
- [Medium] media: virtio: builder->framevecs leak in
  scatterlist_builder_free_framevecs()
- [Medium] media: virtio: missing return on framevec overflow in
  __scatterlist_builder_add_userptr()
- [Low] media: virtio: duplicate shadow buffer copy in
  scatterlist_builder_add_userptr()
- [Low] media: virtio: missing endian conversions on
  virtio_media_sg_entry and kernel-doc mismatch
- [Low] media: virtio: kernel-doc and num_framevecs init mismatch in
  scatterlist_builder
- [Low] media: virtio: missing cpu_to_le64()/cpu_to_le32() in
  __scatterlist_builder_add_userptr()
--

commit 4bce5e6699b198a30ba3d3b14cac75e70807d014
Author: Alexandre Courbot <gnurou@gmail.com>

media: virtio: Add extended controls support

This commit adds V4L2 extended control ioctl handlers (VIDIOC_G_EXT_CTRLS,
VIDIOC_S_EXT_CTRLS, and VIDIOC_TRY_EXT_CTRLS) to virtio-media, along with
scatterlist builder helpers to pin userspace control payloads and pass their
physical segments to the host via the session shadow buffer.

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c, inside
__scatterlist_builder_add_userptr() (lines 264-268), does the capacity check
on builder->cur_framevec >= builder->num_framevecs forget to return after
setting ret = -ENOMEM? Execution continues to sg_alloc_table_from_pages(),
which overwrites ret, and then writes past the end of builder->framevecs at
line 316 (or dereferences NULL). In addition,
scatterlist_builder_allocate_framevecs() (line 407) resets
builder->cur_framevec = 0 without resetting builder->num_framevecs = 0 before
accumulating the count.

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c, at lines 264-268 of
__scatterlist_builder_add_userptr(), should the builder->cur_framevec >=
builder->num_framevecs branch return -ENOMEM immediately instead of falling
through to pin pages and write out of bounds to
builder->framevecs[builder->cur_framevec++] at line 316?

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c, inside
__scatterlist_builder_add_userptr() (lines 271-279), why is -EFAULT from
vb2_create_framevec() converted into -EINVAL? The V4L2 extended control ioctls
(and the function's own kernel-doc comment at line 243) require -EFAULT when a
control payload pointer references an invalid userspace address.

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c, inside
__scatterlist_builder_add_userptr() (lines 289-290), should
sg_alloc_table_from_pages() use GFP_KERNEL instead of 0 for its gfp_mask?
This path runs in sleepable ioctl process context right after GFP_KERNEL
allocations, and passing 0 disables direct reclaim, kswapd reclaim, IO, and FS
operations, which can cause spurious -ENOMEM failures under memory pressure.

[Severity: Low]
In drivers/media/virtio/scatterlist_builder.c, inside
__scatterlist_builder_add_userptr() (lines 311-312), sg_entry->start and
sg_entry->len are declared as __le64 and __le32 in struct
virtio_media_sg_entry (include/uapi/linux/virtio_media.h, lines 168-172), so
assigning sg_phys(sg_iter) and sg_iter->length without cpu_to_le64() and
cpu_to_le32() triggers Sparse endianness warnings. Also, struct
scatterlist_builder in drivers/media/virtio/scatterlist_builder.h (lines
28-32 and 78-80) is missing a @num_framevecs kernel-doc entry.

[Severity: Low]
In drivers/media/virtio/scatterlist_builder.c, inside
__scatterlist_builder_add_userptr() (lines 305-306), sg_list is already
allocated inside builder->shadow_buffer, yet scatterlist_builder_add_userptr()
(lines 351-352) passes sg_list to scatterlist_builder_add_data(). When
always_use_shadow_buffer is enabled, scatterlist_builder_add_data() copies
sg_list into builder->shadow_buffer a second time and consumes double the
shadow buffer space.

[Severity: High]
In drivers/media/virtio/scatterlist_builder.c, when
scatterlist_builder_add_ext_ctrls() (lines 374-385) passes ctrls and
ctrls->controls to scatterlist_builder_add_data() (lines 67-118), can this map
kernel stack memory directly for DMA? Both video_usercopy() (which places
struct v4l2_ext_controls in its stack buffer sbuf) and v4l_g_ctrl() /
v4l_s_ctrl() (which allocate struct v4l2_ext_controls and struct
v4l2_ext_control on the stack) pass stack addresses here. Because stack
addresses satisfy virt_addr_valid() when CONFIG_VMAP_STACK=n and
is_vmalloc_addr() when CONFIG_VMAP_STACK=y, scatterlist_builder_add_data()
maps the stack pages directly into virtqueue scatterlists instead of bouncing
them through builder->shadow_buffer, violating the DMA API.

[Severity: Low]
In drivers/media/virtio/scatterlist_builder.h (lines 28-32 and 78-80), the
kernel-doc comment for struct scatterlist_builder omits @num_framevecs and
names scatterlist_builder_add_ext_ctrls_userptrs() and
scatterlist_builder_retrieve_ext_ctrls() instead of
scatterlist_builder_allocate_framevecs() and
scatterlist_builder_free_framevecs(). In
drivers/media/virtio/scatterlist_builder.c, the kernel-doc for
__scatterlist_builder_add_userptr() (line 243) also documents returning
-EFAULT on an invalid userptr while line 277 rewrites it to -EINVAL, and
scatterlist_builder_allocate_framevecs() (line 407) resets
builder->cur_framevec = 0 without initializing builder->num_framevecs = 0.

[Severity: High]
In drivers/media/virtio/scatterlist_builder.c, does
scatterlist_builder_free_framevecs() (lines 439-448) leak builder->framevecs
when builder->cur_framevec is 0? scatterlist_builder_allocate_framevecs()
(lines 417-418) allocates builder->framevecs whenever at least one control has
ctrl->size > 0, so if an error occurs before the first framevec is recorded
(for example, vb2_create_framevec() fails on the first control pointer),
kfree(builder->framevecs) is skipped and builder->framevecs is set to NULL.

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c, inside
scatterlist_builder_free_framevecs() (lines 439-448), kfree(builder->framevecs)
is guarded by builder->cur_framevec, so failing before the first framevec is
added leaks the builder->framevecs array.

[Severity: Medium]
In drivers/media/virtio/scatterlist_builder.c,
__scatterlist_builder_add_userptr() (line 270) pins user control payload pages
as writable via vb2_create_framevec(userptr, length, true), but
scatterlist_builder_free_framevecs() (lines 442-445) unpins them with
vb2_destroy_framevec() without marking them dirty first. Should it call
set_page_dirty_lock() on the frame_vector_pages() before destroying the
framevec, as the videobuf2 memops backends do, so host writes to reclaimable
or file-backed user pages are not lost?

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c, inside
virtio_media_send_ext_controls_ioctl() (lines 281 and 295-299), end_ctrls_sg
is saved from builder.cur_sg (an index into builder.sgs[]), but the response
loop passes i to scatterlist_builder_add_descriptor(&builder, i), which
indexes builder.descs[i] (drivers/media/virtio/scatterlist_builder.c, line
41). If a precedingvmalloc buffer spans multiple non-contiguous physical
pages, scatterlist_builder_add_data() uses multiple builder.descs[] entries
for a single builder.sgs[] entry, causing the response chain to point at the
wrong descriptors.

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c, inside
virtio_media_send_ext_controls_ioctl(), do the early error returns at lines
313-314 (return -ENOSPC when ctrls->count > num_ctrls) and lines 337-338
(return -EINVAL when resp_len < sizeof(*ctrls)) bypass the free_framevecs
label? Returning directly leaks builder.framevecs and all struct frame_vector
instances and leaves the userspace payload pages permanently pinned.

[Severity: High]
In drivers/media/virtio/virtio_media_ioctls.c, inside
virtio_media_send_ext_controls_ioctl() (lines 308-341), ctrls->count is
checked against num_ctrls before scatterlist_builder_retrieve_ext_ctrls()
copies the shadow buffer response back into ctrls, and ctrls->count is not
restored to num_ctrls when the device returns ctrls->count > num_ctrls. When
the shadow buffer is used, scatterlist_builder_retrieve_ext_ctrls()
(drivers/media/virtio/scatterlist_builder.c, lines 509-523) overwrites
ctrls->count with the unvalidated value from the shadow buffer after the
check; and because extended control ioctls set INFO_FL_ALWAYS_COPY, leaving
ctrls->count > num_ctrls on return causes v4l2_compat_put_array_args() and
v4l_print_ext_controls() to read past the end of the kernel controls array.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261120215916.3149345-1-briandaniels@google.com?part=3

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

* Re: [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack
  2026-11-20 21:59 ` [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack Brian Daniels
@ 2026-11-20 22:25   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-11-20 22:25 UTC (permalink / raw)
  To: Brian Daniels; +Cc: virtualization, media-ci, Michael S. Tsirkin, Eugenio Perez

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] media: virtio: incomplete stack initialization in
  virtio_media_legacy_ctrl()
--

commit d098c9e95ded482f86a03623164a3f51eaba79ca
Author: Nick Rogers <nick@getfieldwork.ai>

media: virtio: clear the size of legacy controls built on the stack

This commit adds virtio_media_legacy_ctrl() to zero out the size field of
stack-allocated v4l2_ext_control entries before forwarding extended control
ioctls to the virtio host.

> diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/virtio/virtio_media_ioctls.c
> index aa56efe9a08c2..ad240073aec9f 100644
> --- a/drivers/media/virtio/virtio_media_ioctls.c
> +++ b/drivers/media/virtio/virtio_media_ioctls.c
[ ... ]
> @@ -593,11 +594,31 @@ static int virtio_media_querycap(struct file *file, void *fh,
>   * Extended control ioctls are handled mostly identically.
>   */
>  
> +/*
> + * VIDIOC_G_CTRL and VIDIOC_S_CTRL reach a driver without a control handler
> + * as one extended control the V4L2 core builds on its own stack, with its
> + * size left uninitialized. They carry a 32-bit value and never a payload,
> + * so a size there is stack garbage, which would be sent as a user pointer
> + * to copy and fail the ioctl. An array from userspace is never on the
> + * stack: the core copies it into an allocation.
> + */
> +static void virtio_media_legacy_ctrl(struct v4l2_ext_controls *ctrls)
> +{
> +	u32 i;
> +
> +	if (!ctrls->count || !object_is_on_stack(ctrls->controls))
> +		return;
> +	for (i = 0; i < ctrls->count; i++)
> +		ctrls->controls[i].size = 0;
> +}
> +
>  static int virtio_media_g_ext_ctrls(struct file *file, void *fh,
>  				    struct v4l2_ext_controls *ctrls)
>  {
>  	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
>  
> +	virtio_media_legacy_ctrl(ctrls);
> +
>  	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_G_EXT_CTRLS,
>  						    ctrls);
>  }
> @@ -607,6 +628,8 @@ static int virtio_media_s_ext_ctrls(struct file *file, void *fh,
>  {
>  	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
>  
> +	virtio_media_legacy_ctrl(ctrls);
> +
>  	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_S_EXT_CTRLS,
>  						    ctrls);
>  }
> @@ -616,6 +639,8 @@ static int virtio_media_try_ext_ctrls(struct file *file, void *fh,
>  {
>  	struct v4l2_fh *vfh = file_to_v4l2_fh(file);
>  
> +	virtio_media_legacy_ctrl(ctrls);
> +
>  	return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_TRY_EXT_CTRLS,
>  						    ctrls);
>  }

[Severity: Medium]
Does clearing only controls[i].size in virtio_media_legacy_ctrl() still leave
other fields of ctrls and ctrls->controls[i] uninitialized on the stack?

In v4l_g_ctrl() and v4l_s_ctrl(), both struct v4l2_ext_controls ctrls and
struct v4l2_ext_control ctrl are declared on the stack without
zero-initialization, and only ctrls.which, ctrls.count, ctrls.controls,
ctrl.id, and the 32-bit ctrl.value member are assigned (with check_ext_ctrls()
clearing ctrls.reserved[0] and ctrl.reserved2[0]).  That leaves
ctrls->error_idx, ctrls->request_fd, struct padding, and the upper 32 bits of
the 64-bit union in ctrl.value64 holding stack garbage when
scatterlist_builder_add_ext_ctrls() sends both full structures to the host.
In addition to leaking 16 bytes of guest kernel stack to the host on every
VIDIOC_G_CTRL and VIDIOC_S_CTRL call, a VIDIOC_S_CTRL targeting a 64-bit host
control will pass stack garbage in the upper 32 bits of ctrl.value64.

Also, VIDIOC_G_CTRL and VIDIOC_S_CTRL never call vidioc_try_ext_ctrls, so
virtio_media_try_ext_ctrls() has no legacy stack-allocated caller.  Rather
than detecting stack pointers with object_is_on_stack() in the driver, could
v4l_g_ctrl() and v4l_s_ctrl() in drivers/media/v4l2-core/v4l2-ioctl.c
zero-initialize ctrls and ctrl directly?

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261120215916.3149345-1-briandaniels@google.com?part=6

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

* Re: [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure
  2026-11-20 21:59 ` [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure Brian Daniels
@ 2026-11-20 22:25   ` sashiko-bot
  0 siblings, 0 replies; 13+ messages in thread
From: sashiko-bot @ 2026-11-20 22:25 UTC (permalink / raw)
  To: Brian Daniels; +Cc: virtualization, media-ci, Michael S. Tsirkin, Eugenio Perez

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [High] media: virtio: DMA mapping of kernel stack in
  scatterlist_builder_add_data()
- [High] media: virtio: pfn_to_kaddr() build and KASAN bug in
  retrieve_data()
- [High] media: virtio: session use-after-free on unbind in
  virtio_media_remove()
- [High] media: virtio: V4L2 core and compat bypass in
  virtio_media_device_ioctl()
- [Medium] media: virtio: unaligned shadow_buffer_pos in
  scatterlist_builder_add_data()
- [Medium] media: virtio: missing NUL-termination of cap->card in
  virtio_media_querycap()
- [Medium] media: virtio: uninitialized stack variables in
  virtio_media_g_input/output()
--

commit 2de20993548662c5f3f30aa219959343b41cbc39
Author: Alexandre Courbot <gnurou@gmail.com>

media: virtio: Add V4L2 ioctl forwarding infrastructure

This commit introduces a scatterlist builder and synchronous V4L2 ioctl
forwarding via VIRTIO_MEDIA_CMD_IOCTL, implementing VIDIOC_QUERYCAP and
fixed-size V4L2 ioctls.

> diff --git a/drivers/media/virtio/scatterlist_builder.c b/drivers/media/virtio/scatterlist_builder.c
> new file mode 100644
> index 0000000000000..ae8ffee82fa6e
> --- /dev/null
> +++ b/drivers/media/virtio/scatterlist_builder.c
[ ... ]
> +int scatterlist_builder_add_data(struct scatterlist_builder *builder,
> +				 void *data, size_t len)
> +{
> +	const size_t cur_desc = builder->cur_desc;
> +
> +	if (len == 0)
> +		return 0;
> +
> +	if (builder->cur_desc >= builder->num_descs)
> +		return -ENOSPC;
> +
> +	if (!always_use_shadow_buffer && virt_addr_valid(data) &&
> +	    virt_addr_valid(data + len)) {
> +		/*
> +		 * If "data" is in the 1:1 physical memory mapping then we can
> +		 * use a single SG entry and avoid copying.
> +		 */
> +		struct page *page = virt_to_page(data);
> +		size_t offset = (((size_t)data) & ~PAGE_MASK);
> +		struct scatterlist *next_desc =
> +			&builder->descs[builder->cur_desc];
> +
> +		memset(next_desc, 0, sizeof(*next_desc));
> +		sg_set_page(next_desc, page, len, offset);
> +		builder->cur_desc++;
> +	} else if (!always_use_shadow_buffer && is_vmalloc_addr(data)) {

[Severity: High]
Does scatterlist_builder_add_data() map kernel stack buffers directly for
DMA instead of falling back to builder->shadow_buffer?

Both video_usercopy() (for ioctl arguments up to 128 bytes) and handlers
such as virtio_media_g_input() and virtio_media_device_ioctl() pass
stack-allocated buffers here.  When CONFIG_VMAP_STACK=y, stack addresses
satisfy is_vmalloc_addr(data); when CONFIG_VMAP_STACK=n, they satisfy
virt_addr_valid(data).  Without checking !object_is_on_stack(data), stack
pages are placed directly into the virtqueue scatterlist, violating the DMA
API contract when DMA mapping is used (triggering CONFIG_DMA_API_DEBUG
check_for_stack() warnings and risking stack corruption on non-coherent
platforms).

Also, virt_addr_valid(data + len) checks one byte past the end of the
buffer rather than data + len - 1.

[ ... ]

> +	} else {
> +		/*
> +		 * As a last resort, copy into the shadow buffer and reference
> +		 * it with a single SG entry. Calling
> +		 * scatterlist_builder_retrieve_data() will be necessary to copy
> +		 * the data written by the device back into @data.
> +		 */
> +		void *shadow_buffer =
> +			builder->shadow_buffer + builder->shadow_buffer_pos;
> +		struct page *page = virt_to_page(shadow_buffer);
> +		unsigned long offset =
> +			(((unsigned long)shadow_buffer) & ~PAGE_MASK);
> +		struct scatterlist *next_desc =
> +			&builder->descs[builder->cur_desc];
> +
> +		if (len >
> +		    builder->shadow_buffer_size - builder->shadow_buffer_pos)
> +			return -ENOSPC;
> +
> +		memcpy(shadow_buffer, data, len);
> +		memset(next_desc, 0, sizeof(*next_desc));
> +		sg_set_page(next_desc, page, len, offset);
> +		builder->cur_desc++;
> +		builder->shadow_buffer_pos += len;
> +	}

[Severity: Medium]
Can advancing builder->shadow_buffer_pos by an unaligned len pack separate
DMA_TO_DEVICE and DMA_FROM_DEVICE descriptors into the same DMA cacheline?

When multiple descriptors use the shadow buffer (for example, cmd_ioctl at
12 bytes followed by resp_ioctl at 8 bytes and the response payload),
packing them at unaligned offsets shares a single cacheline across
bidirectional DMA mappings and leaves subsequent shadow buffer entries
misaligned.  In addition, this path unconditionally runs
memcpy(shadow_buffer, data, len) even when staging device-writable (_IOR)
response buffers.

[ ... ]

> +int scatterlist_builder_retrieve_data(struct scatterlist_builder *builder,
> +				      size_t sg_index, void *data)
> +{
> +	void *shadow_buf = builder->shadow_buffer;
> +	struct scatterlist *sg;
> +	void *kaddr;
> +
> +	/* We can only retrieve from the range of sgs currently set. */
> +	if (sg_index >= builder->cur_sg)
> +		return -ERANGE;
> +
> +	sg = builder->sgs[sg_index];
> +	kaddr = pfn_to_kaddr(page_to_pfn(sg_page(sg))) + sg->offset;
> +
> +	if (kaddr >= shadow_buf &&
> +	    kaddr < shadow_buf + builder->shadow_buffer_size) {
> +		if (kaddr + sg->length >
> +		    shadow_buf + builder->shadow_buffer_size)
> +			return -EINVAL;
> +
> +		memcpy(data, kaddr, sg->length);
> +	}
> +
> +	return 0;
> +}

[Severity: High]
Should this use sg_virt(sg) instead of
pfn_to_kaddr(page_to_pfn(sg_page(sg))) + sg->offset?

On powerpc, pfn_to_kaddr() returns const void *, failing compilation with
-Werror=discarded-qualifiers when assigned to void *kaddr, and on alpha and
x86_64 UML pfn_to_kaddr() is not defined.  On arm64 with tag-based KASAN
(CONFIG_KASAN_SW_TAGS or CONFIG_KASAN_HW_TAGS), pfn_to_kaddr() returns an
untagged linear address (top byte 0xff) while shadow_buf from kzalloc()
carries a KASAN tag, so the shadow_buf range check evaluates to false and
silently skips copying the device response back into data.

> diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/virtio/virtio_media_driver.c
> index 39c5a38d20b1b..0fe20cf508212 100644
> --- a/drivers/media/virtio/virtio_media_driver.c
> +++ b/drivers/media/virtio/virtio_media_driver.c
[ ... ]
> @@ -77,6 +94,9 @@ static void virtio_media_session_free(struct virtio_media_session *session)
>  	virtio_media_session_fh_del(session);
>  	v4l2_fh_exit(&session->fh);
>  
> +	sg_free_table(&session->command_sgs);
> +
> +	kfree(session->shadow_buf);
>  	kfree(session);
>  }

[Severity: High]
Can session->command_sgs, session->shadow_buf, and session be used after
free and double freed if the device is removed while a file descriptor is
open?

virtio_media_remove() frees all sessions in vv->sessions via
virtio_media_session_free() while open struct file instances still reference
session->fh:

drivers/media/virtio/virtio_media_driver.c:virtio_media_remove() {
    ...
	list_for_each_safe(p, n, &vv->sessions) {
		struct virtio_media_session *s =
			list_entry(p, struct virtio_media_session, list);

		virtio_media_session_remove(vv, s);
		virtio_media_session_free(s);
	}
    ...
}

When userspace later closes the file descriptor, v4l2_release() invokes
virtio_media_device_close(), which accesses the freed session and calls
virtio_media_session_free(session) a second time:

CPU0                              CPU1
virtio_media_remove()
  video_unregister_device(...)
  ...
  virtio_media_session_free(s)
    sg_free_table(&s->command_sgs)
    kfree(s->shadow_buf)
    kfree(s)
                                  v4l2_release()
                                    virtio_media_device_close()
                                      virtio_media_session_close(vv, s)
                                        <-- use-after-free
                                      virtio_media_session_free(s)
                                        <-- double free

> diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/virtio/virtio_media_ioctls.c
> new file mode 100644
> index 0000000000000..e92032bce7dbe
> --- /dev/null
> +++ b/drivers/media/virtio/virtio_media_ioctls.c
[ ... ]
> +static int virtio_media_querycap(struct file *file, void *fh,
> +				 struct v4l2_capability *cap)
> +{
> +	struct video_device *video_dev = video_devdata(file);
> +	struct virtio_media *vv = to_virtio_media(video_dev);
> +
> +	strscpy(cap->bus_info, "platform:virtio-media");
> +	strscpy(cap->driver, VIRTIO_MEDIA_DEFAULT_DRIVER_NAME);
> +
> +	virtio_cread_bytes(vv->virtio_dev, 8, cap->card, sizeof(cap->card));
> +
> +	cap->capabilities = video_dev->device_caps | V4L2_CAP_DEVICE_CAPS;
> +	cap->device_caps = video_dev->device_caps;
> +
> +	return 0;
> +}

[Severity: Medium]
Can virtio_media_querycap() leave cap->card without a NUL terminator?

In include/uapi/linux/virtio_media.h, struct virtio_media_config documents
that card does not need to be NUL-terminated when all 32 bytes are used,
whereas V4L2 requires struct v4l2_capability.card to be a NUL-terminated
string.

> +/*
> + * s/g_input/output work with an unsigned int - recast this to a u32 so the
> + * size is unambiguous.
> + */
> +
> +static int virtio_media_g_input(struct file *file, void *fh, unsigned int *i)
> +{
> +	u32 input;
> +
> +	int ret = virtio_media_send_r_ioctl(file_to_v4l2_fh(file),
> +					 VIDIOC_G_INPUT, &input,
> +					 sizeof(input));
> +	if (ret)
> +		return ret;
> +
> +	*i = input;
> +
> +	return 0;
> +}

[Severity: Medium]
Does virtio_media_g_input() (and virtio_media_g_output() below) pass
uninitialized stack memory to scatterlist_builder_add_data()?

Because input and output are not initialized before calling
virtio_media_send_r_ioctl(), the shadow buffer fallback in
scatterlist_builder_add_data() reads 4 bytes of uninitialized stack memory
via memcpy(shadow_buffer, data, len), and an incomplete host write leaves
uninitialized stack bytes in *i or *o.

[ ... ]

> +long virtio_media_device_ioctl(struct file *file, unsigned int cmd,
> +			       unsigned long arg)
> +{
> +	struct video_device *video_dev = video_devdata(file);
> +	struct virtio_media *vv = to_virtio_media(video_dev);
> +	struct v4l2_fh *vfh = NULL;
> +	struct v4l2_standard standard;
> +	v4l2_std_id std_id = 0;
> +	int ret;
> +
> +	if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags))
> +		vfh = file_to_v4l2_fh(file);
> +
> +	mutex_lock(&vv->vlock);
> +
> +	/*
> +	 * We need to handle a few ioctls manually because their results
> +	 * rely on vfd->tvnorms, which is normally updated by the driver
> +	 * as S_INPUT is called. Since we want to just pass these ioctls
> +	 * through, we have to hijack them from here.
> +	 */
> +	switch (cmd) {
> +	case VIDIOC_S_STD:
> +		ret = copy_from_user(&std_id, (void __user *)arg,
> +				     sizeof(std_id));
> +		if (ret) {
> +			ret = -EFAULT;
> +			break;
> +		}
> +		ret = virtio_media_s_std(file, vfh, std_id);
> +		break;
> +	case VIDIOC_ENUMSTD:
> +		ret = copy_from_user(&standard, (void __user *)arg,
> +				     sizeof(standard));
> +		if (ret) {
> +			ret = -EFAULT;
> +			break;
> +		}
> +		ret = virtio_media_enumstd(file, vfh, &standard);
> +		if (ret)
> +			break;
> +		ret = copy_to_user((void __user *)arg, &standard,
> +				   sizeof(standard));
> +		if (ret)
> +			ret = -EFAULT;
> +		break;
> +	case VIDIOC_QUERYSTD:
> +		ret = virtio_media_querystd(file, vfh, &std_id);
> +		if (ret)
> +			break;
> +		ret = copy_to_user((void __user *)arg, &std_id, sizeof(std_id));
> +		if (ret)
> +			ret = -EFAULT;
> +		break;
> +	default:
> +		ret = video_ioctl2(file, cmd, arg);
> +		break;
> +	}
> +
> +	mutex_unlock(&vv->vlock);
> +
> +	return ret;
> +}

[Severity: High]
Does intercepting VIDIOC_S_STD, VIDIOC_ENUMSTD, and VIDIOC_QUERYSTD before
video_ioctl2() bypass V4L2 registration, priority, and 32-bit compat
handling?

Unlike __video_do_ioctl(), these three branches do not check
video_is_registered(video_dev) after acquiring vv->vlock.  If
virtio_media_device_ioctl() blocks on mutex_lock(&vv->vlock) while
virtio_media_remove() unregisters the device, deletes vv->commandq, and
frees all sessions, these branches proceed to dereference the freed session
and deleted virtqueue:

CPU0                              CPU1
v4l2_ioctl()
  video_is_registered(vdev)
  virtio_media_device_ioctl()
                                  virtio_media_remove()
                                    video_unregister_device(...)
                                    mutex_lock(&vv->vlock)
                                    ...
                                    virtio_dev->config->del_vqs(...)
                                    mutex_unlock(&vv->vlock)
                                    virtio_media_session_free(s)
    mutex_lock(&vv->vlock)
    virtio_media_querystd()
      ...                         <-- use-after-free of s and commandq

In addition, 32-bit compat userspace on x86_64 issues VIDIOC_ENUMSTD32,
which misses the VIDIOC_ENUMSTD case and falls through to video_ioctl2() ->
v4l_enumstd(), failing with -EINVAL because video_dev->tvnorms is 0.
Bypassing video_ioctl2() also skips is_valid_ioctl(), v4l2_prio_check() on
VIDIOC_S_STD, and INFO_FL_CLEAR zeroing of struct v4l2_standard fields
beyond index on VIDIOC_ENUMSTD.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261120215916.3149345-1-briandaniels@google.com?part=2

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

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

Thread overview: 13+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-20 21:59 [PATCH v11 0/6] media: add virtio-media driver Brian Daniels
2026-11-20 21:59 ` [PATCH v11 1/6] media: virtio: Add core driver and session management Brian Daniels
2026-11-20 22:19   ` sashiko-bot
2026-11-20 21:59 ` [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure Brian Daniels
2026-11-20 22:25   ` sashiko-bot
2026-11-20 21:59 ` [PATCH v11 3/6] media: virtio: Add extended controls support Brian Daniels
2026-11-20 22:23   ` sashiko-bot
2026-11-20 21:59 ` [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll Brian Daniels
2026-11-20 22:21   ` sashiko-bot
2026-11-20 21:59 ` [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support Brian Daniels
2026-11-20 22:16   ` sashiko-bot
2026-11-20 21:59 ` [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack Brian Daniels
2026-11-20 22:25   ` sashiko-bot

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