From nobody Tue Nov 24 16:50:25 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=1795229419; b=cIW7bOwV6Gn6uJoAN4ubFkQ2uTGLK8D+e40fJLLPOsUwzi2ukHHF8zPrd/6AXgDZ+EDF iIRvF8EjjvA388O/mJLunhjlu0CNG8KWY5JxoiAl6CrbA1klUW5dMOgSmQy86/MNZqLDo a/f/9ILoG7+0mx9uR1CTwIRb6yUNEx2QOsPp86IhRZg6Ez6iOLT23lKJFoQoE9vpQJbOv kRMMdNQ5pfu8I04PZ4qX5cWu7LPLynKTjnUfbQB3Ek9iiCbJgc50nLRVsaglCLZBkl/lD V5qUhaQa9riiSt1bJaD/XodYMdMDlEx3C61zx01WDc/2Q4eTNanrrw/8H0E5dILJleQ== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795229419; 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=OQC+5oFZWg/8m/7XKy1njTpb1n/Pb1rUxnv2mjco1yQ=; b=A3yZORiPLAKJGbZzZ06SMtbltqUsCagVxmYQiDpeOfei5MsxFD6fns2PdEnaO8anoexp 6TUUt7q8/2YU91bcrbHAd1WGitY9CNDycbpE+49nEgggEJlsOgPMw3TF3rpFUYhex8iVZ hhLHYGSDYy+gaFJaBl28C2opHNc4cn/8lYGMu6X12dWcl2m0TFVdzShyTzGSJls4EdYuM 34MADTd5b+uol3e3sjsp4SH00WBt54eZsYEUizxy9zM7EAME+KMNCR7NJzTOWFCXWBaJc dcvWZ/2mH4JhlL9/5AVkIK9nl1T9FVioLO0OFTgR/pG9jLpzyVhmGuyZMFvaEavwTYQ== 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="Dkf9/yEh"; 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 943DC606A68C for ; Sat, 21 Nov 2026 02:50:14 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 943DC606A68C 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=Dkf9/yEh Received: by mail-qk1-f197.google.com with SMTP id af79cd13be357-93f26dd2165so405847585a.3 for ; Fri, 20 Nov 2026 18:50:14 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795229413; x=1795834213; 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=OQC+5oFZWg/8m/7XKy1njTpb1n/Pb1rUxnv2mjco1yQ=; b=Dkf9/yEhZRHmpH4ubr0qYXb/6rH3euKMIA15GYYwCj07JWV5pejFeFTJebVGeWxIEh OhMnPSwUYZ6/z5y89mXivgM1Oweph82ZMuTtrLDPAdQVwbvrUQtGsb/yu8OgWTfQtww/ woQm+nTEXri9RZIi7uD4B+Rd1b9meaf1RrsxygDwiv53MU0LL7p/vWYLim/Jwwb+QMee jX5hasfNYqjW1qA4pJLQMKHqCEfjtfPcJsHwVBcAjrDaXT1hgjjRiOaf+1hLCkvPq0rg pc+sybmAX2NDnXj/P/WiouUKgnl7WIUJNWcEJt7b/Xaql8scBHlbH2yuGokXhiRnffAQ tpBg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795229413; x=1795834213; 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=OQC+5oFZWg/8m/7XKy1njTpb1n/Pb1rUxnv2mjco1yQ=; b=1lMspX/FAC/r6l/Ow99EiGh8dfsIOCEPWh+/BJrQLWPjdgTboQWCbk13NGNg70s6Bo qvqRIO7k5VYoEYn1761j7eNUNsiigHnXBVnve1/vDj2Qa9+nbOee0Td9I9gQxTGIrEGu IbBH7rN/G/Y4jI4dwhEKnTXG0QwebIav2aBeEpq4Mw+OGKtmqylSRLZKrr3AmpV5rD+f V+x0eM4Q5PjGLdKe/xMBvfPYte/Hr2NRCUWNRbDjP/E+DCOnNfxxMsSzyKamY0/Kp1UC twfuE3EAbIbQ11KmozxC1AO2TJzXsAsLDmAXJ/n0LzLcM1Bv9egCjHL6vmrM6e+gvqFl adlA== X-Forwarded-Encrypted: i=1; AL+hErEXmsuZMRzjuPtvzAvmaZaVinrELhR+AQGexKNTdhfWKC5V3LqJbyk2K8bHm9UIhyTvJMvEVJR6MSyGqtY=@vger.kernel.org X-Gm-Message-State: APuU4Z/7PpMz+CQgk3hgFV5OwTOQG0c0yeWmfVuk9OX3No321Fkymhev Zyxde8pLQzFTBjLBoCyJFQ60chBWgYthcZFSRkACqEvqDw1RvE5ZMKl4N+Y+75DLXt7lowvnzKL 7J73WgGidu8HHjV9lcKun7fHUUc7r X-Received: from qknqw11.prod.google.com ([2002:a05:620a:8b0b:b0:949:a126:3644]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:620a:2b45:b0:949:6476:91db with SMTP id af79cd13be357-949ba9e3342mr836991485a.42.1795229413179; Fri, 20 Nov 2026 18:50:13 -0800 (PST) Date: Fri, 20 Nov 2026 21:50:02 -0500 In-Reply-To: <20261121025007.3445723-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: <20261121025007.3445723-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261121025007.3445723-2-briandaniels@google.com> Subject: [PATCH v12 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 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 f72ce07a4..ba8373452 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -29630,6 +29630,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 @@ -29742,6 +29743,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:50:25 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.128.198 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795229419; b=SRPnTqarSJWJoLzj1LSE483ADlnV8mLDTIqMhYwGOGmwQNkY82+C6bnAORIrm6x/NUOA F8oJl+gCNTpb5ZbK6c2ABI26ZFdlwdCyRG5rqB81sVbChCrqnk+vyVKI9e1A1DQ8bPquO 59ll2sLMvOd/K/Z7FLRj2163upnD9AxShzfuJzqGOEbcRYwPX45l8Hmd9rIh91ONwcWIB vrI7Ul5tekgBKyrK6VHfyKKiT6uvlu+4VKLpVQqNZI4TLrtx7Ozd1GgPq2Qw8hguelDyV S9/owS8ePMuBRMURqF7uvJI1d5Ql5zZKiQGTslfXD3IQNyg2J3Sll9RYU16xVIp4kmA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795229419; 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=q8hc2BbtAIxr9fjlfzYHrBagNpHuX7NGKh07YtC74C4=; b=zwGr3SSt1z9MDNBkTQ1nvKDjkn7o06U8Ro1znMMq1MO5gMyI26gGlZh/QWKq4Du71d/m /91/B4Lp5RXYVqxjEisb1RMOMoHpSV+GbB7VD6Vd5OnLgVFLXYtlj8MYun31eFeleX6GC 5mGZAj4UUdG3XS7c8fuaSP0a+RC9p/Lljp8mo19ac8oEAhPcNIRbLAZ+zhbYgLrcKmmnZ 7YpHEmzaHZ/XsRE8zWS6e9fe52eqy43bsZ+YASAX2XSTQY3OX008v5EIuBb16RdC88/H7 a4NyBo7r22Sw6IrrsCW25JEpoYIsYyjrgTLYC/Czr77y4hbYXCDPMn+jtzqavXsgerg== 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=NmY7EOi2; arc=none smtp.remote-ip=209.85.128.198 Received: from mail-yw1-f198.google.com (mail-yw1-f198.google.com [209.85.128.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 6ABDB60A2600 for ; Sat, 21 Nov 2026 02:50:16 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 6ABDB60A2600 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=NmY7EOi2 Received: by mail-yw1-f198.google.com with SMTP id 00721157ae682-8b3ad09ad82so22673787b3.3 for ; Fri, 20 Nov 2026 18:50:16 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795229415; x=1795834215; 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=q8hc2BbtAIxr9fjlfzYHrBagNpHuX7NGKh07YtC74C4=; b=NmY7EOi2EroSpQ4vJOYK6jQvBMTSJfavatQiHBGr++DgHzOkCeehahO/jiA6ruBWDe yzPaa19jw9PPZ2smk0EHlFDXPKjeG+0yTnYg1U8yv7bD6+wUonxIYrs3ck2ISarh5Bup lizIg389oyLzIk7utRzGduhCZr/eEZKWvxwIXYTjb6zkq36zsEseJt9TZNoIbQsYWcka +nbuujwUjcikOQzNNf/+08RFGOZf6crUdW+iVVaBEEYstAhK8Or6AJihdvldsdhmnZlA XqPsJq++VaSjuOYqAMiERH/Le8LtDNwXpWfh5v/cQhZ2UNlPBwlFKrwttPBFGA3cAwJx KbPA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795229415; x=1795834215; 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=q8hc2BbtAIxr9fjlfzYHrBagNpHuX7NGKh07YtC74C4=; b=MHVwifIIznYq22oyx0OChwcShWuPnS/O1ztcrRsonUacx5W/iHAyMfYbPeAXcAkj3P FxhWWocNzrjQS5NiLxywNm6lrC7YxlMyR8q8AN8mSLfEd2SYOyx/qbTtEC2bVWxiba4a nOJn4dEbhNBkMfU06wEwRvekZBVhDy7kdZXdGOXIRiiMxLZDKIBV0JL9wcOeF+SHzL3B zzC515Hk96CH9Z8DXJuGBCg1wqgtVJVhFd75uFX4g2H9N6yGlibA2JMPMPPclaWxBmRj Z2nwlwYk+JKMLEV9gtbqr4p2A2+4w82UrxQOWL/0/YvWhUXdXG+bzSx7bcgcAiyfn29f 8aLQ== X-Forwarded-Encrypted: i=1; AL+hErG5GxqUTFPdiYRhm8RM35oiUCPmdfo+HVWbOKF76sLsIlx7lkNF1Xv3fQ3UK8SOZ7cB0YTJt+k2121sYik=@vger.kernel.org X-Gm-Message-State: APuU4Z86nw8CkCNoMMTMMVmTl9UP58qsWzbKfSs/agNDfjIYkPsENoHS RLFFxY+Hf3pCO62JLdk2rde5OSCuT9cquhOCoLovCM9lvIp2bG0Ct5n44MqIkQ3Uc3z0Z+6dUU8 oKxdKNV79L1gnv+j3f5KSt1LCp+7b X-Received: from ywkk1-n1.prod.google.com ([2002:a05:690c:a0a1:10b0:8b5:1ca:fc48]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:690c:680e:b0:8b4:dc54:1d37 with SMTP id 00721157ae682-8b52042e7d0mr22956797b3.19.1795229414968; Fri, 20 Nov 2026 18:50:14 -0800 (PST) Date: Fri, 20 Nov 2026 21:50:03 -0500 In-Reply-To: <20261121025007.3445723-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: <20261121025007.3445723-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261121025007.3445723-3-briandaniels@google.com> Subject: [PATCH v12 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 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:50:25 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.128.197 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795229426; b=s+FW/XXE2fPxJuWrteeNlvD84S7kedkEqyWnbajyLxsfDrTEPQ2Na72RXWwdX6xt3qrR JQjxWjoKo4s5iGIZ0fDt1VvGJNosj6G9J0nSTr22r6B9q/jg58wlO/EYHDX1uYR/NGajR oRXcQjrr5+5/rFy/dGKtATNczBRAAlCOzj/74CVdhHOkpbkwvnGjjAWSGQ2ZxFm20ovfa cofuWNnu83Vk2kCP7AvAuPMCbQ5Z5zU9VnBz0fvoNatZlQW0mJfsDqXtNUCrdujiegySq te+8NIxYmV//RdzA29I3EOpXZL8XDN2ZKBa+gTnst1g49nBEHFnyAUzMaSMQi1yYAwg== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795229426; 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=AeIehshobaBW7sJsqwLTRISjsy3SdPFV2HokrUS9HfU=; b=wZLq9oK1t+l1rXRLulZ3QfbcPnh9Jf7xLE1EOOPcUy+AnSuYH6n9FdLo3KlFKw/c8fqA MvU7Y1x8Yn3pZ46/WNu0Ns9fUf+PW/MBx4pgcwhgLuNtM8ouy7FvO743sIf8k4cvpeaxE nXM2jm3OR3jk6+NGjQ8bC16j/6SIP3NnbtmjeYykTjI7rqjmDXQGua0N24qVsq0VWiAof i3FrnqlIX7ta+BlX+X+I/tKhrGpXdKv6KlWF/pkbTacseSVzV5EwFZWOWNMuPifDkR2DZ 9tqzuh7SJJlpOTAD+zJlRDGrvLzp3D+JBChi9tJLB2Ex6M/MV7+oOLbNDs6PthxBYoQ== 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=bBqdHv22; arc=none smtp.remote-ip=209.85.128.197 Received: from mail-yw1-f197.google.com (mail-yw1-f197.google.com [209.85.128.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 358C4606A6B6 for ; Sat, 21 Nov 2026 02:50:18 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 358C4606A6B6 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=bBqdHv22 Received: by mail-yw1-f197.google.com with SMTP id 00721157ae682-8b3ad0823c3so26389877b3.2 for ; Fri, 20 Nov 2026 18:50:18 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795229417; x=1795834217; 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=AeIehshobaBW7sJsqwLTRISjsy3SdPFV2HokrUS9HfU=; b=bBqdHv22a9BCXcSU8MQpHGyx4ONjrCQyXDPFrE87rZcToBrL8Cxikb4e/gJuukx5Sl zBqbD/BFWxrcfMOmuBofuabEMhbjnkw9ga5vgDxvJkQppZZ/fo1vnKV0P+JmId01J4cd ny6FtmuvlbA1m26aDbCUKSYiO4+yGARRFssaONFOBxRJ84o6TlICryWkgMiWmNf9Wj3k ueyDq7EnGqPGw49iSJATd4wWLR2LT3dNhzOeTEIWCkXJ9yegjAWcAyXvcO78NI5twBsh dd+x4PddnGiZgrVgoRqjUoeYqNTqEvojM3/DuxWDbjVrEhELZ87gjHhATQEk3ykePsWx ALbg== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795229417; x=1795834217; 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=AeIehshobaBW7sJsqwLTRISjsy3SdPFV2HokrUS9HfU=; b=Gvl1074PnsHGVZw5SvS+33EM/liDta9sE3zylyX/V6/z8HNiu4fzosqGndXEO8ek3n /vI2WpGWmvxHl7c4IGTvy+t5FaU61k9B3LFR3vXAO2NW8wenUA0/Y/GHmO8qOqzLKmE5 x3NpIgQBzJBsxz5at2c2v9T+FG8GXcRz+G1NszWp4bjs3CTAehtSd9TOtHaGjYP/uV0P DKHhC2+XQdgn1vJMH+ioV/mFLu6zpzuUhcKpbAkWP6o7ubt9kELyLm/MsfVm3fP5i7Cv DxRwoMfLT3jmMYW2bw2RzWg3BlU1Ihz9XRYVHgRTRe/7k6Bd/1YP0AodYHNZA/ujGrLz HzUg== X-Forwarded-Encrypted: i=1; AL+hErFjwVkRN8nrotszB4Z/eANCeEiLqc9kJCG4sB3S7bhmbAP/dBaSBDeg7DzwvQwFJqjvXw6PCVATqhw7hzM=@vger.kernel.org X-Gm-Message-State: APuU4Z+YlBASnF5f12d8nyZYGU98BIcn97wTc5TL05IEy3hNTx+/2go0 uWQN9eU7bFuKFHaSgUO6XTql6HufkIT6DUksEcQp3JGwKptoiTS1mw22iDaMsjtqZJJqS6UEI/v nkjFKD9JsikLKexsnVOHAA6BJNwr5 X-Received: from ywbme24-n2.prod.google.com ([2002:a05:690c:8698:20b0:8b4:fbc6:1835]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:690c:4a06:b0:8b4:d66a:2002 with SMTP id 00721157ae682-8b520515e7fmr23275967b3.65.1795229416758; Fri, 20 Nov 2026 18:50:16 -0800 (PST) Date: Fri, 20 Nov 2026 21:50:04 -0500 In-Reply-To: <20261121025007.3445723-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: <20261121025007.3445723-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261121025007.3445723-4-briandaniels@google.com> Subject: [PATCH v12 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 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..631c7b13c 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, false); + 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, true); + } + + 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:50:25 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.160.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795229426; b=zv4Upt92xeXn+/b8gjBD9WewC3bA3jyZSl/M1RCX1IrSQhBqVUzb0ysuv1o7DZM4FTlH GL80svnJptbn7EZkBO7/LBkA5HMMAaU3RfayHZjI5vNCHPrwWyqCMWchdk+kxzKcbWQTH zkVjrRJsf7+yzktpI6jrbYpY0B8gXre44IbMe281o+Ra18eXrmFaWG7EtJYmxkPHB8jDo SUIo0cjqBHk6uIDtYZFpS6PcC6Z0NkofvVk1GEr+TL+DDPlbYA4eUIKV7f4XWN04prDKJ Vgkh7xQ3JJp7Lg6uxrpRGwpsaADuRc1SP/enlqmWkk8fyiG+Yh6kWvsmM7n193sMvQw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795229426; 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=MrmFpeLJ/38ckjhm/RtP/AIZC3X17uQZsfKeEHaVR4s=; b=qLqCmv6ooZgFkt+baaf6jrWSulXsAanSi4Wqn4dTbTNCiet0fOVpoYY0Hh83iTwaGQFv qhkxU/UHC/YlUgZH2HOPtfjcTU+Mqg+RmdsGzIKBAzvvSV/jsJNdCKDcs+fmA+8I4hHak dURSB4OlsVJJYW5Rz2+ooMnT3+/D0A4C3T/mMpva7zk35CpcEw3dO9DU1L9bETiwW2fke khmOJsZojs7PzlHbmIXlN3lggbo5CuVFF77VCJPm+G497K55UL7+agJaEinvNFp17PKeZ VTikssYzIN0TfH5n94PU4w2P2ajSxUvTyx7QvkwnGIvYJCotfPHtywX91Q7GNtHdEBg== 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=nOl3nVUt; arc=none smtp.remote-ip=209.85.160.199 Received: from mail-qt1-f199.google.com (mail-qt1-f199.google.com [209.85.160.199]) (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 360D0606A68E for ; Sat, 21 Nov 2026 02:50:20 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 360D0606A68E 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=nOl3nVUt Received: by mail-qt1-f199.google.com with SMTP id d75a77b69052e-5363b06bcb2so30574761cf.2 for ; Fri, 20 Nov 2026 18:50:20 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795229419; x=1795834219; 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=MrmFpeLJ/38ckjhm/RtP/AIZC3X17uQZsfKeEHaVR4s=; b=nOl3nVUtvbx9UsnK+IqYQvacLql4PqI8xCydglM2pHC+7/cYlrSdkcWTaaeNEOFC8j +YNF44TqGgDZ87UhVIUr/Z5SQU3wTCz81NGBc6YBYACXigNioqp3eYFDBqm/qM/s6lE0 4wSwmEnNzibN4qlOqQfzGcdbxIkitd5dFrAup62SxotZcLZ1ZohnY7CpM/FWYbn1bWgN AXEU7J9S5YLf397FlECbNJpko/Q8/T02GLxEfTQugoXJC5qx4opE2/Vifjx93B3bsKf3 uOcXfSQ3PYii5cCojJ/Kw1lJhHwPRVgT5lv+XUV+fJifAvQVjyz8vhOEvhv4ZLTaTUcn bpqA== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795229419; x=1795834219; 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=MrmFpeLJ/38ckjhm/RtP/AIZC3X17uQZsfKeEHaVR4s=; b=k4fCo48HcqEOusDo9O8OhDD2xftJar46xhumlfI6graL/SlXozmWNQ+pf2TS609uP7 2Z5QzG0bvPeKZ8lxPg9AbzzuRA3zxcLQL2C71mOFbFIOSIyOBmZizwANFRmTWhzvH85d sRhnakEPuO+xYyyCepXgX630s5UMKoY25McJN5T2fCSf93Nd7wcNNZ+iWYeXSBuuktzd /eeo6mR6jiFbBCXp5+fiysvu4uD4Fwv900fAulDxSmg/7r8pO5woUmL8/Sou+P5dDT2R vYK/8VH1p3Sm5tvrk66zX6Pe5cEsbB0t9iCTk7fptYYpgplNk7tY9oXeANCaCcrZDXo/ xCZA== X-Forwarded-Encrypted: i=1; AL+hErHHTa0X940n7l00Q6AF+Vur/IGCvmvsU6eJcvWTgU9c7UwOGQtNU43oiP2d6D90I5CgAu/AlS/D1T2SJYQ=@vger.kernel.org X-Gm-Message-State: APuU4Z+/UuuW84X6TtQ/S2HxI1cZMTuLKktCX4gN4Iijc8n+XhGTxHOD RQRq38yOwBLEQhM2FAO8v6dREdCL9SGPr5Ya1k/6gG0Mxxy9J3kwjbVnnpCYKP+3ih9/OGjst5U W0KJ6p1owvici/PDEXcS5Df6TpmA1 X-Received: from qvbqh10.prod.google.com ([2002:a05:6214:4c0a:b0:920:f933:ca92]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:622a:c0a:b0:55d:32b0:69d3 with SMTP id d75a77b69052e-55d76aa5797mr84989231cf.30.1795229418812; Fri, 20 Nov 2026 18:50:18 -0800 (PST) Date: Fri, 20 Nov 2026 21:50:05 -0500 In-Reply-To: <20261121025007.3445723-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: <20261121025007.3445723-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261121025007.3445723-5-briandaniels@google.com> Subject: [PATCH v12 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 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 631c7b13c..f01df04cd 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:50:25 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.219.69 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795229424; b=DYG99bFbw5CTx5+JqRG+QshhR5xM2nm3pT73gwa447X8mMaXTKiGqykc99BRDEsYdi8Q 4RodC5uJoO7aRf2VD5SQY4QaSNsQbpFClLEXZGuLYqUcQfNj2QbpMgjPyoqs2litKlR3V hRWcnoEBpZIBDNQzWBfEE91xFKL10RmpxLuTS2ut/YuMXpmDXdizccrA+RLjPlR3xT2/g FYAucvdjdKaz1UPsRwY8aBlIObMzPSlZdq/2wEOXq0lmeuy0EGFgOy8AZu8+XSSuvbFwK Fo/qBU7r6YXgFKMdkgwAFOp4HhFvLpHOyoJSZHOrk51udv07pgU516OdfliSD2wpjvA== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795229424; 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=Qno4z6wJ+6Pj/3ZsgyReuilsORsK31+sE01I7rt/N6s=; b=GRo3IdGE817lmZNq4m1FmIA+JeerLSDTqS+epts0uEpyEGpvSvy8W9aJTQafNjSrUzKR AmAiC7O6Y7J7uBDdycGz2RzlhbAos0cQzSfAJ9p9ThmA/R4Qo9A25W0oN+hvq5qxtmQjU R27BHw6oq3bYBEp6o89nHdRwXQa6NWPRfEpDappEYdoGBsqCdDN5xjvEuyTmZvyiIVwAt OvtwW3UEVPQSyTmmpNUW5tnDPfgokK+s0pIFqBQkECOlJ07ZLlhre84IyJGzw1LLBARaa BYm8oes4mYdSeBFqP/cVztGPu3+LUjN+ZW0SwYuQDoZWSMQECScksOC+bm8FkN6zRog== 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=JFX3oitR; arc=none smtp.remote-ip=209.85.219.69 Received: from mail-qv1-f69.google.com (mail-qv1-f69.google.com [209.85.219.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 2545F60A3801 for ; Sat, 21 Nov 2026 02:50:22 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 2545F60A3801 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=JFX3oitR Received: by mail-qv1-f69.google.com with SMTP id 6a1803df08f44-9210357af78so41780016d6.1 for ; Fri, 20 Nov 2026 18:50:22 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795229421; x=1795834221; 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=Qno4z6wJ+6Pj/3ZsgyReuilsORsK31+sE01I7rt/N6s=; b=JFX3oitRvJaGpTGrxhUuhqnPlD4UmqgBeIaKIJKhmHyXKFysF5DDjVEE/QjnlnI+U9 cDf2C0YDye7KVxyCgO8PePsYUHNogb8GZ3ydk+JwLuVQ/VeeGGlEGu/yqAcSXS+fZ1QR 7yUb3BBhvA4xyW9FrQt9Oc3/v+TjqeBMNy5LfmJiQ3bFqZg8laDFA6+bJ9M5VsZ3RBt0 xfMX2p08U5Bm0Bj0rQ2feIh+OhdkYxUuVY0avd0UXJ+XQykiHB7XUR6uuA5ROkI7HeqD TwByvcyB0ERf0A6kYbOCvYsPiasfOd9IKjVTw7SqvOOcb9I18+4XNlg6krpAJyoDkFeo AafQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795229421; x=1795834221; 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=Qno4z6wJ+6Pj/3ZsgyReuilsORsK31+sE01I7rt/N6s=; b=TK4PwINqR+C3gBPMsidVjpt+9EMCwMyglsq4ByNfqkJK9Lw3ulxJPr5+ZJk/M3F6Dp grLwTLVN0Ry0SVxski7JO7NXtLAz+gvOB6eTxt8P5+zq1DREmFXmerG0kpB9hAsJ737F Iizw52ugLscHkNi1ZqWvy8tPTghRhlRpUST7FPS5UWM/XmYwd1GlhllaBBHh7ZdDMFOW LGgCz16pD2AmLlxN+gXXNnJYU38rbbVkrc+N844Sf2fbGlpXlZCl3lrrj502B5trv7if APxBHW2ekP1HvEKjsTnKrGUZox966HsBQstP5OXBZ4zRRedOigetOjYA6YtUIHAfGwys KGAw== X-Forwarded-Encrypted: i=1; AL+hErHM+MkMhvQE8RWSH6T+9dRiZGx7GwsdXRr94KPnUQbdL0b9jo7kxcleye/Cv4hGJsVokXskBHSqL0g42V0=@vger.kernel.org X-Gm-Message-State: APuU4Z9vT40+MxcannUn38xtGfCHhos3E2NfXE7/pySDjofGIkw2yYXg tXdsvLpGH/Q91jgZ6pz/fm+qhMHD89QCmCNemIzMYW3Y42oGeGBNhUlKBO2v9jW54eBFeJGile9 vh+4DzDCt+b7kxkeP+50GZXOwlVbn X-Received: from qvbld13.prod.google.com ([2002:a05:6214:418d:b0:91e:cc05:97dd]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:6214:29e8:b0:921:21ee:1643 with SMTP id 6a1803df08f44-92134771510mr82859566d6.0.1795229420832; Fri, 20 Nov 2026 18:50:20 -0800 (PST) Date: Fri, 20 Nov 2026 21:50:06 -0500 In-Reply-To: <20261121025007.3445723-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: <20261121025007.3445723-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261121025007.3445723-6-briandaniels@google.com> Subject: [PATCH v12 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 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:50:25 2026 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.128.199 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1795229425; b=AVrwikr++EpPQ/CftvkV0h2oqToOWU4YtnPWSyrm+s5226d/bGBZj1upTgprVsi1Qfgk E+hVJqoPLJAKWW0q4Zsqe8SmU/6L4BbnzCRAY/IIRcPe8KWRxkVOI6VyKUKlECQJ+d48r RcLmXyVzSbzg61bNHsH1XMu9NsL5+8eP0M8VOT6EHWLBxqkmraB6YdURS1xeHFunSvD+1 sdYQU83KOvRj41HgIdj0vVJNcze9Ic1EAJBSDs3k/Kv57CfeIqlTNucuxLzB6MRlbvmkO XH40SVFwyAv+BLJTakNykBLKs/6nTpdZlr3zuFxEL9XH/B4nR1FXgN96yW5nmZtb0tw== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1795229425; 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=DKXb3XP5512p3dJHGo2KoBBF7YTIyEsZxlx/DyWyIB8=; b=oF0sUzGkpHpwioQtH7ZiNEaW9YPIXqpYHH2YPKyxE0QDqCB3jRiYYPB7iaS0ZBYaS6L7 9eXdTs9icNA9+jm3CoEnZQxhSK+FbNqa5MRiYNIGMZBFbDUgdZS5ZadJPNdRuzYq5EF+2 2fWI8yJBo2Vz/hkC0QpfpNjD/Roonfj+i01pHXQIs6kLoBeDWuakNEZ8fxVikoyZwLLW3 zwPriF+CEQ5avxMjwpbc9eSxot8PRlqTx32UH4hKrtKoIqLaHDRp4jVCTD7iVn3pdA1C5 t7ayD/CkfC6ove4u3AOGBYUSY1WDySVL6wTt2DYURH0x32FifOC0xyu9FKZhhLfD7rw== 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=n595g1o+; arc=none smtp.remote-ip=209.85.128.199 Received: from mail-yw1-f199.google.com (mail-yw1-f199.google.com [209.85.128.199]) (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 0F46260A2607 for ; Sat, 21 Nov 2026 02:50:23 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org 0F46260A2607 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=n595g1o+ Received: by mail-yw1-f199.google.com with SMTP id 00721157ae682-8b4d9d2e261so25960037b3.0 for ; Fri, 20 Nov 2026 18:50:23 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=google.com; s=20260707; t=1795229423; x=1795834223; 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=DKXb3XP5512p3dJHGo2KoBBF7YTIyEsZxlx/DyWyIB8=; b=n595g1o+Ws9OCWESRJo9DQ080tYkjD8AvEja2lJmeWN0UVnCdcva6KNYXPt5jwUO3R llkL8/sOGi0V5HAOEcN8+bMu2Yrm2qu5SoFix3LoNNoY9Pr8Wtjoc3Bk4/iNv5IwTODz 2DjJTlHsjSOj5wfyKlRpyJpXK9WDRLUihSbK53GlmgI6ZNUhKbrzKOk1j2SDgrzZ7Fek 3vjmQv5QLG1dB8qokK9Lug3K8hjc6tORk5iY7B+hUy8lSGNrfWSfEYLRpB4WeyqBA9tN A0Px6VHsuC58GTuAjv3xVp/duBvxUcq+SQQK2KMnmE7TJBkX3ge8S5e7MtlIj2ivVuPE Y+VQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1795229423; x=1795834223; 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=DKXb3XP5512p3dJHGo2KoBBF7YTIyEsZxlx/DyWyIB8=; b=KsFT43e4KzbUpkCKCP0WHo2dyJHvUJeGo5myPrU3Aapgwa8xZubxJWkE5HyFMze3s3 OrFlI/KcKy0xvuaQNl6d8IJn7uaKjGkkMHamaz/g7tYDrK02cVXAr9KCA77rvOLCf9xu pB3AaNt/hwpx4LccetpPyqZomAw1erSCx09VtPHVOw39J5+rGlOpzYh4v0IhHQzlhB2c Y42Tu23BBXKMwDVFrdS4T+w2C/onbWcwowFrtyJoZojB7es6x+wUCARoO9Gi3lvF+GCv BJEoC1RvEDgoE45gVlSonw5kHD1+55KKnfaSI405o49xo0kfMC6E3BHMC5kHKwY4nJbp epKg== X-Forwarded-Encrypted: i=1; AL+hErE3vxY7NwWKQaNz7oPuNtWoj+XqFDrAoSP70boi2/Q8l0V7E6GjIyI7pZDkG19Ome1K6ilcky9zIQzrI34=@vger.kernel.org X-Gm-Message-State: APuU4Z+hQKOaX8b3I7kSFV4Cyk0kHnHfRY/O9oHjBeejdXAZEpjD3E3P DgIHlkTTYUsZ4xBxI3Zs0QarhDuXBtoxLeeiQ3zBS5Yzy2mfRhl/IBZ8eN5vdDcfvDyHybyJMk/ ErU9SfDRcZTprBN+rAm//YfRd0d6V X-Received: from yxvc11.prod.google.com ([2002:a53:ef0b:0:b0:67d:aba9:9204]) (user=briandaniels job=prod-delivery.src-stubby-dispatcher) by 2002:a05:690e:43cc:20b0:67d:baf9:116b with SMTP id 956f58d0204a3-67df42c4555mr1179076d50.9.1795229422929; Fri, 20 Nov 2026 18:50:22 -0800 (PST) Date: Fri, 20 Nov 2026 21:50:07 -0500 In-Reply-To: <20261121025007.3445723-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: <20261121025007.3445723-1-briandaniels@google.com> X-Mailer: git-send-email 2.56.1.750.gf70dc682cf-goog Message-ID: <20261121025007.3445723-7-briandaniels@google.com> Subject: [PATCH v12 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 , Brian Daniels 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/ Signed-off-by: Nick Rogers Signed-off-by: Brian Daniels --- 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