From nobody Tue Nov 24 16:49:38 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.219.70 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795211967; b=CY5Kp2fiXaGlV1GfwdfXzPKJDOobK9BNMwNZft7XvQyIAWtJaPfML05hyBMryH9/jCtq 7p+puCSc6ic+gZfaZScepxGY2Gwndwheg9/UMx+i5HvZVVdADVZxGFBlpo6iWtyQW6yxX 45Y5tXBHxareRwaRr9JpT/jJPXJQqu49EISdM5FdJSWMiOso+HXNdhCdYKtknzGq0UrwV RwcjXxfSj1lc7VT4ZodGVq07IQzR5gLBxHf5iv9ozcIXL3gS5iVihCpiYljxZN01M03MK v7sr1keXQn982BWKDHdezQCcnKuJNe9mxTOMDeyQ4ydqPt+kOuoku+rl4+Zs45DTnSw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795211967; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=4w4Q9ZG7x/vNPSW7+FRl+kNIJqFLWi67ftuc3P54atE=; b=maYgb9qSXLmUnLgUdmVzjgo9tHhS8KPL5JeRV5uMDuwBDL9PBUtyWJRUU85a2h9XJYPm x9WvApb73sDdk1NJoTBL2r6V57smeRNRkt15jADpJ4Lf1f5Z99jIaUPG0ILjEgMZ3TWp4 /UjJIlDgrO8u7KM2jtUj8vcrJm6R4KgU+D4zP4PLG4GZ5pA2iP3bj7L2iqziXL7aHzLXu HM68o/8zn2pd9WWHenauckuPOBXRiObLB7AcsG4g8rq6eFDXXw5zB2dRot4pPYDdoZlrN uNTBKihSAcd5Nea12/0quBmRuTBeQnPF88Db2xotpqixgXGW67Ncpw+4bmDkyhYRvCg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b="L+gl/YGE"; arc=none smtp.remote-ip=209.85.219.70 Received: from mail-qv1-f70.google.com (mail-qv1-f70.google.com [209.85.219.70]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id DC17C606A6A8 for ; Fri, 20 Nov 2026 21:59:25 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org DC17C606A6A8 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=L+gl/YGE Received: by mail-qv1-f70.google.com with SMTP id 6a1803df08f44-91256a7b7b3so21722706d6.2 for ; Fri, 20 Nov 2026 13:59:25 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795211965; x=1795816765; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=4w4Q9ZG7x/vNPSW7+FRl+kNIJqFLWi67ftuc3P54atE=; b=L+gl/YGEOHSx35owhUo1U8pbjird/XNlthZIJBqljTxWiIMfIjpRstqKT7A5DWiOuF 0LIC8YbUv7c+yWYJu3vEehwOOsvN40uTQLw1Xm0Yfqz5cqYTgt7dkZxrNKhCiDOi7aB3 KvaYA5yX3nzJsFZa3uA2mwzs5UvtxlxPZHMrvSpG5dgEKml+rPUX3eLEhulMOHTN+/4f 4unLpWJIsQWPGMP6Ql+V+MFTo0jfVkUUv+u/V2YIR/PIcmIgpjyZOW2GvRmrrRdAA3Iy /Acs6YJz2za4g7L9RjUEsIQaWhTNlKbkOqbQorufZ14vFx0F7eLzMfOcGL8JZvqEyC1i qpXw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795211965; x=1795816765; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=4w4Q9ZG7x/vNPSW7+FRl+kNIJqFLWi67ftuc3P54atE=; b=TEGo7VNqyHG5AU4oa6YYpoqrhGZrQxS2ufxhvkX51oFprba6pQWgQz8GllHveziot/ z8cJy11W8ypSboyW72oa0vtS8gzvtpYtab9nu9TiMSoPDpJ4KnwbWm2wcpw5cttMiLs+ 0OAIAGwZH04yZx5fhoMG0j4NBpUx42+Mhc5BtTidlZAr5pvS2Mr/5W/STuGTQnJsqcos uDnUUfRvV+gtImhmzMLkrFhPS8dPn8hvDvqE0J6VM40Um2WfNTuUE9iCQ8dkgH00u8lh ggKVMbKaKUoms6203XYPRfehEp2C8xp+r+O6ulK1EJnBZCeD0D203eyH5lbF6Aubw/wu xsnQ== X-Forwarded-Encrypted: i=1; AL+hErFgB1+432Q7K6q5Kpv4BjVRiFWfB7SvGnAeAc0Gu9dJutSjHN3oNjvOFdaw72z01Gte2OreqkN0Lx8ZrI8=@vger.kernel.org X-Gm-Message-State: APuU4Z9zphv7ESDIAM/bGEbyoYPIj/Ae8lvqXRdI5hLv4+iUgHe5G5bX 0iw2dvao6l3lXh5/eWls+tlPH8ywEsoG60IBlN/gx/UKd6dsaoJT6MqC3u/02TPZA2CrLsqhnPd OLl94jDnYA3NbI2JUL4gQwjA8ggMO X-Received: from qvho13.prod.google.com ([2002:ad4:5c8d:0:b0:91e:843a:2926]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:ad4:5f8d:0:b0:91c:cff6:533f with SMTP id 6a1803df08f44-92134988a6dmr70259266d6.5.1795211964100; Fri, 20 Nov 2026 13:59:24 -0800 (PST) Date: Fri, 20 Nov 2026 16:59:11 -0500 In-Reply-To: <20261120215916.3149345-1-briandaniels@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261120215916.3149345-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261120215916.3149345-2-briandaniels@google.com> Subject: [PATCH v11 1/6] media: virtio: Add core driver and session management From: Brian Daniels To: Mauro Carvalho Chehab Cc: adelva@google.com, aesteve@redhat.com, changyeon@google.com, daniel.almeida@collabora.com, eperezma@redhat.com, gnurou@gmail.com, gurchetansingh@google.com, hverkuil@xs4all.nl, linux-kernel@vger.kernel.org, linux-media@vger.kernel.org, mst@redhat.com, nicolas.dufresne@collabora.com, virtualization@lists.linux.dev, xuanzhuo@linux.alibaba.com, dbassey@redhat.com, laurent.pinchart@ideasonboard.com, Brian Daniels Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Alexandre Courbot 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=3Dy), add linux/virtio_media.h to the same exception list in usr/include/Makefile. Signed-off-by: Alexandre Courbot Assisted-by: LLM Co-developed-by: Brian Daniels Signed-off-by: Brian Daniels --- 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 =20 +VIRTIO MEDIA DRIVER +M: Brian Daniels +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 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 =20 Say Y when you want to be able to see such devices. =20 +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) +=3D dvb-core/ # There are both core and drivers at RC subtree - merge before drivers obj-y +=3D rc/ =20 +obj-$(CONFIG_MEDIA_VIRTIO) +=3D virtio/ + obj-$(CONFIG_CEC_CORE) +=3D cec/ =20 # 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 :=3D virtio_media_driver.o + +obj-$(CONFIG_MEDIA_VIRTIO) +=3D 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 + +#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 *f= h) +{ + 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 =3D 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/vir= tio_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 +#include + +#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.lis= t. + * @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 a= re + * 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/vir= tio/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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#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 =3D 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 =3D 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 @se= ssion + * 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 =3D &session->cmd.close; + struct scatterlist cmd_sg =3D {}; + struct scatterlist *sgs[1] =3D { &cmd_sg }; + int ret; + + mutex_lock(&vv->vlock); + + cmd_close->hdr.cmd =3D VIRTIO_MEDIA_CMD_CLOSE; + cmd_close->hdr.__reserved =3D 0; + cmd_close->session_id =3D session->id; + cmd_close->__reserved =3D 0; + + sg_set_buf(&cmd_sg, cmd_close, sizeof(*cmd_close)); + sg_mark_end(&cmd_sg); + + ret =3D 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 vir= tio + * 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 comple= te. + */ +static void commandq_callback(struct virtqueue *queue) +{ + unsigned int len; + struct virtio_media_cmd_callback_param *param; + +process_bufs: + while ((param =3D virtqueue_get_buf(queue, &len))) { + param->resp_len =3D len; + param->done =3D true; + wake_up(¶m->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 res= ponse + * 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 =3D { + .vv =3D vv, + .done =3D false, + .resp_len =3D 0, + }; + struct virtio_media_resp_header *resp_header; + int ret =3D 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 =3D 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 =3D 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 res= ponse + * 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 =3D resp_len ? *resp_len : 0; + int ret =3D virtio_media_kick_command(vv, sgs, out_sgs, in_sgs, + &local_resp_len); + if (resp_len) + *resp_len =3D 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 =3D video_devdata(file); + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_cmd_open *cmd_open =3D &vv->cmd.open; + struct virtio_media_resp_open *resp_open =3D &vv->resp.open; + struct scatterlist cmd_sg =3D {}, resp_sg =3D {}; + struct scatterlist *sgs[2] =3D { &cmd_sg, &resp_sg }; + struct virtio_media_session *session; + int ret; + + session =3D 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 =3D VIRTIO_MEDIA_CMD_OPEN; + cmd_open->hdr.__reserved =3D 0; + ret =3D virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_open), + NULL); + session->id =3D 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 =3D &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 =3D video_devdata(file); + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D + fh_to_session(file->private_data); + + int ret =3D 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 =3D { + .owner =3D THIS_MODULE, + .open =3D virtio_media_device_open, + .release =3D virtio_media_device_close, +}; + +static void virtio_media_release(struct v4l2_device *v4l2_dev) +{ + struct virtio_media *vv =3D + 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 =3D &virtio_dev->dev; + struct virtqueue *vqs[1]; + static struct virtqueue_info vq_info[1] =3D { + { + .name =3D "command", + .callback =3D commandq_callback, + }, + }; + struct virtio_media *vv; + struct video_device *vd; + int ret; + + vv =3D 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 =3D virtio_dev; + virtio_dev->priv =3D vv; + + init_waitqueue_head(&vv->wq); + + ret =3D v4l2_device_register(dev, &vv->v4l2_dev); + if (ret) + goto err_free_virtio_media; + + vv->v4l2_dev.release =3D virtio_media_release; + + ret =3D virtio_find_vqs(virtio_dev, 1, vqs, vq_info, NULL); + if (ret) + goto err_v4l2_device_unregister; + + vv->commandq =3D vqs[0]; + + vd =3D &vv->video_dev; + vd->v4l2_dev =3D &vv->v4l2_dev; + vd->fops =3D &virtio_media_fops; + vd->release =3D 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 =3D VFL_DIR_M2M; + else if (vd->device_caps & + (V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OUTPUT_MPLANE)) + vd->vfl_dir =3D VFL_DIR_TX; + else + vd->vfl_dir =3D VFL_DIR_RX; + + __u32 device_type; + + virtio_cread_le(virtio_dev, struct virtio_media_config, device_type, + &device_type); + if (device_type >=3D VFL_TYPE_MAX) { + dev_err(&virtio_dev->dev, "Invalid device_type: %u", + device_type); + ret =3D -EINVAL; + goto err_del_vqs; + } + + virtio_device_ready(virtio_dev); + + ret =3D 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 =3D 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 =3D + 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[] =3D { + { VIRTIO_ID_MEDIA, VIRTIO_DEV_ANY_ID }, + { 0 }, +}; + +static unsigned int features[] =3D {}; + +static struct virtio_driver virtio_media_driver =3D { + .feature_table =3D features, + .feature_table_size =3D ARRAY_SIZE(features), + .driver.name =3D VIRTIO_MEDIA_DEFAULT_DRIVER_NAME, + .driver.owner =3D THIS_MODULE, + .id_table =3D id_table, + .probe =3D virtio_media_probe, + .remove =3D virtio_media_remove, +}; + +module_virtio_driver(virtio_media_driver); + +MODULE_DEVICE_TABLE(virtio, id_table); +MODULE_DESCRIPTION("virtio media driver"); +MODULE_AUTHOR("Alexandre Courbot "); +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-C= lause) */ + +/* + * 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 +#include + +/* + * Virtio protocol definition. + */ + +/** + * struct virtio_media_config - Video device configuration space. + * @device_caps: flags representing the device capabilities as used in &st= ruct + * v4l2_capability. It corresponds with the device_caps fiel= d 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_OP= EN. + * @hdr: header containing the status of the command. + * @session_id: if &struct virtio_media_resp_header.status =3D=3D 0, conta= ins 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 t= he + * 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_CLO= SE. + * @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 +=3D linux/usb/audio.h no-header-test +=3D linux/v4l2-mediabus.h no-header-test +=3D linux/v4l2-subdev.h no-header-test +=3D linux/videodev2.h +no-header-test +=3D linux/virtio_media.h no-header-test +=3D linux/vm_sockets.h no-header-test +=3D sound/asequencer.h no-header-test +=3D sound/asoc.h --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 16:49:38 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.219.70 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795211969; b=ch5xX+eFcJ2A+AA00HPKomv96Yypj6tUV5ZTOTl+R4EKMOSwr2EztaLGKIOeA33vOuny WEUny2gYSqBVggb2BnRst7z6sQHzKhpCMKES3xvXnCEWBVRut0MWfbsZ8ZA2X5GriLOXQ diSFhrZX81PojoG3/EvJkITeVa4X+UparsOW0FbZaT6yefLqidotsH0iAePrAM/v8rebG S7Q1KDi4bIBx7ixINfEti2Qh7na8siY7rgu8BrMH+t9K54jEB+P2b+MyEyR7ncP+5H5eP cgIcM+1D9S1bKl4d88nrmhKLdHUxohg5B+yJcPWeyVw62j5RA0jKhZZ1h9gx66zNjmw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795211969; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=BblxjRz0gm8In323ng1N0PZo6Fj2zpXu4irDO3ggmQ8=; b=0UmnOvPzfC/nL3cK9tqLF2v/Lzxa3kdfUu6ipA4wfoner4W+IjNYpSecR0SaE7Q/oU1l E8VxzeMP1P9ueeP5sSdA227uKguESesEp4+6adBw7ytJRaFMSzx/QKh9rimV9NEtn7Nxp FpPMoY51s2z+X3ox6MLl17KOXwJJazyc8PGITTpwSeJJqZd7oNkkWR8QcoqYJ3E1rUgnP kni/56NPzAr7w1o2VCKznXTH+87j+je+DN1YA2LSh1c+au0vD6EJVktrgGdYcXFfkdT1O CF7ewLc4zGQPKwMRR7lFiuyOjjlVqhNbdKe9TNMe5nCk5Y+g3OQJOvIFVPin0auAmgA== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=ogFL3fGb; arc=none smtp.remote-ip=209.85.219.70 Received: from mail-qv1-f70.google.com (mail-qv1-f70.google.com [209.85.219.70]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AF388606A6B4 for ; Fri, 20 Nov 2026 21:59:27 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org AF388606A6B4 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=ogFL3fGb Received: by mail-qv1-f70.google.com with SMTP id 6a1803df08f44-92126ecb4b8so27578926d6.3 for ; Fri, 20 Nov 2026 13:59:27 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795211966; x=1795816766; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=BblxjRz0gm8In323ng1N0PZo6Fj2zpXu4irDO3ggmQ8=; b=ogFL3fGbC5YxqdIJnfNrXnKUsNJ97rL7z6hXHREGyuATqO+O8RCuuZHkIvC2VYQ/OW CwS7qZUp0CwIBiUyn5AXnvbUA+03Ke+7mPx5WCVJxK4nld9DiqrRl8fMhJ/AQxx1fFR0 Da4h+EkO0c/vSlHhX6d0PiuuvB2HAnb/cFUo7Fdmvd0giGpOGtOanc5oU07bsK63Eypn YK/WMg6+i9C+pQGA/95Rh5xGR/Cg6ZVdIGPA5SDkZ+6GrSIQoqW26jS3XVTsaUcWGuYY 2sWToy9UWen2d/M0i/ChlynZGr6jx7V96Dwd7CNKZspiWUP41J4z8/C74ZWSPSKEflk1 SmVQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795211966; x=1795816766; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=BblxjRz0gm8In323ng1N0PZo6Fj2zpXu4irDO3ggmQ8=; b=1ngs2G5XKSEJPp8TAx+x8cFrxJLhrw6e44Y2O4vKRe1oUJQO2XXrNyDKqhLoU7ELcr hEWEKweW5wiI33sbsoJWKJTN3V2h2n09hHqfyguFtGuaMrEX7R55OENOoLZ4waO8UZAF 6EnX5qecKZCyqSmSRIGqAP9F7OWMJ3ENisiOkfAjkvrN3+0kpUh3dT45mk8YOdc2Rq2A 2m/SJo9ui+7+D5+/sesMnDCkCF6q13YZ2P1x36208nG6veTAbUThjhJcQjk6wjEzse7z 0dGMrEY62ci9po/4F8SMqJkZzCRMKxv8ZSxH+cxbLZwTmqh2eSqw/Ib4Db4ndAbZi0of m5Sw== X-Forwarded-Encrypted: i=1; AL+hErFOdxUZ880cvXAg4UL2dnWqZxOWzUbFj1CIw3nHc05yinqBljVBuOq9ml+Tl1Q4rC/eIVgiqFzR/f7vqUs=@vger.kernel.org X-Gm-Message-State: APuU4Z/OA319oHPF1M9omMTzqDXupTM/9vQ95IYLFOfFqx7nQRDSHPff ooPvUjRQZ0K35gfZrQWutRHwNYZ0Qfd0JXm8ctr5Y2CAcpGsYbfHqax66CYFZTXTQEJZP34U6sK LfTBt3UQVhetmqwM9IGSlp2JjExNb X-Received: from qvbdu15.prod.google.com ([2002:a05:6214:9af:b0:91f:1178:6921]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6214:5c06:b0:921:3f1a:ee86 with SMTP id 6a1803df08f44-9213f1af746mr37612896d6.25.1795211966188; Fri, 20 Nov 2026 13:59:26 -0800 (PST) Date: Fri, 20 Nov 2026 16:59:12 -0500 In-Reply-To: <20261120215916.3149345-1-briandaniels@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261120215916.3149345-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261120215916.3149345-3-briandaniels@google.com> Subject: [PATCH v11 2/6] media: virtio: Add V4L2 ioctl forwarding infrastructure From: Brian Daniels To: Mauro Carvalho Chehab Cc: adelva@google.com, aesteve@redhat.com, changyeon@google.com, daniel.almeida@collabora.com, eperezma@redhat.com, gnurou@gmail.com, gurchetansingh@google.com, hverkuil@xs4all.nl, linux-kernel@vger.kernel.org, linux-media@vger.kernel.org, mst@redhat.com, nicolas.dufresne@collabora.com, virtualization@lists.linux.dev, xuanzhuo@linux.alibaba.com, dbassey@redhat.com, laurent.pinchart@ideasonboard.com, Brian Daniels Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Alexandre Courbot 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 Assisted-by: LLM Co-developed-by: Brian Daniels Signed-off-by: Brian Daniels --- 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. =20 -virtio-media-objs :=3D virtio_media_driver.o +virtio-media-objs :=3D scatterlist_builder.o virtio_media_ioctls.o virtio_= media_driver.o =20 obj-$(CONFIG_MEDIA_VIRTIO) +=3D virtio-media.o diff --git a/drivers/media/virtio/scatterlist_builder.c b/drivers/media/vir= tio/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 +#include +#include +#include + +#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_N= RMASK) + +/** + * 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 >=3D builder->num_sgs) + return -ENOSPC; + builder->sgs[builder->cur_sg++] =3D &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 buf= fer + * to be referenced from there. + */ +int scatterlist_builder_add_data(struct scatterlist_builder *builder, + void *data, size_t len) +{ + const size_t cur_desc =3D builder->cur_desc; + + if (len =3D=3D 0) + return 0; + + if (builder->cur_desc >=3D 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 =3D virt_to_page(data); + size_t offset =3D (((size_t)data) & ~PAGE_MASK); + struct scatterlist *next_desc =3D + &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 =3D false; + unsigned long prev_pfn =3D 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 =3D vmalloc_to_page(data); + unsigned long cur_pfn =3D page_to_pfn(page); + /* All pages but the first will start at offset 0. */ + unsigned long offset =3D + (((unsigned long)data) & ~PAGE_MASK); + size_t len_in_page =3D min(PAGE_SIZE - offset, len); + struct scatterlist *next_desc =3D + &builder->descs[builder->cur_desc]; + + if (builder->cur_desc >=3D builder->num_descs) + return -ENOSPC; + + /* Optimize contiguous pages */ + if (prev_pfn_valid && (cur_pfn =3D=3D prev_pfn + 1)) { + (next_desc - 1)->length +=3D 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 +=3D len_in_page; + len -=3D len_in_page; + prev_pfn =3D cur_pfn; + prev_pfn_valid =3D 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 =3D + builder->shadow_buffer + builder->shadow_buffer_pos; + struct page *page =3D virt_to_page(shadow_buffer); + unsigned long offset =3D + (((unsigned long)shadow_buffer) & ~PAGE_MASK); + struct scatterlist *next_desc =3D + &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 +=3D 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 direc= tly. + * + * @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 =3D builder->shadow_buffer; + struct scatterlist *sg; + void *kaddr; + + /* We can only retrieve from the range of sgs currently set. */ + if (sg_index >=3D builder->cur_sg) + return -ERANGE; + + sg =3D builder->sgs[sg_index]; + kaddr =3D pfn_to_kaddr(page_to_pfn(sg_page(sg))) + sg->offset; + + if (kaddr >=3D 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 descr= iptor + * 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 =3D &session->cmd.ioctl; + + cmd_ioctl->hdr.cmd =3D VIRTIO_MEDIA_CMD_IOCTL; + cmd_ioctl->hdr.__reserved =3D 0; + cmd_ioctl->session_id =3D session->id; + cmd_ioctl->code =3D 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 =3D &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/vir= tio/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 + +#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 t= his. + * + * virtio-media descriptor chains are typically made of the following part= s: + * + * 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 memb= er in + * an optimal way, by building a scatterlist adapted to the originating me= mory + * 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 =20 +#include #include =20 #include "uapi/linux/virtio_media.h" =20 +/* + * 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 handl= ed 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 cha= in 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(); =20 + void *shadow_buf; + + struct sg_table command_sgs; + struct list_head list; }; =20 diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/vir= tio_media.h index 68299377a..a120c1014 100644 --- a/drivers/media/virtio/virtio_media.h +++ b/drivers/media/virtio/virtio_media.h @@ -14,6 +14,8 @@ =20 #include "uapi/linux/virtio_media.h" =20 +#define DESC_CHAIN_MAX_LEN SG_MAX_SINGLE_ALLOC + #define VIRTIO_MEDIA_DEFAULT_DRIVER_NAME "virtio-media" =20 /** @@ -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 =20 diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/vir= tio/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; =20 session =3D kzalloc_obj(*session, GFP_KERNEL); if (!session) - return ERR_PTR(-ENOMEM); + goto err_session; + + session->shadow_buf =3D kzalloc(VIRTIO_SHADOW_BUF_SIZE, GFP_KERNEL); + if (!session->shadow_buf) + goto err_shadow_buf; + + ret =3D sg_alloc_table(&session->command_sgs, DESC_CHAIN_MAX_LEN, + GFP_KERNEL); + if (ret) + goto err_payload_sgs; =20 // The caller is expected to set the ID once the host assigns a value. session->id =3D 0; @@ -50,6 +60,13 @@ virtio_media_session_alloc(struct virtio_media *vv, stru= ct file *file) virtio_media_session_fh_add(session, file); =20 return session; + +err_payload_sgs: + kfree(session->shadow_buf); +err_shadow_buf: + kfree(session); +err_session: + return ERR_PTR(-ENOMEM); } =20 /** @@ -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); =20 + sg_free_table(&session->command_sgs); + + kfree(session->shadow_buf); kfree(session); } =20 @@ -342,6 +362,7 @@ static const struct v4l2_file_operations virtio_media_f= ops =3D { .owner =3D THIS_MODULE, .open =3D virtio_media_device_open, .release =3D virtio_media_device_close, + .unlocked_ioctl =3D virtio_media_device_ioctl, }; =20 static void virtio_media_release(struct v4l2_device *v4l2_dev) @@ -394,6 +415,7 @@ static int virtio_media_probe(struct virtio_device *vir= tio_dev) =20 vd =3D &vv->video_dev; vd->v4l2_dev =3D &vv->v4l2_dev; + vd->ioctl_ops =3D &virtio_media_ioctl_ops; vd->fops =3D &virtio_media_fops; vd->release =3D 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/vir= tio/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 +#include +#include +#include + +#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 t= he + * 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 =3D fh->vdev; + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D fh_to_session(fh); + struct scatterlist *sgs[3]; + struct scatterlist_builder builder =3D { + .descs =3D session->command_sgs.sgl, + .num_descs =3D DESC_CHAIN_MAX_LEN, + .cur_desc =3D 0, + .shadow_buffer =3D session->shadow_buf, + .shadow_buffer_size =3D VIRTIO_SHADOW_BUF_SIZE, + .shadow_buffer_pos =3D 0, + .sgs =3D sgs, + .num_sgs =3D ARRAY_SIZE(sgs), + .cur_sg =3D 0, + }; + + /* Command descriptor */ + int ret =3D scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl); + + if (ret) + return ret; + + /* Response descriptor */ + ret =3D scatterlist_builder_add_ioctl_resp(&builder, session); + if (ret) + return ret; + + /* Response payload */ + ret =3D 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 =3D virtio_media_send_command(vv, sgs, 1, 2, + sizeof(struct virtio_media_resp_ioctl) + + ioctl_data_len, NULL); + if (ret < 0) + return ret; + + ret =3D 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 =3D fh->vdev; + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D fh_to_session(fh); + struct scatterlist *sgs[3]; + struct scatterlist_builder builder =3D { + .descs =3D session->command_sgs.sgl, + .num_descs =3D DESC_CHAIN_MAX_LEN, + .cur_desc =3D 0, + .shadow_buffer =3D session->shadow_buf, + .shadow_buffer_size =3D VIRTIO_SHADOW_BUF_SIZE, + .shadow_buffer_pos =3D 0, + .sgs =3D sgs, + .num_sgs =3D ARRAY_SIZE(sgs), + .cur_sg =3D 0, + }; + + /* Command descriptor */ + int ret =3D scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl); + + if (ret) + return ret; + + /* Command payload */ + ret =3D 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 =3D scatterlist_builder_add_ioctl_resp(&builder, session); + if (ret) + return ret; + + ret =3D 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 payloa= d. + * + * 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 =3D fh->vdev; + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D fh_to_session(fh); + struct scatterlist *sgs[4]; + struct scatterlist_builder builder =3D { + .descs =3D session->command_sgs.sgl, + .num_descs =3D DESC_CHAIN_MAX_LEN, + .cur_desc =3D 0, + .shadow_buffer =3D session->shadow_buf, + .shadow_buffer_size =3D VIRTIO_SHADOW_BUF_SIZE, + .shadow_buffer_pos =3D 0, + .sgs =3D sgs, + .num_sgs =3D ARRAY_SIZE(sgs), + .cur_sg =3D 0, + }; + + /* Command descriptor */ + int ret =3D scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl); + + if (ret) + return ret; + + /* Command payload */ + ret =3D 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 =3D scatterlist_builder_add_ioctl_resp(&builder, session); + if (ret) + return ret; + + /* Response payload, same as command */ + ret =3D scatterlist_builder_add_descriptor(&builder, 1); + if (ret) + return ret; + + ret =3D virtio_media_send_command(vv, sgs, 2, 2, + sizeof(struct virtio_media_resp_ioctl) + + minimum_resp_payload, + NULL); + if (ret < 0) + return ret; + + ret =3D 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 =3D 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 =3D 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 =3D 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 w= e 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_modulato= r) +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_frequenc= y) +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 =3D video_devdata(file); + struct virtio_media *vv =3D 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 =3D video_dev->device_caps | V4L2_CAP_DEVICE_CAPS; + cap->device_caps =3D 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 =3D virtio_media_send_r_ioctl(file_to_v4l2_fh(file), + VIDIOC_G_INPUT, &input, + sizeof(input)); + if (ret) + return ret; + + *i =3D input; + + return 0; +} + +static int virtio_media_s_input(struct file *file, void *fh, unsigned int = i) +{ + u32 input =3D 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 =3D virtio_media_send_r_ioctl(file_to_v4l2_fh(file), + VIDIOC_G_OUTPUT, &output, + sizeof(output)); + if (ret) + return ret; + + *o =3D output; + + return 0; +} + +static int virtio_media_s_output(struct file *file, void *fh, unsigned int= o) +{ + u32 output =3D 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 =3D 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 =3D { + /* VIDIOC_QUERYCAP handler */ + .vidioc_querycap =3D virtio_media_querycap, + + /* VIDIOC_ENUM_FMT handlers */ + .vidioc_enum_fmt_vid_cap =3D virtio_media_enum_fmt, + .vidioc_enum_fmt_vid_overlay =3D virtio_media_enum_fmt, + .vidioc_enum_fmt_vid_out =3D virtio_media_enum_fmt, + .vidioc_enum_fmt_sdr_cap =3D virtio_media_enum_fmt, + .vidioc_enum_fmt_sdr_out =3D virtio_media_enum_fmt, + .vidioc_enum_fmt_meta_cap =3D virtio_media_enum_fmt, + .vidioc_enum_fmt_meta_out =3D virtio_media_enum_fmt, + + /* VIDIOC_G_FMT handlers */ + .vidioc_g_fmt_vid_cap =3D virtio_media_g_fmt, + .vidioc_g_fmt_vid_overlay =3D virtio_media_g_fmt, + .vidioc_g_fmt_vid_out =3D virtio_media_g_fmt, + .vidioc_g_fmt_vid_out_overlay =3D virtio_media_g_fmt, + .vidioc_g_fmt_vbi_cap =3D virtio_media_g_fmt, + .vidioc_g_fmt_vbi_out =3D virtio_media_g_fmt, + .vidioc_g_fmt_sliced_vbi_cap =3D virtio_media_g_fmt, + .vidioc_g_fmt_sliced_vbi_out =3D virtio_media_g_fmt, + .vidioc_g_fmt_vid_cap_mplane =3D virtio_media_g_fmt, + .vidioc_g_fmt_vid_out_mplane =3D virtio_media_g_fmt, + .vidioc_g_fmt_sdr_cap =3D virtio_media_g_fmt, + .vidioc_g_fmt_sdr_out =3D virtio_media_g_fmt, + .vidioc_g_fmt_meta_cap =3D virtio_media_g_fmt, + .vidioc_g_fmt_meta_out =3D virtio_media_g_fmt, + + /* VIDIOC_S_FMT handlers */ + .vidioc_s_fmt_vid_cap =3D virtio_media_s_fmt, + .vidioc_s_fmt_vid_overlay =3D virtio_media_s_fmt, + .vidioc_s_fmt_vid_out =3D virtio_media_s_fmt, + .vidioc_s_fmt_vid_out_overlay =3D virtio_media_s_fmt, + .vidioc_s_fmt_vbi_cap =3D virtio_media_s_fmt, + .vidioc_s_fmt_vbi_out =3D virtio_media_s_fmt, + .vidioc_s_fmt_sliced_vbi_cap =3D virtio_media_s_fmt, + .vidioc_s_fmt_sliced_vbi_out =3D virtio_media_s_fmt, + .vidioc_s_fmt_vid_cap_mplane =3D virtio_media_s_fmt, + .vidioc_s_fmt_vid_out_mplane =3D virtio_media_s_fmt, + .vidioc_s_fmt_sdr_cap =3D virtio_media_s_fmt, + .vidioc_s_fmt_sdr_out =3D virtio_media_s_fmt, + .vidioc_s_fmt_meta_cap =3D virtio_media_s_fmt, + .vidioc_s_fmt_meta_out =3D virtio_media_s_fmt, + + /* VIDIOC_TRY_FMT handlers */ + .vidioc_try_fmt_vid_cap =3D virtio_media_try_fmt, + .vidioc_try_fmt_vid_overlay =3D virtio_media_try_fmt, + .vidioc_try_fmt_vid_out =3D virtio_media_try_fmt, + .vidioc_try_fmt_vid_out_overlay =3D virtio_media_try_fmt, + .vidioc_try_fmt_vbi_cap =3D virtio_media_try_fmt, + .vidioc_try_fmt_vbi_out =3D virtio_media_try_fmt, + .vidioc_try_fmt_sliced_vbi_cap =3D virtio_media_try_fmt, + .vidioc_try_fmt_sliced_vbi_out =3D virtio_media_try_fmt, + .vidioc_try_fmt_vid_cap_mplane =3D virtio_media_try_fmt, + .vidioc_try_fmt_vid_out_mplane =3D virtio_media_try_fmt, + .vidioc_try_fmt_sdr_cap =3D virtio_media_try_fmt, + .vidioc_try_fmt_sdr_out =3D virtio_media_try_fmt, + .vidioc_try_fmt_meta_cap =3D virtio_media_try_fmt, + .vidioc_try_fmt_meta_out =3D virtio_media_try_fmt, + + /* Standard handling */ + .vidioc_g_std =3D virtio_media_g_std, + .vidioc_s_std =3D virtio_media_s_std, + .vidioc_querystd =3D virtio_media_querystd, + + /* Input handling */ + .vidioc_enum_input =3D virtio_media_enuminput, + .vidioc_g_input =3D virtio_media_g_input, + .vidioc_s_input =3D virtio_media_s_input, + + /* Output handling */ + .vidioc_enum_output =3D virtio_media_enumoutput, + .vidioc_g_output =3D virtio_media_g_output, + .vidioc_s_output =3D virtio_media_s_output, + + /* Control handling */ + .vidioc_query_ext_ctrl =3D virtio_media_query_ext_ctrl, + .vidioc_querymenu =3D virtio_media_querymenu, + + /* Audio ioctls */ + .vidioc_enumaudio =3D virtio_media_enumaudio, + .vidioc_g_audio =3D virtio_media_g_audio, + .vidioc_s_audio =3D virtio_media_s_audio, + + /* Audio out ioctls */ + .vidioc_enumaudout =3D virtio_media_enumaudout, + .vidioc_g_audout =3D virtio_media_g_audout, + .vidioc_s_audout =3D virtio_media_s_audout, + .vidioc_g_modulator =3D virtio_media_g_modulator, + .vidioc_s_modulator =3D virtio_media_s_modulator, + + /* Crop ioctls */ + /* + * Not directly an ioctl (part of VIDIOC_CROPCAP), so no need to + * implement. + */ + .vidioc_g_pixelaspect =3D NULL, + .vidioc_g_selection =3D virtio_media_g_selection, + .vidioc_s_selection =3D virtio_media_s_selection, + + /* Compression ioctls */ + /* Deprecated in V4L2. */ + .vidioc_g_jpegcomp =3D NULL, + /* Deprecated in V4L2. */ + .vidioc_s_jpegcomp =3D NULL, + .vidioc_g_enc_index =3D virtio_media_g_enc_index, + .vidioc_encoder_cmd =3D virtio_media_encoder_cmd, + .vidioc_try_encoder_cmd =3D virtio_media_try_encoder_cmd, + .vidioc_try_decoder_cmd =3D virtio_media_try_decoder_cmd, + + /* Stream type-dependent parameter ioctls */ + .vidioc_g_parm =3D virtio_media_g_parm, + .vidioc_s_parm =3D virtio_media_s_parm, + + /* Tuner ioctls */ + .vidioc_g_tuner =3D virtio_media_g_tuner, + .vidioc_s_tuner =3D virtio_media_s_tuner, + .vidioc_g_frequency =3D virtio_media_g_frequency, + .vidioc_s_frequency =3D virtio_media_s_frequency, + .vidioc_enum_freq_bands =3D virtio_media_enum_freq_bands, + + /* Sliced VBI cap */ + .vidioc_g_sliced_vbi_cap =3D virtio_media_g_sliced_vbi_cap, + + /* Log status ioctl */ + /* Guest-only operation */ + .vidioc_log_status =3D NULL, + + .vidioc_s_hw_freq_seek =3D virtio_media_s_hw_freq_seek, + + .vidioc_enum_framesizes =3D virtio_media_enum_framesizes, + .vidioc_enum_frameintervals =3D virtio_media_enum_frameintervals, + + /* DV Timings IOCTLs */ + .vidioc_s_dv_timings =3D virtio_media_s_dv_timings, + .vidioc_g_dv_timings =3D virtio_media_g_dv_timings, + .vidioc_query_dv_timings =3D virtio_media_query_dv_timings, + .vidioc_enum_dv_timings =3D virtio_media_enum_dv_timings, + .vidioc_dv_timings_cap =3D virtio_media_dv_timings_cap, + .vidioc_g_edid =3D NULL, + .vidioc_s_edid =3D NULL, + + /* For other private ioctls */ + .vidioc_default =3D NULL, +}; + +long virtio_media_device_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + struct video_device *video_dev =3D video_devdata(file); + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct v4l2_fh *vfh =3D NULL; + struct v4l2_standard standard; + v4l2_std_id std_id =3D 0; + int ret; + + if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags)) + vfh =3D 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 =3D copy_from_user(&std_id, (void __user *)arg, + sizeof(std_id)); + if (ret) { + ret =3D -EFAULT; + break; + } + ret =3D virtio_media_s_std(file, vfh, std_id); + break; + case VIDIOC_ENUMSTD: + ret =3D copy_from_user(&standard, (void __user *)arg, + sizeof(standard)); + if (ret) { + ret =3D -EFAULT; + break; + } + ret =3D virtio_media_enumstd(file, vfh, &standard); + if (ret) + break; + ret =3D copy_to_user((void __user *)arg, &standard, + sizeof(standard)); + if (ret) + ret =3D -EFAULT; + break; + case VIDIOC_QUERYSTD: + ret =3D virtio_media_querystd(file, vfh, &std_id); + if (ret) + break; + ret =3D copy_to_user((void __user *)arg, &std_id, sizeof(std_id)); + if (ret) + ret =3D -EFAULT; + break; + default: + ret =3D 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; }; =20 +/** + * VIRTIO_MEDIA_CMD_IOCTL - Driver command for executing an ioctl. + * + * This command asks the device to run one of the ``VIDIOC_*`` ioctls on t= he + * 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*`` ma= cro. + * + * 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 w= ill + * write into. + * + */ +#define VIRTIO_MEDIA_CMD_IOCTL 3 + +/** + * struct virtio_media_cmd_ioctl - Driver command for VIRTIO_MEDIA_CMD_IOC= TL. + * @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_I= OCTL. + * @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 --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 16:49:38 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.160.200 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795211971; b=0WY2y2Sl9Z/jPlGoiL6QxzHW4kNNo60VVyYHdmP39M7mNkka9Igq0Gh82zry6b2VbLfD oOntQJrfE85IVx7/hBiXYy4CfXCGdNasgSbix0qjILRWc/kPa2dv6KkPg6Dsb5VhFZ+MQ ozGhA/zfQ25HBruJVLlnn2OmIRjgqyWTYdUny3qpbZ5oMzXu8DIuRID5QmDRVGNrZWQZB evqGlu+p+1vyVHgwwVM9fMyHceL8A573wUm1OXLKnnfm1UX7QlkcVuQwM2GfzOMx1U1tm Acg0ekOVmVy0zujcryDx0pdmN9bwW1LorEsLwl7Dwa4JnWby2SEx/WcNmzXQ+VFxDkQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795211971; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=EIk/aq/W9rVwRyOwrz6inYicDcFOQZ4YndxTsNgbVuk=; b=Dujas39R8NptJUkHBx9PcWAMaAIcin2OCxXY3hLVI5YuyyL29u+Df+2bMNvG/+TvQ1dq NfDG4c4Rhj40ZOYpHFx52m9ICxLNat9q359hca0OBnK5C0zAwhV2cUI1HD3c6qp9FYDhS X2SWzN0wYnRKjUlVq065NOb+fDzmeLeAyWkWPNdTFQbU2jSL7cn9p0HoUKWYJB8Mh9O3t 4N7f1/Sgx6CmOPKL/cvjsk2aBccNGQXceZA0JoklDXeTKG3yzp4J6KNPigDhHPL5D+xAG 5dlffcHrodtUqhCI1O3l8KQnA5eqAyRlWZHTJXc4aJBXGWZnrraLsfvqQ9SVaZ2yKiQ== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=nJiVUAFe; arc=none smtp.remote-ip=209.85.160.200 Received: from mail-qt1-f200.google.com (mail-qt1-f200.google.com [209.85.160.200]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id D25B260A260D for ; Fri, 20 Nov 2026 21:59:29 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org D25B260A260D Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=nJiVUAFe Received: by mail-qt1-f200.google.com with SMTP id d75a77b69052e-55d2bde4c78so22782201cf.1 for ; Fri, 20 Nov 2026 13:59:29 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795211969; x=1795816769; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=EIk/aq/W9rVwRyOwrz6inYicDcFOQZ4YndxTsNgbVuk=; b=nJiVUAFeaSBsDFRa28axiEsbaj6Ja1hTHP3gVA/yCnoaInb9snr6RrhukS3A7AiGzt xVwtTpwzzhkFa9AIqwOyEwjL5+OCcjifH6rVZLLgiS+QpJmZeQuf6KcwMM54Y4uW0gn5 ISQWojPz3/GIkmkYCyX8uKcbyrbWb6dJWufsUZkAmK0Lee+PrXlSHjEdmQEDn2NGZ4EY N8CpkVi5XSIQ6x2btEWED1EkDFWokNGfNDGK441aPNYmseutFZe/M1ysg0jLH8ybkjWe zQZNe43pxICLO6dVaYBijQlkyV5JzVcXETzXir5bT02/rHVvP6ugTfRvVmFT35bQ7fJg KOBw== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795211969; x=1795816769; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=EIk/aq/W9rVwRyOwrz6inYicDcFOQZ4YndxTsNgbVuk=; b=QGgVtjJZAas4klME1mjhfg/UtRFTPzRvEFx24AMBz+X8gcdcuZPUQP5SvSkPYWfeEI PMjN3Ajc50R2BrQO7LRssYzxj2rJnajqgg9Zl9smuig0h9m7c9k2RLQBCiZ4HbKa4ERM anYzJ8phOVRRV9rcfdHDLRHwn7Y5jJa5bNWdWUWkX5LCC/P9tw4SsavSOORo1V43/kW6 VXQkq+3yCFVwWc73SLFqUQN3ilPl5PUkOkfWjPyk6a1E6aBm0ZAwYSE6PevUl/Z7yaqs t5KRNcnrMInH9zPEn0HVdIkBnBLS3DqJkRg4r+owkGHr5l9QuRjPy+LkRkpRFKpwLAKE 3whw== X-Forwarded-Encrypted: i=1; AL+hErFVMh4s1mUh5BTicuLTJQx4mhXT+dh1giTgq8gb1XP1SldhdXheQjT1YtAd2zsY1b7+JYZtorwcEfTaW5w=@vger.kernel.org X-Gm-Message-State: APuU4Z9D9uuTyWE+geMwvTrFcYSzdAQQPUrtk3/IgimpWxA7/aazntea C4EH64AMVSrF2tY1jcAFHDrfhctQv9nNlgSYuhUcNxI75QGnhLH2Rd2YPKMingWXJ3366rlJE9r Ppe/JL9RAiFYzi6/UtT1eIVQFvGP3 X-Received: from qvbq39.prod.google.com ([2002:a05:6214:8627:b0:91f:a3f:7b3b]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:622a:5a15:b0:55c:234b:54a2 with SMTP id d75a77b69052e-55d76a75e7amr84488521cf.62.1795211968400; Fri, 20 Nov 2026 13:59:28 -0800 (PST) Date: Fri, 20 Nov 2026 16:59:13 -0500 In-Reply-To: <20261120215916.3149345-1-briandaniels@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261120215916.3149345-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261120215916.3149345-4-briandaniels@google.com> Subject: [PATCH v11 3/6] media: virtio: Add extended controls support From: Brian Daniels To: Mauro Carvalho Chehab Cc: adelva@google.com, aesteve@redhat.com, changyeon@google.com, daniel.almeida@collabora.com, eperezma@redhat.com, gnurou@gmail.com, gurchetansingh@google.com, hverkuil@xs4all.nl, linux-kernel@vger.kernel.org, linux-media@vger.kernel.org, mst@redhat.com, nicolas.dufresne@collabora.com, virtualization@lists.linux.dev, xuanzhuo@linux.alibaba.com, dbassey@redhat.com, laurent.pinchart@ideasonboard.com, Brian Daniels Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Alexandre Courbot 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 Assisted-by: LLM Co-developed-by: Brian Daniels Signed-off-by: Brian Daniels --- 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/vir= tio/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 scatter= list_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 sha= dow + * 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. F= or + * 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 ca= se 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 =3D {}; + struct frame_vector *framevec; + struct scatterlist *sg_iter; + struct page **pages; + const unsigned int offset =3D userptr & ~PAGE_MASK; + unsigned int pages_count; + size_t entries_size; + size_t initial_cur_framevec =3D builder->cur_framevec; + int i; + int ret; + + if (builder->cur_framevec >=3D builder->num_framevecs) { + pr_err("Ran out of framevecs (%zu/%zu)", builder->cur_framevec, + builder->num_framevecs); + ret =3D -ENOMEM; + } + + framevec =3D vb2_create_framevec(userptr, length, true); + if (IS_ERR(framevec)) { + if (PTR_ERR(framevec) !=3D -EFAULT) { + pr_warn("error %ld creating frame vector for userptr 0x%lx, length 0x%l= x\n", + PTR_ERR(framevec), userptr, length); + } else { + /* -EINVAL is expected in case of invalid userptr. */ + framevec =3D ERR_PTR(-EINVAL); + } + return PTR_ERR(framevec); + } + + pages =3D frame_vector_pages(framevec); + if (IS_ERR(pages)) { + pr_warn("error getting vector pages\n"); + ret =3D PTR_ERR(pages); + goto free_framevec; + } + pages_count =3D frame_vector_count(framevec); + ret =3D 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 =3D sg_nents(sg_table.sgl); + entries_size =3D sizeof(**sg_list) * *nents; + if (builder->shadow_buffer_pos + entries_size > + builder->shadow_buffer_size) { + ret =3D -ENOMEM; + goto free_sg; + } + + *sg_list =3D builder->shadow_buffer + builder->shadow_buffer_pos; + builder->shadow_buffer_pos +=3D entries_size; + + for_each_sgtable_sg(&sg_table, sg_iter, i) { + struct virtio_media_sg_entry *sg_entry =3D &(*sg_list)[i]; + + sg_entry->start =3D sg_phys(sg_iter); + sg_entry->len =3D sg_iter->length; + sg_entry->__reserved =3D 0; + } + + builder->framevecs[builder->cur_framevec++] =3D framevec; + +free_sg: + sg_free_table(&sg_table); +free_framevec: + // Only destroy the framevec if we didn't save it + if (builder->cur_framevec =3D=3D initial_cur_framevec && framevec) + vb2_destroy_framevec(framevec); + return ret; +} + +/** + * scatterlist_builder_add_userptr() - Add a user-memory buffer using an a= rray + * 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 *bui= lder, + unsigned long userptr, + unsigned long length) +{ + int ret; + int nents; + struct virtio_media_sg_entry *sg_list; + + ret =3D __scatterlist_builder_add_userptr(builder, userptr, length, + &sg_list, &nents); + if (ret) + return ret; + + ret =3D 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 a= nd 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 =3D scatterlist_builder_add_data(builder, ctrls, sizeof(*ctrls)); + if (ret) + return ret; + + if (ctrls->count > 0) { + /* array of v4l2_controls */ + ret =3D 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 sto= re + * framevecs during a request. + * @builder: builder to use. + * @ctrls: &struct v4l2_ext_controls from which we determine how many fram= evecs + * are needed + * + * The framevecs are used to pin the user pages during the request. Once t= he + * request is completed, the allocated framevecs and pointers should be fr= eed + * with scatterlist_builder_free_framevecs(). + */ +int +scatterlist_builder_allocate_framevecs(struct scatterlist_builder *builder, + struct v4l2_ext_controls *ctrls) +{ + int i; + + builder->cur_framevec =3D 0; + + /* Count the pointers to user memory in individual controls */ + for (i =3D 0; i < ctrls->count; i++) { + struct v4l2_ext_control *ctrl =3D &ctrls->controls[i]; + + if (ctrl->size > 0) + builder->num_framevecs +=3D 1; + } + + if (builder->num_framevecs > 0) { + builder->framevecs =3D kzalloc_objs(struct frame_vector*, + builder->num_framevecs); + if (!builder->framevecs) { + builder->num_framevecs =3D 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 =3D builder->framevecs[builder->cur_framevec]; + vb2_destroy_framevec(vec); + } + + kfree(builder->framevecs); + } + + builder->framevecs =3D NULL; + builder->num_framevecs =3D 0; + builder->cur_framevec =3D 0; +} + +/** + * scatterlist_builder_add_ext_ctrls_userptrs() - Add the userspace payloa= ds of + * a &struct v4l2_ext_contr= ols + * 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 s= plit + * 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 *bui= lder, + struct v4l2_ext_controls *ctrls) +{ + int i; + int ret; + + for (i =3D 0; i < ctrls->count; i++) { + struct v4l2_ext_control *ctrl =3D &ctrls->controls[i]; + + if (ctrl->size > 0) { + unsigned long uptr =3D (unsigned long)ctrl->ptr; + + ret =3D 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 *bui= lder, + size_t sg_index, + struct v4l2_ext_controls *ctrls) +{ + struct v4l2_ext_control *controls_backup =3D ctrls->controls; + int ret; + + ret =3D scatterlist_builder_retrieve_data(builder, sg_index++, ctrls); + + if (ret) + return ret; + + ctrls->controls =3D controls_backup; + + if (ctrls->count > 0 && ctrls->controls) { + ret =3D 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/vir= tio/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 allo= cated + * 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; }; =20 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); =20 +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 *bui= lder, + struct v4l2_ext_controls *ctrls); + +int scatterlist_builder_retrieve_ext_ctrls(struct scatterlist_builder *bui= lder, + 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/vir= tio/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 =3D sgs, .num_sgs =3D ARRAY_SIZE(sgs), .cur_sg =3D 0, + .framevecs =3D NULL, + .cur_framevec =3D 0, }; =20 /* Command descriptor */ @@ -107,6 +109,8 @@ static int virtio_media_send_w_ioctl(struct v4l2_fh *fh= , u32 ioctl, .sgs =3D sgs, .num_sgs =3D ARRAY_SIZE(sgs), .cur_sg =3D 0, + .framevecs =3D NULL, + .cur_framevec =3D 0, }; =20 /* Command descriptor */ @@ -171,6 +175,8 @@ static int virtio_media_send_wr_ioctl(struct v4l2_fh *f= h, u32 ioctl, .sgs =3D sgs, .num_sgs =3D ARRAY_SIZE(sgs), .cur_sg =3D 0, + .framevecs =3D NULL, + .cur_framevec =3D 0, }; =20 /* Command descriptor */ @@ -215,6 +221,130 @@ static int virtio_media_send_wr_ioctl(struct v4l2_fh = *fh, u32 ioctl, return 0; } =20 +/** + * 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 m= emory + * that we need to map properly, hence the dedicated function. + */ +static int virtio_media_send_ext_controls_ioctl(struct v4l2_fh *fh, u32 io= ctl, + struct v4l2_ext_controls *ctrls) +{ + struct video_device *video_dev =3D fh->vdev; + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D fh_to_session(fh); + size_t num_cmd_sgs; + size_t end_ctrls_sg; + struct v4l2_ext_control *controls_backup =3D ctrls->controls; + const u32 num_ctrls =3D ctrls->count; + struct scatterlist *sgs[64]; + struct scatterlist_builder builder =3D { + .descs =3D session->command_sgs.sgl, + .num_descs =3D DESC_CHAIN_MAX_LEN, + .cur_desc =3D 0, + .shadow_buffer =3D session->shadow_buf, + .shadow_buffer_size =3D VIRTIO_SHADOW_BUF_SIZE, + .shadow_buffer_pos =3D 0, + .sgs =3D sgs, + .num_sgs =3D ARRAY_SIZE(sgs), + .cur_sg =3D 0, + .framevecs =3D NULL, + .cur_framevec =3D 0, + }; + size_t resp_len =3D 0; + int i; + + int ret =3D scatterlist_builder_allocate_framevecs(&builder, ctrls); + + if (ret) + return ret; + + /* Command descriptor */ + ret =3D scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl); + + if (ret) + goto free_framevecs; + + /* v4l2_controls */ + ret =3D scatterlist_builder_add_ext_ctrls(&builder, ctrls); + if (ret) + goto free_framevecs; + + end_ctrls_sg =3D builder.cur_sg; + + ret =3D scatterlist_builder_add_ext_ctrls_userptrs(&builder, ctrls); + if (ret) + goto free_framevecs; + + num_cmd_sgs =3D builder.cur_sg; + + /* Response descriptor */ + ret =3D scatterlist_builder_add_ioctl_resp(&builder, session); + if (ret) + goto free_framevecs; + + /* Response payload (same as input but without userptrs) */ + for (i =3D 1; i < end_ctrls_sg; i++) { + ret =3D scatterlist_builder_add_descriptor(&builder, i); + if (ret < 0) + goto free_framevecs; + } + + ret =3D 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 =3D controls_backup; + if (ctrls->count !=3D 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 >=3D 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 -=3D 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 =3D 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, vo= id *fh, return 0; } =20 +/* + * 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 =3D 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 =3D 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 =3D 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 =3D { =20 /* Control handling */ .vidioc_query_ext_ctrl =3D virtio_media_query_ext_ctrl, + .vidioc_g_ext_ctrls =3D virtio_media_g_ext_ctrls, + .vidioc_s_ext_ctrls =3D virtio_media_s_ext_ctrls, + .vidioc_try_ext_ctrls =3D virtio_media_try_ext_ctrls, .vidioc_querymenu =3D virtio_media_querymenu, =20 /* 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; }; =20 +/** + * 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 --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 16:49:38 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.222.197 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795211974; b=12iQfR7GbpGWBIIeOy9Fmcscami9oMM7Hltq+86lYdpG+hN4XDoaniO8iEthsRNf5XMW mghRD9RL+W3cKe9RBAYbBPtiP2qCY7KOuZ2SczbaZr8D98ZGjaVWXQRqwKbzGaW0Jg8Rk 7D9kL0qHrwj/e6Bt8wl85YKBfWuIpeLpdvwShOLAjqtEiro8aMHRkVFxNbk/ez68kOeMX 8+ozVT4nUGKIc2DoBYu9dW6u2xIOX5jmDgDFweD3DHylBWcR8onWtCJNPaRZMe57gXJdd kN9ThM8EJvphMF3+LS8ueJfLgUNRb4gTuP5kbNNmpwCW6DTL6DAFXwV3ew0iCZxSLPQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795211974; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=nEXxawZRBRn58OZRiMFm93IHmkm3WqdHBrYSH2F97J0=; b=qev0Ppmb3g9PgGmRmcQph7krezNrFjSwSEhSrwqG5GlJH+1nIQv3sxGwmbq6QOiSanfu 0HTNTaPokeW/ffX6NTVU1bATs8J3HjbDQdPAv2lMVu+51tRqxIFiJyACELRTf+C+tOT/R mciWwO9KLfriMASy+30//PvEzmJioB3t7OLd6tI591bCXSbFk93DN1UbrnfY8/wG4epxv 22jLfEOcFZYunTxBDqKPSOvrY6f8kfJ3S7/oywyTFrng7ezb6Cn1U4hWXNDK/omuO0CNu R8suN7OoDb9DYbOdp4EhygFIEYht9o4JvKjoX7zbFW6+UA9SONxyiNRB1cGb/M4ih7g== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=JZENisR+; arc=none smtp.remote-ip=209.85.222.197 Received: from mail-qk1-f197.google.com (mail-qk1-f197.google.com [209.85.222.197]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id AF33660A2622 for ; Fri, 20 Nov 2026 21:59:31 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org AF33660A2622 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=JZENisR+ Received: by mail-qk1-f197.google.com with SMTP id af79cd13be357-9495af07676so220455685a.2 for ; Fri, 20 Nov 2026 13:59:31 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795211971; x=1795816771; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=nEXxawZRBRn58OZRiMFm93IHmkm3WqdHBrYSH2F97J0=; b=JZENisR+dsnSLPTxgwq7+eaILFggQMtKBFxJ2/ugWj6ndtT1X8CCAoZrvRy1enbglg WQ1356IR3qpk0/D/zilTiNJ6jimNaaYOSgrSEPsjJ3tmGS5XPEEF35KQHwMkA9Rg1LdE ZnatpUS3dh5RfpN1jH6zbKP8kPwa8lHWl+OMnfOIMs0khx220xgGFiBlmgXSLICDKrfW 1KutaXHS7opegdEWudAIt2spq7/2VW4PhiQGBDmaYDwRvDvcOGjjQA9+1A078pt1A31g Kkj0OnMzGTMOuXHqrIyI45rK2JrGSMB/Od0wGtrFaH149JPbFldCgheK0fSZ2JGVtbcT BhTQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795211971; x=1795816771; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=nEXxawZRBRn58OZRiMFm93IHmkm3WqdHBrYSH2F97J0=; b=TwuYRumKFGMGcspYbAfpKvUL+xkMjzPz8Pyxsz2GUd5Fs24Mwlc52gU8TpEIUutXnJ vgYvrDPQ3qdcPGLry8YOyjvIFIXzbv/3PBYR1fYtl+ikvlRAGSIU/JJnhF1qB+0H3Bx7 kieJNObZuNjU01JfjJxTn0s75Xci7vbCme9oCiFAtIOXz+c9GpQnKakYy9L/acCr8Hu3 Bcavpd//BP2y5mKWvZZdW0iEMETtkiFx8+Rv6pkp34aD4lG3KXztZFdDC5WFLZEAq5wa LXNS6WeBa+zqGjJnopxxjRXVPCYlaj5pYyBaE7y49EaKRfzCOTyZcib76QRt2IAMyEjh NocA== X-Forwarded-Encrypted: i=1; AL+hErHWNY5pDjPcJ4zdOzkEqwO7T+1jhS2g9rj0rqm3KBc6TNpO2o3bn6Z3D6kv3fvSD3ClHhzsHx+2jrMLElg=@vger.kernel.org X-Gm-Message-State: APuU4Z+TNnqUq4tt9GSGViJJIW/3XYU/Kwa3d9gIajGAR9qogRcJECvx RM4jCSgcp67N2FvRaiUbojaQuS2BQysn18T3KLOhGRKbv3km1Gdq6JPdP4JGKj/DTXDuMThAybi iZcXoQeeYtB+m/oi/8d5D6JemejPs X-Received: from qknpf7.prod.google.com ([2002:a05:620a:8587:b0:949:4c6b:168d]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:620a:46a3:b0:949:7069:3fab with SMTP id af79cd13be357-949bab3e9aemr804413285a.83.1795211970457; Fri, 20 Nov 2026 13:59:30 -0800 (PST) Date: Fri, 20 Nov 2026 16:59:14 -0500 In-Reply-To: <20261120215916.3149345-1-briandaniels@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261120215916.3149345-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261120215916.3149345-5-briandaniels@google.com> Subject: [PATCH v11 4/6] media: virtio: Add buffer streaming, event handling, and poll From: Brian Daniels To: Mauro Carvalho Chehab Cc: adelva@google.com, aesteve@redhat.com, changyeon@google.com, daniel.almeida@collabora.com, eperezma@redhat.com, gnurou@gmail.com, gurchetansingh@google.com, hverkuil@xs4all.nl, linux-kernel@vger.kernel.org, linux-media@vger.kernel.org, mst@redhat.com, nicolas.dufresne@collabora.com, virtualization@lists.linux.dev, xuanzhuo@linux.alibaba.com, dbassey@redhat.com, laurent.pinchart@ideasonboard.com, Brian Daniels Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Alexandre Courbot 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 Assisted-by: LLM Co-developed-by: Brian Daniels Signed-off-by: Brian Daniels --- 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/vir= tio/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 scat= terlist_builder *builder, return 0; } =20 +/** + * scatterlist_builder_add_buffer() - Add a &struct v4l2_buffer and its pl= anes + * 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 =3D 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 =3D 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 sh= adow + * 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 bu= ffer + * 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 s= hould + * not modify it, but we enforce this for additional safety. + */ +int scatterlist_builder_retrieve_buffer(struct scatterlist_builder *builde= r, + size_t sg_index, struct v4l2_buffer *b, + struct v4l2_plane *orig_planes) +{ + int ret; + + ret =3D scatterlist_builder_retrieve_data(builder, sg_index++, b); + if (ret) + return ret; + + if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) { + b->m.planes =3D orig_planes; + + if (orig_planes) { + ret =3D 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 a= nd its * controls to @builder. diff --git a/drivers/media/virtio/scatterlist_builder.h b/drivers/media/vir= tio/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); =20 +int scatterlist_builder_add_buffer(struct scatterlist_builder *builder, + struct v4l2_buffer *buffer); + +int scatterlist_builder_retrieve_buffer(struct scatterlist_builder *builde= r, + 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); =20 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 @@ =20 #include "uapi/linux/virtio_media.h" =20 +#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 =20 +/** + * 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 handl= ed 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 er= ror. * @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; =20 __dma_from_device_group_begin(); union { @@ -57,6 +102,12 @@ struct virtio_media_session { =20 struct sg_table command_sgs; =20 + 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; }; =20 diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/vir= tio_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.lis= t. + * @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 a= re @@ -39,10 +43,16 @@ struct virtio_media { =20 struct virtio_device *virtio_dev; struct virtqueue *commandq; + struct virtqueue *eventq; + struct work_struct eventq_work; + + void *event_buffer; =20 struct list_head sessions; struct mutex sessions_lock; /* protects sessions list */ =20 + 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); =20 /* virtio_media_ioctls.c */ =20 diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/vir= tio/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 #include #include +#include +#include +#include +#include =20 #include #include #include +#include =20 #include "uapi/linux/virtio_media.h" #include "session.h" #include "virtio_media.h" =20 +#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; =20 session =3D kzalloc_obj(*session, GFP_KERNEL); @@ -54,11 +62,20 @@ virtio_media_session_alloc(struct virtio_media *vv, str= uct file *file) =20 // The caller is expected to set the ID once the host assigns a value. session->id =3D 0; + session->nonblocking_dequeue =3D file->f_flags & O_NONBLOCK; =20 INIT_LIST_HEAD(&session->list); v4l2_fh_init(&session->fh, &vv->video_dev); virtio_media_session_fh_add(session, file); =20 + for (i =3D 0; i <=3D 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; =20 err_payload_sgs: @@ -91,11 +108,16 @@ static void virtio_media_session_add(struct virtio_med= ia *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); =20 sg_free_table(&session->command_sgs); =20 + for (i =3D 0; i <=3D 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_me= dia *vv, return 0; } =20 +/** + * 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 =3D NULL; + + mutex_lock(&vv->sessions_lock); + list_for_each(p, &vv->sessions) { + struct virtio_media_session *s =3D + list_entry(p, struct virtio_media_session, list); + if (s->id =3D=3D id) { + session =3D s; + break; + } + } + mutex_unlock(&vv->sessions_lock); + + return session; +} + /** * struct virtio_media_cmd_callback_param - Callback parameters to the vir= tio * command queue. @@ -290,6 +337,234 @@ int virtio_media_send_command(struct virtio_media *vv= , struct scatterlist **sgs, return 0; } =20 +/** + * 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] =3D &vresp; + + ret =3D 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 =3D queue->vdev->priv; + + schedule_work(&vv->eventq_work); +} + +/** + * virtio_media_process_dqbuf_event() - Process a dequeued event for a ses= sion. + * @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 =3D 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 >=3D ARRAY_SIZE(session->queues)) { + v4l2_err(&vv->v4l2_dev, + "unmanaged queue %d passed to dqbuf event", + dqbuf_evt->buffer.type); + return; + } + queue =3D &session->queues[queue_type]; + + if (dqbuf_evt->buffer.index >=3D 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 =3D &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 =3D dqbuf->buffer.m; + memcpy(&dqbuf->buffer, &dqbuf_evt->buffer, sizeof(dqbuf->buffer)); + dqbuf->buffer.m =3D 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 =3D 0; i < dqbuf->buffer.length; i++) { + plane_m =3D dqbuf->planes[i].m; + memcpy(&dqbuf->planes[i], &dqbuf_evt->planes[i], + sizeof(struct v4l2_plane)); + dqbuf->planes[i].m =3D plane_m; + } + } + + /* Set the DONE flag as the buffer is waiting to be dequeued. */ + dqbuf->buffer.flags |=3D V4L2_BUF_FLAG_DONE; + + mutex_lock(&session->queues_lock); + list_add_tail(&dqbuf->list, &queue->pending_dqbufs); + queue->queued_bufs -=3D 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 =3D 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 =3D 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 =3D (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 =3D 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 =3D (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 =3D (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 =3D + 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 =3D fh_to_session(file->private_data); =20 - int ret =3D virtio_media_session_close(vv, session); + mutex_lock(&session->error_lock); + bool session_error =3D session->error; + + mutex_unlock(&session->error_lock); + + int ret =3D 0; + + /* If session is in an error state, then it has already been closed */ + if (!session_error) + ret =3D virtio_media_session_close(vv, session); =20 virtio_media_session_remove(vv, session); virtio_media_session_free(session); @@ -358,10 +642,66 @@ static int virtio_media_device_close(struct file *fil= e) return ret; } =20 +/** + * 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 *wa= it) +{ + struct virtio_media_session *session =3D + fh_to_session(file->private_data); + enum v4l2_buf_type capture_type =3D + session->uses_mplane ? V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE : + V4L2_BUF_TYPE_VIDEO_CAPTURE; + enum v4l2_buf_type output_type =3D + session->uses_mplane ? V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE : + V4L2_BUF_TYPE_VIDEO_OUTPUT; + struct virtio_media_queue_state *capture_queue =3D + &session->queues[capture_type]; + struct virtio_media_queue_state *output_queue =3D + &session->queues[output_type]; + __poll_t req_events =3D poll_requested_events(wait); + __poll_t rc =3D 0; + + poll_wait(file, &session->dqbuf_wait, wait); + poll_wait(file, &session->fh.wait, wait); + + mutex_lock(&session->error_lock); + if (session->error) + rc |=3D EPOLLERR; + mutex_unlock(&session->error_lock); + + mutex_lock(&session->queues_lock); + if (req_events & (EPOLLIN | EPOLLRDNORM)) { + if (!capture_queue->streaming || + (capture_queue->queued_bufs =3D=3D 0 && + list_empty(&capture_queue->pending_dqbufs))) + rc |=3D EPOLLERR; + else if (!list_empty(&capture_queue->pending_dqbufs) || + capture_queue->is_capture_last) + rc |=3D EPOLLIN | EPOLLRDNORM; + } + if (req_events & (EPOLLOUT | EPOLLWRNORM)) { + if (!output_queue->streaming) + rc |=3D EPOLLERR; + else if (output_queue->queued_bufs < + output_queue->allocated_bufs) + rc |=3D EPOLLOUT | EPOLLWRNORM; + } + mutex_unlock(&session->queues_lock); + + if (v4l2_event_pending(&session->fh)) + rc |=3D EPOLLPRI; + + return rc; +} + static const struct v4l2_file_operations virtio_media_fops =3D { .owner =3D THIS_MODULE, .open =3D virtio_media_device_open, .release =3D virtio_media_device_close, + .poll =3D virtio_media_device_poll, .unlocked_ioctl =3D virtio_media_device_ioctl, }; =20 @@ -371,29 +711,47 @@ static void virtio_media_release(struct v4l2_device *= v4l2_dev) container_of(v4l2_dev, struct virtio_media, v4l2_dev); =20 v4l2_device_unregister(&vv->v4l2_dev); + kfree(vv->event_buffer); kfree(vv); } =20 static int virtio_media_probe(struct virtio_device *virtio_dev) { struct device *dev =3D &virtio_dev->dev; - struct virtqueue *vqs[1]; - static struct virtqueue_info vq_info[1] =3D { + struct virtqueue *vqs[2]; + static struct virtqueue_info vq_info[2] =3D { { .name =3D "command", .callback =3D commandq_callback, }, + { + .name =3D "event", + .callback =3D eventq_callback, + }, }; struct virtio_media *vv; struct video_device *vd; + int i; int ret; =20 vv =3D kzalloc_obj(struct virtio_media); if (!vv) return -ENOMEM; =20 + const size_t virtio_media_event_aligned_size =3D + ALIGN(VIRTIO_MEDIA_EVENT_MAX_SIZE, dma_get_cache_alignment()); + + vv->event_buffer =3D kzalloc(virtio_media_event_aligned_size * + VIRTIO_MEDIA_NUM_EVENT_BUFS, + GFP_KERNEL); + if (!vv->event_buffer) { + ret =3D -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); =20 vv->virtio_dev =3D virtio_dev; @@ -403,15 +761,17 @@ static int virtio_media_probe(struct virtio_device *v= irtio_dev) =20 ret =3D v4l2_device_register(dev, &vv->v4l2_dev); if (ret) - goto err_free_virtio_media; + goto err_free_event_buffer; =20 vv->v4l2_dev.release =3D virtio_media_release; =20 - ret =3D virtio_find_vqs(virtio_dev, 1, vqs, vq_info, NULL); + ret =3D virtio_find_vqs(virtio_dev, 2, vqs, vq_info, NULL); if (ret) goto err_v4l2_device_unregister; =20 vv->commandq =3D vqs[0]; + vv->eventq =3D vqs[1]; + INIT_WORK(&vv->eventq_work, virtio_media_event_work); =20 vd =3D &vv->video_dev; vd->v4l2_dev =3D &vv->v4l2_dev; @@ -449,13 +809,34 @@ static int virtio_media_probe(struct virtio_device *v= irtio_dev) if (ret) goto err_del_vqs; =20 + mutex_lock(&vv->events_lock); + + for (i =3D 0; i < VIRTIO_MEDIA_NUM_EVENT_BUFS; i++) { + void *ebuf =3D vv->event_buffer + + virtio_media_event_aligned_size * i; + + ret =3D virtio_media_send_event_buffer(vv, ebuf); + if (ret) + break; + } + + mutex_unlock(&vv->events_lock); + + if (ret) + goto err_video_unregister_device; + return 0; =20 +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 *v= irtio_dev) /* Remove the video device to stop accessing the commandq virtqueue */ video_unregister_device(&vv->video_dev); =20 + /* 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 *v= irtio_dev) */ while (virtqueue_detach_unused_buf(vv->commandq)) ; + while (virtqueue_detach_unused_buf(vv->eventq)) + ; =20 /* Delete the virtqueues */ virtio_dev->config->del_vqs(virtio_dev); diff --git a/drivers/media/virtio/virtio_media_ioctls.c b/drivers/media/vir= tio/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 #include #include +#include +#include #include =20 #include "scatterlist_builder.h" @@ -221,6 +223,101 @@ static int virtio_media_send_wr_ioctl(struct v4l2_fh = *fh, u32 ioctl, return 0; } =20 +/** + * 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 =3D fh->vdev; + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D fh_to_session(fh); + struct v4l2_plane *orig_planes =3D 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 =3D { + .descs =3D session->command_sgs.sgl, + .num_descs =3D DESC_CHAIN_MAX_LEN, + .cur_desc =3D 0, + .shadow_buffer =3D session->shadow_buf, + .shadow_buffer_size =3D VIRTIO_SHADOW_BUF_SIZE, + .shadow_buffer_pos =3D 0, + .sgs =3D sgs, + .num_sgs =3D ARRAY_SIZE(sgs), + .cur_sg =3D 0, + .framevecs =3D 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 =3D b->m.planes; + + /* Command descriptor */ + ret =3D scatterlist_builder_add_ioctl_cmd(&builder, session, ioctl); + if (ret) + return ret; + + /* Command payload (struct v4l2_buffer) */ + ret =3D scatterlist_builder_add_buffer(&builder, b); + if (ret < 0) + return ret; + + end_buf_sg =3D builder.cur_sg; + num_cmd_sgs =3D builder.cur_sg; + + /* Response descriptor */ + ret =3D scatterlist_builder_add_ioctl_resp(&builder, session); + if (ret) + return ret; + + /* Response payload (same as input, but no userptr mapping) */ + for (i =3D 1; i < end_buf_sg; i++) { + ret =3D scatterlist_builder_add_descriptor(&builder, i); + if (ret < 0) + return ret; + } + + ret =3D 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 -=3D sizeof(struct virtio_media_resp_ioctl); + + /* Make sure that the reply length covers our v4l2_buffer */ + if (resp_len < sizeof(*b)) + return -EINVAL; + + ret =3D 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; } =20 +/** + * 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 =3D + list_entry(p, struct virtio_media_buffer, list); + + list_del(&dqbuf->list); + } + + /* All buffers are now dequeued. */ + for (i =3D 0; i < queue->allocated_bufs; i++) + queue->buffers[i].buffer.flags =3D 0; + + queue->queued_bufs =3D 0; + queue->streaming =3D false; + queue->is_capture_last =3D 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 *fi= le, void *fh, ctrls); } =20 +/* + * 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 =3D fh->vdev; + struct virtio_media *vv =3D to_virtio_media(video_dev); + int ret; + + /* First subscribe to the event in the guest. */ + switch (sub->type) { + case V4L2_EVENT_SOURCE_CHANGE: + ret =3D v4l2_src_change_event_subscribe(fh, sub); + break; + default: + ret =3D v4l2_event_subscribe(fh, sub, 1, NULL); + break; + } + if (ret) + return ret; + + /* Then ask the host to signal us these events. */ + ret =3D 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 =3D virtio_media_send_w_ioctl(fh, VIDIOC_UNSUBSCRIBE_EVENT, sub, + sizeof(*sub)); + if (ret < 0) + return ret; + + ret =3D 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 =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + int ret; + + if (i > VIRTIO_MEDIA_LAST_QUEUE) + return -EINVAL; + + ret =3D virtio_media_send_w_ioctl(vfh, VIDIOC_STREAMON, &i, sizeof(i)); + if (ret < 0) + return ret; + + session->queues[i].streaming =3D true; + + return 0; +} + +static int virtio_media_streamoff(struct file *file, void *fh, + enum v4l2_buf_type i) +{ + struct v4l2_fh *vfh =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + int ret; + + if (i > VIRTIO_MEDIA_LAST_QUEUE) + return -EINVAL; + + ret =3D 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 =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + struct virtio_media_buffer *buffers =3D NULL; + struct virtio_media_queue_state *queue; + int ret; + + if (b->type > VIRTIO_MEDIA_LAST_QUEUE) + return -EINVAL; + + if (b->memory =3D=3D V4L2_MEMORY_USERPTR) + return -EINVAL; + + if (b->count > 0) { + buffers =3D + vcalloc(b->count, sizeof(struct virtio_media_buffer)); + if (!buffers) + return -ENOMEM; + } + + ret =3D virtio_media_send_wr_ioctl(vfh, VIDIOC_REQBUFS, b, sizeof(*b), + sizeof(*b)); + if (ret) { + vfree(buffers); + return ret; + } + + queue =3D &session->queues[b->type]; + + /* REQBUFS(0) is an implicit STREAMOFF. */ + if (b->count =3D=3D 0) + virtio_media_clear_queue(session, queue); + + vfree(queue->buffers); + queue->buffers =3D buffers; + + queue->allocated_bufs =3D 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 =3D true; + + b->capabilities &=3D ~V4L2_BUF_CAP_SUPPORTS_USERPTR; + + /* We do not support DMABUF yet. */ + b->capabilities &=3D ~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 =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + struct virtio_media_queue_state *queue; + struct virtio_media_buffer *buffer; + + int ret =3D virtio_media_send_buffer_ioctl(vfh, VIDIOC_QUERYBUF, b); + + if (ret) + return ret; + + if (b->type > VIRTIO_MEDIA_LAST_QUEUE) + return -EINVAL; + + queue =3D &session->queues[b->type]; + if (b->index >=3D queue->allocated_bufs) + return -EINVAL; + + buffer =3D &queue->buffers[b->index]; + /* + * Set the DONE flag if the buffer is waiting in our own dequeue + * queue. + */ + b->flags |=3D (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 =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + struct virtio_media_queue_state *queue; + struct virtio_media_buffer *buffers =3D NULL; + u32 type =3D b->format.type; + int ret; + + if (type > VIRTIO_MEDIA_LAST_QUEUE) + return -EINVAL; + + queue =3D &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 =3D vcalloc(queue->allocated_bufs + b->count, + sizeof(*queue->buffers)); + if (!buffers) + return -ENOMEM; + } + + ret =3D 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 =3D=3D 0) + return 0; + + memcpy(buffers, queue->buffers, + sizeof(*queue->buffers) * queue->allocated_bufs); + vfree(queue->buffers); + queue->buffers =3D buffers; + + queue->allocated_bufs =3D 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 =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D 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 =3D &session->queues[b->type]; + if (b->index >=3D queue->allocated_bufs) + return -EINVAL; + buffer =3D &queue->buffers[b->index]; + + buffer->buffer.m =3D b->m; + if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) { + if (b->length > VIDEO_MAX_PLANES) + return -EINVAL; + for (i =3D 0; i < b->length; i++) + buffer->planes[i].m =3D b->m.planes[i].m; + } + + ret =3D virtio_media_send_buffer_ioctl(vfh, VIDIOC_PREPARE_BUF, b); + if (ret) + return ret; + + buffer->buffer.flags =3D V4L2_BUF_FLAG_PREPARED; + + return 0; +} + +static int virtio_media_qbuf(struct file *file, void *fh, struct v4l2_buff= er *b) +{ + struct v4l2_fh *vfh =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D 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 =3D &session->queues[b->type]; + if (b->index >=3D queue->allocated_bufs) + return -EINVAL; + buffer =3D &queue->buffers[b->index]; + prepared =3D 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 =3D b->m; + if (V4L2_TYPE_IS_MULTIPLANAR(b->type)) { + if (b->length > VIDEO_MAX_PLANES) + return -EINVAL; + for (i =3D 0; i < b->length; i++) + buffer->planes[i].m =3D b->m.planes[i].m; + } + } + old_flags =3D buffer->buffer.flags; + buffer->buffer.flags =3D V4L2_BUF_FLAG_QUEUED; + + ret =3D virtio_media_send_buffer_ioctl(vfh, VIDIOC_QBUF, b); + if (ret) { + /* Rollback the previous flags as the buffer is not queued. */ + buffer->buffer.flags =3D old_flags; + return ret; + } + + queue->queued_bufs +=3D 1; + + return 0; +} + +static int virtio_media_dqbuf(struct file *file, void *fh, + struct v4l2_buffer *b) +{ + struct video_device *video_dev =3D video_devdata(file); + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D + 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 =3D NULL; + const bool is_multiplanar =3D V4L2_TYPE_IS_MULTIPLANAR(b->type); + int ret; + bool error; + + if (b->type > VIRTIO_MEDIA_LAST_QUEUE) + return -EINVAL; + + queue =3D &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 =3D &queue->pending_dqbufs; + + if (session->nonblocking_dequeue) { + if (list_empty(buffer_queue)) + return -EAGAIN; + } else if (queue->allocated_bufs =3D=3D 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 =3D 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 =3D session->error; + mutex_unlock(&session->error_lock); + + if (error) + return -EIO; + + mutex_lock(&session->queues_lock); + dqbuf =3D 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 &=3D ~V4L2_BUF_FLAG_DONE; + + if (is_multiplanar) { + size_t nb_planes =3D min_t(u32, b->length, VIDEO_MAX_PLANES); + + memcpy(b->m.planes, dqbuf->planes, + nb_planes * sizeof(struct v4l2_plane)); + planes_backup =3D b->m.planes; + } + + memcpy(b, &dqbuf->buffer, sizeof(*b)); + + if (is_multiplanar) + b->m.planes =3D planes_backup; + + if (V4L2_TYPE_IS_CAPTURE(b->type) && b->flags & V4L2_BUF_FLAG_LAST) + queue->is_capture_last =3D 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, v= oid *fh, unsigned int o) sizeof(output), sizeof(output)); } =20 +/* + * 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 =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + + int ret =3D 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 =3D=3D V4L2_DEC_CMD_START) { + session->queues[V4L2_BUF_TYPE_VIDEO_CAPTURE].is_capture_last =3D + false; + session->queues[V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE] + .is_capture_last =3D 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 = =3D { .vidioc_try_fmt_meta_cap =3D virtio_media_try_fmt, .vidioc_try_fmt_meta_out =3D virtio_media_try_fmt, =20 + /* Buffer handlers */ + .vidioc_reqbufs =3D virtio_media_reqbufs, + .vidioc_querybuf =3D virtio_media_querybuf, + .vidioc_qbuf =3D virtio_media_qbuf, + .vidioc_expbuf =3D NULL, + .vidioc_dqbuf =3D virtio_media_dqbuf, + .vidioc_create_bufs =3D virtio_media_create_bufs, + .vidioc_prepare_buf =3D virtio_media_prepare_buf, + /* Overlay interface not supported yet */ + .vidioc_overlay =3D NULL, + /* Overlay interface not supported yet */ + .vidioc_g_fbuf =3D NULL, + /* Overlay interface not supported yet */ + .vidioc_s_fbuf =3D NULL, + + /* Stream on/off */ + .vidioc_streamon =3D virtio_media_streamon, + .vidioc_streamoff =3D virtio_media_streamoff, + /* Standard handling */ .vidioc_g_std =3D virtio_media_g_std, .vidioc_s_std =3D virtio_media_s_std, @@ -667,6 +1269,7 @@ const struct v4l2_ioctl_ops virtio_media_ioctl_ops =3D= { .vidioc_g_enc_index =3D virtio_media_g_enc_index, .vidioc_encoder_cmd =3D virtio_media_encoder_cmd, .vidioc_try_encoder_cmd =3D virtio_media_try_encoder_cmd, + .vidioc_decoder_cmd =3D virtio_media_decoder_cmd, .vidioc_try_decoder_cmd =3D virtio_media_try_decoder_cmd, =20 /* Stream type-dependent parameter ioctls */ @@ -701,6 +1304,9 @@ const struct v4l2_ioctl_ops virtio_media_ioctl_ops =3D= { .vidioc_g_edid =3D NULL, .vidioc_s_edid =3D NULL, =20 + .vidioc_subscribe_event =3D virtio_media_subscribe_event, + .vidioc_unsubscribe_event =3D virtio_media_unsubscribe_event, + /* For other private ioctls */ .vidioc_default =3D NULL, }; @@ -714,9 +1320,19 @@ long virtio_media_device_ioctl(struct file *file, uns= igned int cmd, struct v4l2_standard standard; v4l2_std_id std_id =3D 0; int ret; + bool error; =20 - if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags)) + if (test_bit(V4L2_FL_USES_V4L2_FH, &video_dev->flags)) { vfh =3D file_to_v4l2_fh(file); + struct virtio_media_session *session =3D fh_to_session(vfh); + + mutex_lock(&session->error_lock); + error =3D session->error; + mutex_unlock(&session->error_lock); + + if (error) + return -EIO; + } =20 mutex_lock(&vv->vlock); =20 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; }; =20 +/* 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 consi= dered + * 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 dequeu= ed. + * @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 --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 16:49:38 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=74.125.224.69 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795211975; b=kbeQL8gqWSU6rBHBgWU9OJfpwwJkG+toeSqtAIMl4hOwXe/DhGxqtSdz6LZvxxEruFsu lXcK5e6PFJw2D3kfgATPHxAE2BCeaNxoe6G1aPoeEQ6UJq+1F9Sn/4oHwqQbeeJX+XLem TVmHAxElVnJAtmlqNePwMyFytlvNIrRKN/fYQGhlW0CesqRPONuv8KqxzkP/xjCf8XfTf n0q8J5SQyM1y/4a6KPkfoQHnuh4BgqUvT81qH482lszYCJ88I5l00Cyp3wSKc4BW1+02t AqqYixvV5GlJHdAZ1WB5/AHevZkQIyLJgeVvL5368VSrN98xKpyVPPHf1jfQ3PRmrEA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795211975; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=Jt9RCBa8sBvR061AaSkNCLxjeK/ds/G5ZqPF9nB3MHo=; b=H5UL+2nR0YaC2bTJMpmvp1xxs+J+eUiutDoM2xQNhtwBhcGMYUNPKNRlPTqqRELKENr1 CVPViZJvoBpG1kEKV4qxTk9lQFLZGO8ok9T8bgVDbGAMVNQtqH8TZzLJ7VciMRfXVL0wN wvFA9k4uQeoBJNQbdlWMLeTTm2KtOtmDfi9227Pae81NrLlUFkjAvVHnVqUjklhK4ybyi BEFumRgcRsV5FE8F3euFKgYrjLIJ2iABz1oGrGsnDlyO+xiq4Cor98KMVqcU807UvZzu0 yvjwqcVMlTN4pBqP3gvK1Gs5UZMrvrrgyHzAMN9I1afQ2nstCL5j0ricM6JFuxQSlpg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=hUHuwLjn; arc=none smtp.remote-ip=74.125.224.69 Received: from mail-yx1-f69.google.com (mail-yx1-f69.google.com [74.125.224.69]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 42F1A606A68B for ; Fri, 20 Nov 2026 21:59:33 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 42F1A606A68B Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=hUHuwLjn Received: by mail-yx1-f69.google.com with SMTP id 956f58d0204a3-677c4ca2265so2445447d50.2 for ; Fri, 20 Nov 2026 13:59:33 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795211972; x=1795816772; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=Jt9RCBa8sBvR061AaSkNCLxjeK/ds/G5ZqPF9nB3MHo=; b=hUHuwLjnaw2waPEA3gbRkaue8jIUyad3T/hL7GzGNTJGZjwpQgzcUpzwLym/+Qt/hr ET9zhJ1THltN8n0Ly3x2zP1XuDqE9vX1YyNCJLtqaJDpshpt1f0BUHPHdhvUpiTGDoi+ /HX6PzvNRRHBN9bdvHhF3wi9YUqcmEvpY2pdszuYXyKrX+We62CEstg0C4zgNdQq7li2 /1i9qN++kRpvcxR3alOZ35pRGLR+4MRIpFJ8p+vtTruCtdwlD43+uvCHhBwcfIOXnFPF TKcfgmJ3KGNvCczTXjoFi8tIuoXstHL3TGInNXn5yrvRvXMzQRKfDIB4j42JVDxmRugs mPfA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795211972; x=1795816772; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=Jt9RCBa8sBvR061AaSkNCLxjeK/ds/G5ZqPF9nB3MHo=; b=NcHR1gc6vyfzvUWNnnQRUVe6OO7BVYwBNtNdyh77U0l/KNeVLtGZ9+KzB70RnxMojl f7O8QQNj/Fy5El3CMjAOa8sMBiBvPCTAexi9jYRMIJLtB+00qZu+U/4WmPW+aWE5T1Y7 8iQuZXDm7HaFIUPApiXmVWIPSvaNJ5TgKjBQJckNBwrELipyjhucVwitCVv3EmPEzLgE o+22yeBCnHSqKvYoiH/2w2ZDnw4gYtuYW9LYj8eoDpLY5Hk0fTHxKTIVeXyPmr6eDq7Z lep8v36JFPUCifnPwWpCuDOH9fbguAMcCrXc3tB64JhfgPCTN6529dNlwyDDCtWkTdiL vpGQ== X-Forwarded-Encrypted: i=1; AL+hErGEaeb9h/CgP7eGRUlhC6KLGOICAicdj32ccRgR6x7Rg083JqCvAEzFZIvjnSDz4bdSrACB3k+WipY5K2Q=@vger.kernel.org X-Gm-Message-State: APuU4Z96LLnVW+R91a0QydiRqcSV8PuBYnaXGUZsksudHTCGkUBJtZGV b3pHAAj7LiN9WV1Q4kSHb+DNxuGmIx78KvKQ/MFmvsndvbH8OtCsPpM+ZGjfFR+nGf8X2UZkL68 VQJwifp29f1E0keEunFmWAucSLxd7 X-Received: from yxws18.prod.google.com ([2002:a53:de52:0:b0:679:1d65:95e]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:690e:480c:b0:672:e7e1:f3de with SMTP id 956f58d0204a3-67df44bf2f6mr805895d50.73.1795211972187; Fri, 20 Nov 2026 13:59:32 -0800 (PST) Date: Fri, 20 Nov 2026 16:59:15 -0500 In-Reply-To: <20261120215916.3149345-1-briandaniels@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261120215916.3149345-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261120215916.3149345-6-briandaniels@google.com> Subject: [PATCH v11 5/6] media: virtio: Add MMAP buffer mapping support From: Brian Daniels To: Mauro Carvalho Chehab Cc: adelva@google.com, aesteve@redhat.com, changyeon@google.com, daniel.almeida@collabora.com, eperezma@redhat.com, gnurou@gmail.com, gurchetansingh@google.com, hverkuil@xs4all.nl, linux-kernel@vger.kernel.org, linux-media@vger.kernel.org, mst@redhat.com, nicolas.dufresne@collabora.com, virtualization@lists.linux.dev, xuanzhuo@linux.alibaba.com, dbassey@redhat.com, laurent.pinchart@ideasonboard.com, Brian Daniels Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Alexandre Courbot 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 Assisted-by: LLM Co-developed-by: Brian Daniels Signed-off-by: Brian Daniels --- 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 handl= ed 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 cha= in 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; =20 union { struct virtio_media_resp_ioctl ioctl; + struct virtio_media_resp_mmap mmap; } resp; __dma_from_device_group_end(); =20 diff --git a/drivers/media/virtio/virtio_media.h b/drivers/media/virtio/vir= tio_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.lis= t. * @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 a= re - * 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``. T= he + * 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; =20 + struct virtio_shm_region mmap_region; + void *event_buffer; =20 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; =20 union { struct virtio_media_resp_open open; + struct virtio_media_resp_munmap munmap; } resp; __dma_from_device_group_end(); =20 diff --git a/drivers/media/virtio/virtio_media_driver.c b/drivers/media/vir= tio/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. */ =20 +#include #include #include #include @@ -20,6 +21,7 @@ #include #include #include +#include =20 #include #include @@ -32,6 +34,12 @@ =20 #define VIRTIO_MEDIA_NUM_EVENT_BUFS 16 =20 +/* 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; } =20 +static void virtio_media_vma_close_locked(struct vm_area_struct *vma) +{ + struct virtio_media *vv =3D vma->vm_private_data; + struct virtio_media_cmd_munmap *cmd_munmap =3D &vv->cmd.munmap; + struct virtio_media_resp_munmap *resp_munmap =3D &vv->resp.munmap; + struct scatterlist cmd_sg =3D {}, resp_sg =3D {}; + struct scatterlist *sgs[2] =3D { &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 =3D VIRTIO_MEDIA_CMD_MUNMAP; + cmd_munmap->hdr.__reserved =3D 0; + cmd_munmap->driver_addr =3D + (vma->vm_pgoff << PAGE_SHIFT) - vv->mmap_region.addr; + ret =3D 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 nee= ded + * and can be removed. + */ +static void virtio_media_vma_close(struct vm_area_struct *vma) +{ + struct virtio_media *vv =3D 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 =3D { + .close =3D 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 =3D video_devdata(file); + struct virtio_media *vv =3D to_virtio_media(video_dev); + struct virtio_media_session *session =3D + fh_to_session(file->private_data); + struct virtio_media_cmd_mmap *cmd_mmap =3D &session->cmd.mmap; + struct virtio_media_resp_mmap *resp_mmap =3D &session->resp.mmap; + struct scatterlist cmd_sg =3D {}, resp_sg =3D {}; + struct scatterlist *sgs[2] =3D { &cmd_sg, &resp_sg }; + int ret; + + mutex_lock(&session->error_lock); + bool session_error =3D 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 =3D VIRTIO_MEDIA_CMD_MMAP; + cmd_mmap->hdr.__reserved =3D 0; + cmd_mmap->session_id =3D session->id; + cmd_mmap->flags =3D + (vma->vm_flags & VM_WRITE) ? VIRTIO_MEDIA_MMAP_FLAG_RW_MASK : 0; + cmd_mmap->offset =3D vma->vm_pgoff << PAGE_SHIFT; + cmd_mmap->__reserved =3D 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 =3D virtio_media_send_command(vv, sgs, 1, 1, sizeof(*resp_mmap), + NULL); + if (ret < 0) + goto end; + + vma->vm_private_data =3D vv; + /* + * Keep the guest address at which the buffer is mapped since we will + * use that to unmap. + */ + vma->vm_pgoff =3D (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 =3D -EINVAL; + goto cleanup; + } + + ret =3D 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 =3D &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 =3D { .owner =3D THIS_MODULE, .open =3D virtio_media_device_open, .release =3D virtio_media_device_close, .poll =3D virtio_media_device_poll, .unlocked_ioctl =3D virtio_media_device_ioctl, + .mmap =3D virtio_media_device_mmap, }; =20 static void virtio_media_release(struct v4l2_device *v4l2_dev) @@ -773,6 +924,14 @@ static int virtio_media_probe(struct virtio_device *vi= rtio_dev) vv->eventq =3D vqs[1]; INIT_WORK(&vv->eventq_work, virtio_media_event_work); =20 + /* 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 =3D -ENOMEM; + goto err_del_vqs; + } + vd =3D &vv->video_dev; vd->v4l2_dev =3D &vv->v4l2_dev; vd->ioctl_ops =3D &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; }; =20 +/** + * 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 driv= er'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_MM= AP. + * @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_MU= NMAP. + * @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 --=20 2.56.1.750.gf70dc682cf-goog From nobody Tue Nov 24 16:49:38 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.222.198 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795211978; b=opSjUswuhdkWT3hUI1r5Y3K6X1+qiAPYEHWRmVwAutn0WlXo5ETEx6MIl7A4UAjdPP8T QiEAkEWe8oathcYzM8gflOjcKsihc8s8564pP1cvEUewFQmAdd3ts5C4ihQ1PoI1cwuWy dFUGgsbxwbk5myAwib1scdpecsaSws/ZrxNntg/EIYonSNF4PEreNkdoiIA16w0fWrukH wzFjUL9JJzvzsmGAgdwuLQFA3XXXkEftYPjUWR99cWMlW1bOPdIVxdVbKlOkg6ptLFHHi 4QvmuSdLDfean4oyIbDBC2A5C7MwstdEYgbbuvUisJ9FCZEJyW4T3QVDRqMk3jv1k+A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795211978; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Received:Date:In-Reply-To: Mime-Version:References:X-Mailer:Message-ID:Subject:From:To:Cc: Content-Type; bh=yQp6wu37grFSLFpLYqDqLuKQZrEDeFa5v47ChyJcE5k=; b=zQGcdAyM5PwYrmqSJ9zA/Vl/r9z5BOHDe8wr0XYtFMk5By24znvaiF20ZjMGSFDzXW46 JemgvSceYZheDM0gQ3QZBPXXROK5llL0GZsX9bT6PsakIEcrXztuSczU4xzx8TJbcheJe 8ZPoOcND9Drz8SzfMirrj790k0/81SHpjiGqGguMdupgp3vHIQL/rZQfCTNqtEvTspfZT JSo+y+KfkkhBAFijAxjJxNgslfLPPut8sU7CJksBVR+DkgeiqhcfdZ3LXoWCVj75fJQ7k SBaYWenqLQ1kQu7UL0zM17Lk9uS6GKsc7R1bLD9MdcfH3XlIG2Ne4HXuPX8aeWWsRng== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=google.com; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com; dkim=pass header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=DmsRgpud; arc=none smtp.remote-ip=209.85.222.198 Received: from mail-qk1-f198.google.com (mail-qk1-f198.google.com [209.85.222.198]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id 95A7F60A2633 for ; Fri, 20 Nov 2026 21:59:35 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 95A7F60A2633 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=reject dis=none) header.from=google.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=flex--briandaniels.bounces.google.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=google.com header.i=@google.com header.a=rsa-sha256 header.s=20260707 header.b=DmsRgpud Received: by mail-qk1-f198.google.com with SMTP id af79cd13be357-9496ff065bcso197115585a.3 for ; Fri, 20 Nov 2026 13:59:35 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795211974; x=1795816774; darn=vger.kernel.org; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:from:to:cc:subject:date:message-id:reply-to :content-type; bh=yQp6wu37grFSLFpLYqDqLuKQZrEDeFa5v47ChyJcE5k=; b=DmsRgpudvuRAzsbrAEXYra7xBF73LG7dlb0dspoO7HXMXrCSj+yw+MfU7007+EbFNZ gZOhcpRUaP8f4Jh0B7CnvIOPaeCArOf7mh56NXtOV4zf74X/GapuOGcVAKdkpX0/A9x8 V98FXDN6TxVl2AduH033kwC03/05kHVH92JzO5cjd5m3cSChRdG/IagciFZMaWhA+0pR ZsZqCGWOY1VUl2MGT72pQ9WHavKn1j/xakZy9cmnQEmNMUwD8qIK3eLEo+6RE9ABeD4c osoVroPlqmX+QH84D/vF4giz/Q1jtRn98dwZ6KT6XrPlX69nYRMbraQ8m/ByButufvjM BK3g== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795211974; x=1795816774; h=content-type:cc:to:from:subject:message-id:references:mime-version :in-reply-to:date:x-gm-message-state:from:to:cc:subject:date :message-id:reply-to:content-type; bh=yQp6wu37grFSLFpLYqDqLuKQZrEDeFa5v47ChyJcE5k=; b=xmKijNo6CgO/U/eE2AtlecFIjyB9XRh/w58bNFlzDAT/HaN687Jb9rPgBIE7N0BCXB 4zPpX0U3zUeiLcYbgasSTjDySFnlQSE0/fzl38zIV2p591ZOplmXgtUZDvdgPXQDG6i5 jbmerecYqSURBAH4tt452+YbtHQdQ8IveWNvd/xWhYKrMsvDaEqBK/Tnbqnq57w/pWt0 T0rKCBKZyR1zUtt7TAUQsbNVSB1FaDVMXvbWvkaTuomxwLsAEQ+nhBsfB5SCF5YYRzNU Qbi54nYLplDqeJT67iQcndhAtvIcVmfrcrXpI5iqJZITUd5SCz3m8zzjpElu5k9qIjQ5 p03w== X-Forwarded-Encrypted: i=1; AL+hErGoFJkMoe3ToQNqWevMiCeIZM2PTm5UsLTbH+niXIn4vqRHET2D8TI486N3KPDWvxld7bqCKCoT3MKfnY8=@vger.kernel.org X-Gm-Message-State: APuU4Z/3goOxcwwQDr+MFXJ50WpG/usSCQCtFSeJfUQYzmcJpQQaKrtj 5dGr82rrtPmJLcsBjyL/sTr2sgoDVy8N4dOk0EjxxUWY4dvDhCd353ULoga/hVarcj/2n7O2o72 dVx5gVFbjhqLZ8m7AQmuLf8q7BMRH X-Received: from qkil7.prod.google.com ([2002:a05:620a:c07:b0:93e:7793:940c]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:620a:4556:b0:93e:c691:a1c with SMTP id af79cd13be357-949bab3d32emr690699785a.76.1795211974300; Fri, 20 Nov 2026 13:59:34 -0800 (PST) Date: Fri, 20 Nov 2026 16:59:16 -0500 In-Reply-To: <20261120215916.3149345-1-briandaniels@google.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list Mime-Version: 1.0 References: <20261120215916.3149345-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261120215916.3149345-7-briandaniels@google.com> Subject: [PATCH v11 6/6] media: virtio: clear the size of legacy controls built on the stack From: Brian Daniels To: Mauro Carvalho Chehab Cc: adelva@google.com, aesteve@redhat.com, changyeon@google.com, daniel.almeida@collabora.com, eperezma@redhat.com, gnurou@gmail.com, gurchetansingh@google.com, hverkuil@xs4all.nl, linux-kernel@vger.kernel.org, linux-media@vger.kernel.org, mst@redhat.com, nicolas.dufresne@collabora.com, virtualization@lists.linux.dev, xuanzhuo@linux.alibaba.com, dbassey@redhat.com, laurent.pinchart@ideasonboard.com, Nick Rogers Content-Transfer-Encoding: quoted-printable Content-Type: text/plain; charset="utf-8" From: Nick Rogers 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 --- 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/vir= tio/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. */ =20 +#include #include #include #include @@ -593,11 +594,31 @@ static int virtio_media_querycap(struct file *file, v= oid *fh, * Extended control ioctls are handled mostly identically. */ =20 +/* + * 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 =3D 0; i < ctrls->count; i++) + ctrls->controls[i].size =3D 0; +} + static int virtio_media_g_ext_ctrls(struct file *file, void *fh, struct v4l2_ext_controls *ctrls) { struct v4l2_fh *vfh =3D file_to_v4l2_fh(file); =20 + 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 =3D file_to_v4l2_fh(file); =20 + 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 =3D file_to_v4l2_fh(file); =20 + virtio_media_legacy_ctrl(ctrls); + return virtio_media_send_ext_controls_ioctl(vfh, VIDIOC_TRY_EXT_CTRLS, ctrls); } --=20 2.56.1.750.gf70dc682cf-goog