Files
unkernel/kernel/patches/linux/wasm-kwcam-a-V4L2-camera-fed-by-the-JavaScript-host.patch
Pooya Parsa 1b229902b2 Add a guest microphone and camera: kwsnd capture, kwcam (V4L2, raw and host-encoded H.264), and camera frames named to the kwva encoder
Microphone: kwsnd gains a capture substream fed by the host (SDK option
soundIn, the page's Microphone setting and ?mic=0, the CLI's
--sound-in-wav and --sound-in).

Camera: kwcam is a V4L2 capture device (/dev/video0) fed by the host: I420,
NV12 and YUYV at 320x240 to 1280x720, and H.264 encoded by the host's
WebCodecs encoder where it has one, with bitrate, GOP and key frame
controls (SDK option camera, the page's Camera setting and ?cam=0, the
CLI's --camera). The base's rc writes the udev database entry of
/dev/video*, so programs that list cameras through libudev find it.

kwva (protocol 5): an encode whose input surface is a camera buffer's
dma-buf names the frame to the host instead of sending its pixels, and
pixels an app writes into an exported surface reach the host (put).
2026-11-29 10:23:01 +00:00

1215 lines
43 KiB
Diff

From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Pooya Parsa <pooya@pi0.io>
Date: Sun, 29 Nov 2026 00:05:24 +0000
Subject: [PATCH] wasm: kwcam, a V4L2 camera fed by the JavaScript host
A V4L2 capture device for programs that use a camera (v4l2-ctl, ffmpeg,
GStreamer, browsers), registered only when the host has one
(wasm_driver_camera_init() < 0 means none, so a normal boot only pays
for the code). With a camera it is /dev/video0, driver "kwcam": YUV420
(I420), NV12 and YUYV (single plane), and H.264 where the host encodes
it (the init's answer has a bit per compressed format, KWCAM_INIT_H264;
a host without it gets the raw formats only), in that order, YUV420
first and the default (players take planar 4:2:0 as is, and ffmpeg's
v4l2 input tries it first); 320x240, 640x480 and 1280x720, at 30, 25,
20, 15, 10 or 5 frames a second, all discrete (ENUM_FMT, ENUM_FRAMESIZES,
ENUM_FRAMEINTERVALS, G/S_PARM), one camera input. The colorimetry is what
webcams report: sRGB primaries and transfer, BT.601 encoding, limited
range. Controls only with H.264: the codec class's bitrate and GOP size
(following the size and rate, about 0.1 bit a pixel and a key frame a
second, until a program sets them) and the key frame button.
Buffers are videobuf2-dma-contig on a platform device "kwcam" with a
32-bit DMA mask: dma-direct gives contiguous direct-mapped pages, which
the host writes at their linear address and mmap maps with
remap_pfn_range(). videobuf2-vmalloc cannot be mapped here: with
VMALLOC_FLAT vmalloc_user() is a large kmalloc, whose head page
vm_insert_page() refuses. MMAP, read() and DMABUF work, and EXPBUF
exports a buffer as a dma-buf. At most 32 buffers, as uvcvideo (GStreamer's
v4l2src io-mode=dmabuf into a VA encoder holds 17 or more); REQBUFS gives
two at least.
The host is told nothing until STREAMON, when
wasm_driver_camera_stream(fourcc, width, height, 1, fps, bitrate, gop)
starts its camera with the negotiated format, size and frame interval
(and for H.264 the controls); STREAMOFF, or closing the file that
streams, sends it again with fourcc 0, so the host can let its camera
go.
While streaming an hrtimer on CLOCK_MONOTONIC (the host's monotonic
clock) ticks at the frame interval. Each tick takes the oldest queued
buffer, asks wasm_driver_camera_frame(buf, bytes, id, NULL) for the
host's current frame (the host writes it during the call and returns
bytes, or 0 when it has none, and may write its 16-byte id of the frame
at id), fills a black frame (Y 16, Cb and Cr 128) where it had none, and
completes the buffer with the tick's monotonic time and the
next sequence number. So a program gets frames at the rate it asked for
from the start, black ones until the host has a picture (a camera the
user has not allowed yet), and never waits for the host. A tick with no
buffer queued drops its frame (the sequence number counts it); a late
tick delivers one frame and skips the ones it missed. There is no
interrupt, and no import suspends.
H.264 is the stream of a camera that encodes (a UVC camera with its own
encoder): the guest copies it. bytesperline is 0 and sizeimage the
frame's size as NV12. Each frame import takes the host's next chunk (an
Annex B access unit; a key frame with SPS and PPS first and after any
chunk the host dropped), in order and once: the host returns its size,
or 0 when it has none yet, and the buffer then stays queued; nothing is
duplicated, reordered or filled in. The fourth argument, a struct
kwcam_chunk, says whether the chunk is a key frame and how long ago its
frame was captured, and tells the host the controls and a key frame
asked for. The timer ticks four times a frame interval (4 ms at least),
each tick delivering what the host has while buffers are queued (eight
at most), and a buffer's timestamp is the capture time (the tick's less
the chunk's age, up to 10 s), kept increasing. Sequence numbers count
the chunks; buffers get V4L2_BUF_FLAG_KEYFRAME or PFRAME, and no frame
id.
Frame ids (include/uapi/linux/kwcam.h): the host's id of each frame
(128 random bits; zero for a black frame) stays with the buffer.
KWCAM_IOC_FRAME, on any open of the device, takes a dma-buf exported
from one of its MMAP buffers and returns the buffer's index, its frame's
id and sequence number, the stream's format, size and pitch, and whether
user space holds the buffer (dequeued) and whether it is mapped writable
anywhere, so a consumer the host also serves (the guest's VA-API driver)
can name the frame to the host instead of sending its pixels (a
compressed stream's buffers are refused). For the
last, the memory ops are videobuf2-dma-contig's with alloc, put, mmap and
get_dmabuf wrapped: a writable mapping, through V4L2 mmap or an exported
dma-buf (whose ops become a copy of vb2-dc's with mmap wrapped, which is
also how the ioctl recognises the device's dma-bufs), marks the buffer
for as long as it lives; a read-only mapping loses VM_MAYWRITE.
The driver selects VIDEO_DEV and VIDEOBUF2_DMA_CONTIG itself, so it
needs none of the media filter's categories, and so no media controller.
On the lowered kernel the driver with the V4L2 core and videobuf2 adds
241 KB (83 KB with gzip -9) and three imports; H.264 and its controls 2.4
KB of it (1.1 KB with gzip -9).
On SMP the host's imports answer on CPU 0 alone: STREAMON and STREAMOFF
send the stream call and start or cancel the timer through
kw_host_call(), so the timer is pinned to CPU 0 and its frame imports
are made there.
---
drivers/media/Kconfig | 13 +
drivers/media/platform/Makefile | 1 +
drivers/media/platform/kwcam.c | 1023 +++++++++++++++++++++++++++++++
include/uapi/linux/kwcam.h | 46 ++
4 files changed, 1083 insertions(+)
create mode 100644 drivers/media/platform/kwcam.c
create mode 100644 include/uapi/linux/kwcam.h
diff --git a/drivers/media/Kconfig b/drivers/media/Kconfig
--- a/drivers/media/Kconfig
+++ b/drivers/media/Kconfig
@@ -236,6 +236,19 @@ endif
source "drivers/media/firewire/Kconfig"
+config VIDEO_KWCAM
+ tristate "unkernel host camera"
+ depends on WASM && HAS_DMA && (I2C || I2C=n)
+ select VIDEO_DEV
+ select VIDEOBUF2_DMA_CONTIG
+ help
+ A V4L2 capture device (/dev/video0) whose frames come from the
+ JavaScript host of a unkernel instance (js/core/camera.ts): YUYV
+ and NV12 up to 1280x720 at 30 frames a second. The device is
+ registered only when the host has a camera. It selects the V4L2
+ core itself, so no media category of the filter (and so no media
+ controller) is needed. The driver is drivers/media/platform/kwcam.c.
+
# Common driver options
source "drivers/media/common/Kconfig"
diff --git a/drivers/media/platform/Makefile b/drivers/media/platform/Makefile
--- a/drivers/media/platform/Makefile
+++ b/drivers/media/platform/Makefile
@@ -40,5 +40,6 @@ obj-y += xilinx/
# Please place here only ancillary drivers that aren't SoC-specific
# Please keep it alphabetically sorted by Kconfig name
# (e. g. LC_ALL=C sort Makefile)
+obj-$(CONFIG_VIDEO_KWCAM) += kwcam.o
obj-$(CONFIG_VIDEO_MEM2MEM_DEINTERLACE) += m2m-deinterlace.o
obj-$(CONFIG_VIDEO_MUX) += video-mux.o
diff --git a/drivers/media/platform/kwcam.c b/drivers/media/platform/kwcam.c
new file mode 100644
--- /dev/null
+++ b/drivers/media/platform/kwcam.c
@@ -0,0 +1,1023 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * kwcam: a V4L2 camera fed by the JavaScript host (unkernel).
+ *
+ * One capture device, /dev/video0, registered only when the host has a
+ * camera (wasm_driver_camera_init() < 0 means none).
+ * Formats YUV420 (I420), NV12 and YUYV (single plane), and H.264 where the
+ * host encodes it (the init's KWCAM_INIT_H264 bit), 320x240, 640x480 and
+ * 1280x720, at 5 to
+ * 30 frames a second (discrete sizes and intervals, so ENUM_FMT,
+ * ENUM_FRAMESIZES, ENUM_FRAMEINTERVALS, G/S_PARM), one input. Controls
+ * only with H.264: the codec class's bitrate, GOP size and key frame
+ * button, passed to the host (below).
+ * Buffers are videobuf2-dma-contig: dma-direct gives contiguous
+ * direct-mapped pages, which the host writes at their linear address and
+ * mmap maps with remap_pfn_range(). (videobuf2-vmalloc cannot be mmapped
+ * here: with VMALLOC_FLAT vmalloc_user() is a large kmalloc, whose pages
+ * vm_insert_page() refuses.) MMAP, read() and DMABUF; EXPBUF exports a
+ * buffer as a dma-buf.
+ *
+ * The host is told nothing and nothing runs until STREAMON:
+ * wasm_driver_camera_stream(fourcc, width, height, num, den) starts the
+ * host's camera with the negotiated format, size and frame interval
+ * (num/den seconds), and the same call with fourcc 0 stops it at
+ * STREAMOFF or when the streaming file is closed, so the host can release
+ * its camera (and its indicator goes off).
+ *
+ * While streaming, an hrtimer on CLOCK_MONOTONIC (the host's monotonic
+ * clock) ticks at the frame interval. Each tick takes the oldest queued
+ * buffer, asks the host to write its current frame into it with
+ * wasm_driver_camera_frame(buf, bytes) (the host copies during the call
+ * and returns @bytes, or 0 when it has no frame: a camera not granted yet,
+ * or not started), fills a black frame where it had none, and completes
+ * the buffer with the tick's time and the next sequence number. So a
+ * program always gets frames at the rate it asked for, black ones until
+ * the host has a picture, and never waits for the host. A tick with no
+ * buffer queued drops its frame (the sequence number still counts it); a
+ * late tick delivers one frame and skips the missed ones. There is no
+ * interrupt: the host only answers imports, none of which suspends.
+ *
+ * H.264 (compressed): the host encodes, the guest copies the stream, as
+ * from a UVC camera that encodes. Each frame import then takes the host's
+ * next chunk of the stream (Annex B, one access unit; the first after a
+ * start, and after any chunk the host dropped, a key frame with SPS and
+ * PPS), in order, each once; the host returns its size, or 0 when it has
+ * none yet, and the buffer then stays queued for a later tick: nothing is
+ * duplicated, reordered or filled in. The fourth argument, struct
+ * kwcam_chunk, says whether the chunk is a key frame and how long ago its
+ * frame was captured, and tells the host the controls' bitrate and GOP
+ * size and a key frame asked for. Ticks come four times a frame interval
+ * (4 ms at least), each delivering every chunk the host has while buffers
+ * are queued (up to KWCAM_CHUNKS_PER_TICK), so a chunk waits a quarter of
+ * an interval at most for a queued buffer; its timestamp is the tick's
+ * time less the chunk's age (the capture time, up to KWCAM_AGE_MAX_US
+ * back), kept increasing. Sequence numbers count the chunks delivered. Buffers
+ * get V4L2_BUF_FLAG_KEYFRAME or PFRAME (no B-frames: the host encodes for
+ * real time), no frame id, and KWCAM_IOC_FRAME refuses them.
+ *
+ * Frame ids (uapi/linux/kwcam.h): with a frame the host also writes its id
+ * of it (128 random bits; zero, as for a black frame, where it keeps none),
+ * kept with the buffer. KWCAM_IOC_FRAME takes a dma-buf exported from a
+ * buffer and says which buffer it is, its frame's id, and whether user
+ * space holds it (dequeued) and whether it is mapped writable, so a
+ * consumer the host also serves (the VA-API driver) can name the frame to
+ * the host instead of sending its pixels: an id names exactly the pixels
+ * the host wrote into that buffer, as long as the buffer is dequeued and
+ * nothing could write it. For the last, the memory ops are
+ * videobuf2-dma-contig's with mmap wrapped (V4L2 mmap, and the dma-buf
+ * ops of every exported buffer): a writable mapping marks the buffer for
+ * as long as it exists, a read-only one loses VM_MAYWRITE (no mprotect to
+ * writable later). A dma-buf is the device's when its ops are kwcam's.
+ *
+ * SMP: the host's imports answer on CPU 0 alone. STREAMON and STREAMOFF
+ * (process context) send the stream call and start or cancel the timer
+ * through kw_host_call(), so the timer is pinned to CPU 0 and its frame
+ * imports are made there.
+ */
+
+#include <linux/dma-buf.h>
+#include <linux/dma-mapping.h>
+#include <linux/hrtimer.h>
+#include <linux/init.h>
+#include <linux/kwcam.h>
+#include <linux/module.h>
+#include <linux/platform_device.h>
+#include <linux/slab.h>
+#include <linux/string.h>
+#include <media/v4l2-common.h>
+#include <media/v4l2-ctrls.h>
+#include <media/v4l2-device.h>
+#include <media/v4l2-event.h>
+#include <media/v4l2-fh.h>
+#include <media/v4l2-ioctl.h>
+#include <media/videobuf2-dma-contig.h>
+#include <media/videobuf2-v4l2.h>
+#include <asm/wasm.h>
+
+/* wasm_driver_camera_init() bits: compressed formats the host encodes. */
+#define KWCAM_INIT_H264 (1 << 0)
+
+/* The frame import's fourth argument for a compressed stream (host ABI, not uapi). */
+struct kwcam_chunk {
+ u32 flags; /* out: KWCAM_CHUNK_* */
+ u32 age_us; /* out: how long ago its frame was captured */
+ u32 bitrate; /* in: the bitrate control */
+ u32 gop; /* in: the GOP size control */
+ u32 request; /* in: KWCAM_REQ_* */
+ u32 reserved[3];
+};
+#define KWCAM_CHUNK_KEY (1 << 0) /* a key frame (IDR, with SPS and PPS) */
+#define KWCAM_REQ_KEY (1 << 0) /* a key frame next (FORCE_KEY_FRAME) */
+
+/* Host imports, module "unkernel". None of them suspends. */
+/* < 0: no camera. Else the compressed formats the host encodes (KWCAM_INIT_*). */
+long wasm_driver_camera_init(void)
+ __unkernel_import(wasm_driver_camera_init);
+/*
+ * Start (fourcc != 0) with a frame every num/den seconds, or stop (fourcc
+ * 0); for a compressed stream with the controls' bitrate (bits a second)
+ * and GOP size (frames from one key frame to the next).
+ */
+void wasm_driver_camera_stream(u32 fourcc, u32 width, u32 height, u32 num, u32 den,
+ u32 bitrate, u32 gop)
+ __unkernel_import(wasm_driver_camera_stream);
+/*
+ * Raw: write the current frame (@bytes, the negotiated format) at @buf and
+ * its id (16 bytes, or zero) at @id; returns @bytes, or 0 for none (@chunk
+ * is NULL). Compressed: write the next chunk of the stream (at most @bytes)
+ * at @buf and fill in @chunk; returns its size, or 0 for none yet.
+ */
+long wasm_driver_camera_frame(void *buf, long bytes, u8 *id, struct kwcam_chunk *chunk)
+ __unkernel_import(wasm_driver_camera_frame);
+
+/* Compressed: ticks a frame interval, at least this far apart, and chunks a tick at most. */
+#define KWCAM_CHUNK_TICKS 4
+#define KWCAM_CHUNK_TICK_MIN_NS (4 * NSEC_PER_MSEC)
+#define KWCAM_CHUNKS_PER_TICK 8
+/* A chunk's age (since its frame was captured) taken off its timestamp at most. */
+#define KWCAM_AGE_MAX_US (10 * USEC_PER_SEC)
+
+/*
+ * At most this many buffers, as uvcvideo (a 1280x720 YUYV one is 1.8 MiB):
+ * GStreamer's v4l2src io-mode=dmabuf into vavp9enc holds 17 or more, the
+ * encoder keeping its reference frames' input buffers.
+ */
+#define KWCAM_MAX_BUFFERS 32
+
+struct kwcam_size {
+ u32 width, height;
+};
+
+static const struct kwcam_size kwcam_sizes[] = {
+ { 320, 240 }, { 640, 480 }, { 1280, 720 },
+};
+
+/*
+ * Formats, in ENUM_FMT's order; a compressed one only where the host has its
+ * bit. The first is the default and what an unknown format becomes: planar
+ * 4:2:0 is what players take as is (ffmpeg's v4l2 input tries YUV420 first
+ * and gets yuv420p) and the host's cheapest (a camera's VideoFrame copied
+ * plane for plane, or NV12's chroma split).
+ */
+static const struct kwcam_format {
+ u32 fourcc;
+ u32 host; /* KWCAM_INIT_*, 0: raw, always */
+} kwcam_all_formats[] = {
+ { V4L2_PIX_FMT_YUV420, 0 },
+ { V4L2_PIX_FMT_NV12, 0 },
+ { V4L2_PIX_FMT_YUYV, 0 },
+ { V4L2_PIX_FMT_H264, KWCAM_INIT_H264 },
+};
+
+static bool kwcam_compressed(u32 fourcc)
+{
+ return fourcc == V4L2_PIX_FMT_H264;
+}
+
+/* Frame rates offered, fastest first (intervals of 1/fps s). */
+static const u32 kwcam_rates[] = { 30, 25, 20, 15, 10, 5 };
+
+struct kwcam_buffer {
+ struct vb2_v4l2_buffer vb;
+ struct list_head list;
+ void *vaddr; /* the plane's kernel address, from buf_prepare */
+ u8 id[16]; /* the host's id of the frame in it; zero: none */
+};
+
+struct kwcam {
+ struct platform_device *pdev;
+ struct v4l2_device v4l2_dev;
+ struct video_device vdev;
+ struct vb2_queue queue;
+ struct mutex lock; /* ioctls and the queue */
+ spinlock_t qlock; /* buf_list, streaming */
+ struct list_head buf_list;
+ struct v4l2_pix_format fmt;
+ u32 fps;
+ u32 formats[ARRAY_SIZE(kwcam_all_formats)]; /* offered */
+ u32 nformats;
+ struct hrtimer timer;
+ u64 interval_ns;
+ u64 tick_ns; /* the timer's period: the interval, or less for compressed */
+ u32 sequence;
+ bool streaming; /* under qlock */
+ unsigned long frames, black, dropped;
+ /* Compressed (with the controls, only where the host encodes) */
+ struct v4l2_ctrl_handler ctrls;
+ struct v4l2_ctrl *bitrate, *gop;
+ bool bitrate_auto, gop_auto; /* follow size and rate until set */
+ bool ctrl_internal; /* the driver sets a control (under the handler's lock) */
+ u32 bitrate_val, gop_val; /* the controls, for the timer */
+ u32 want_key; /* FORCE_KEY_FRAME, until a tick tells the host */
+ u64 last_ts;
+ struct kwcam_chunk chunk; /* the frame import's, on CPU 0 */
+};
+
+/*
+ * The planes' memory (videobuf2-dma-contig's buf_priv) and whether it is
+ * mapped writable: alloc and put keep the table, the mmap hooks mark it.
+ * A plane not in it (the table was full) counts as writable.
+ */
+struct kwcam_mem {
+ void *priv;
+ bool writable;
+};
+
+static DEFINE_SPINLOCK(kwcam_mem_lock);
+static struct kwcam_mem kwcam_mems[2 * KWCAM_MAX_BUFFERS];
+static struct vb2_mem_ops kwcam_memops;
+/* videobuf2-dma-contig's dma-buf ops, and kwcam's: those with mmap wrapped (made at the first export) */
+static const struct dma_buf_ops *kwcam_dc_dmabuf_ops;
+static struct dma_buf_ops kwcam_dmabuf_ops;
+
+static struct kwcam_mem *kwcam_mem_find(void *priv)
+{
+ u32 i;
+
+ for (i = 0; i < ARRAY_SIZE(kwcam_mems); i++)
+ if (kwcam_mems[i].priv == priv)
+ return &kwcam_mems[i];
+ return NULL;
+}
+
+static bool kwcam_mem_writable(void *priv)
+{
+ struct kwcam_mem *m;
+ unsigned long flags;
+ bool w;
+
+ spin_lock_irqsave(&kwcam_mem_lock, flags);
+ m = kwcam_mem_find(priv);
+ w = !m || m->writable;
+ spin_unlock_irqrestore(&kwcam_mem_lock, flags);
+ return w;
+}
+
+/* A mapping of a plane: a writable one marks it, a read-only one stays read-only. */
+static void kwcam_mem_mapped(void *priv, struct vm_area_struct *vma)
+{
+ struct kwcam_mem *m;
+ unsigned long flags;
+
+ if (!(vma->vm_flags & VM_WRITE)) {
+ vm_flags_clear(vma, VM_MAYWRITE);
+ return;
+ }
+ spin_lock_irqsave(&kwcam_mem_lock, flags);
+ m = kwcam_mem_find(priv);
+ if (m)
+ m->writable = true;
+ spin_unlock_irqrestore(&kwcam_mem_lock, flags);
+}
+
+static void *kwcam_mem_alloc(struct vb2_buffer *vb, struct device *dev, unsigned long size)
+{
+ void *priv = vb2_dma_contig_memops.alloc(vb, dev, size);
+ struct kwcam_mem *m;
+ unsigned long flags;
+
+ if (IS_ERR_OR_NULL(priv))
+ return priv;
+ spin_lock_irqsave(&kwcam_mem_lock, flags);
+ m = kwcam_mem_find(NULL);
+ if (m) {
+ m->priv = priv;
+ m->writable = false;
+ }
+ spin_unlock_irqrestore(&kwcam_mem_lock, flags);
+ return priv;
+}
+
+static void kwcam_mem_put(void *priv)
+{
+ struct kwcam_mem *m;
+ unsigned long flags;
+
+ spin_lock_irqsave(&kwcam_mem_lock, flags);
+ m = kwcam_mem_find(priv);
+ if (m)
+ m->priv = NULL;
+ spin_unlock_irqrestore(&kwcam_mem_lock, flags);
+ vb2_dma_contig_memops.put(priv);
+}
+
+static int kwcam_mem_mmap(void *priv, struct vm_area_struct *vma)
+{
+ kwcam_mem_mapped(priv, vma);
+ return vb2_dma_contig_memops.mmap(priv, vma);
+}
+
+static int kwcam_dmabuf_mmap(struct dma_buf *dbuf, struct vm_area_struct *vma)
+{
+ kwcam_mem_mapped(dbuf->priv, vma);
+ return kwcam_dc_dmabuf_ops->mmap(dbuf, vma);
+}
+
+/* EXPBUF: videobuf2-dma-contig's dma-buf, with kwcam's ops (mmap wrapped; and what KWCAM_IOC_FRAME recognises) */
+static struct dma_buf *kwcam_mem_get_dmabuf(struct vb2_buffer *vb, void *priv, unsigned long flags)
+{
+ struct dma_buf *dbuf = vb2_dma_contig_memops.get_dmabuf(vb, priv, flags);
+ unsigned long irq;
+
+ if (IS_ERR_OR_NULL(dbuf))
+ return dbuf;
+ spin_lock_irqsave(&kwcam_mem_lock, irq);
+ if (!kwcam_dc_dmabuf_ops) {
+ kwcam_dc_dmabuf_ops = dbuf->ops;
+ kwcam_dmabuf_ops = *dbuf->ops;
+ kwcam_dmabuf_ops.mmap = kwcam_dmabuf_mmap;
+ }
+ spin_unlock_irqrestore(&kwcam_mem_lock, irq);
+ if (dbuf->ops == kwcam_dc_dmabuf_ops)
+ dbuf->ops = &kwcam_dmabuf_ops;
+ return dbuf;
+}
+
+static void kwcam_fill_fmt(struct v4l2_pix_format *f, u32 fourcc, u32 w, u32 h)
+{
+ memset(f, 0, sizeof(*f));
+ f->pixelformat = fourcc;
+ f->width = w;
+ f->height = h;
+ f->field = V4L2_FIELD_NONE;
+ if (kwcam_compressed(fourcc)) {
+ /* At most what the frame is raw, as NV12 (a chunk too large never reaches the guest) */
+ f->bytesperline = 0;
+ f->sizeimage = w * h * 3 / 2;
+ } else if (fourcc == V4L2_PIX_FMT_NV12 || fourcc == V4L2_PIX_FMT_YUV420) {
+ /* (YUV420: Y rows of w bytes, then the Cb and Cr planes, rows of w / 2) */
+ f->bytesperline = w;
+ f->sizeimage = w * h * 3 / 2;
+ } else {
+ f->bytesperline = w * 2;
+ f->sizeimage = w * h * 2;
+ }
+ /* What webcams report (uvcvideo): sRGB primaries, BT.601 limited range. */
+ f->colorspace = V4L2_COLORSPACE_SRGB;
+ f->ycbcr_enc = V4L2_YCBCR_ENC_601;
+ f->quantization = V4L2_QUANTIZATION_LIM_RANGE;
+ f->xfer_func = V4L2_XFER_FUNC_SRGB;
+}
+
+/* A black frame in the buffer's format (Y 16, Cb and Cr 128). */
+static void kwcam_black(const struct v4l2_pix_format *f, u8 *p)
+{
+ u32 n = f->width * f->height;
+
+ if (f->pixelformat == V4L2_PIX_FMT_NV12 || f->pixelformat == V4L2_PIX_FMT_YUV420) {
+ memset(p, 16, n);
+ memset(p + n, 128, n / 2);
+ } else {
+ u32 *w = (u32 *)p;
+ u32 i;
+
+ /* Y0 Cb Y1 Cr, little endian. */
+ for (i = 0; i < n / 2; i++)
+ w[i] = 0x80108010;
+ }
+}
+
+/*
+ * Compressed: the host's next chunks into the oldest queued buffers, as
+ * many as it has (up to KWCAM_CHUNKS_PER_TICK); a buffer it has none for
+ * goes back to the head of the queue.
+ */
+static void kwcam_tick_chunks(struct kwcam *cam)
+{
+ long size = cam->fmt.sizeimage;
+ unsigned long flags;
+ u32 n;
+
+ for (n = 0; n < KWCAM_CHUNKS_PER_TICK; n++) {
+ struct kwcam_buffer *buf = NULL;
+ struct kwcam_chunk *c = &cam->chunk;
+ struct vb2_buffer *vb;
+ u64 now, age, ts;
+ long got;
+
+ spin_lock_irqsave(&cam->qlock, flags);
+ if (cam->streaming && !list_empty(&cam->buf_list)) {
+ buf = list_first_entry(&cam->buf_list, struct kwcam_buffer, list);
+ list_del(&buf->list);
+ }
+ spin_unlock_irqrestore(&cam->qlock, flags);
+ if (!buf)
+ return;
+ memset(c, 0, sizeof(*c));
+ c->bitrate = READ_ONCE(cam->bitrate_val);
+ c->gop = READ_ONCE(cam->gop_val);
+ c->request = xchg(&cam->want_key, 0) ? KWCAM_REQ_KEY : 0;
+ memset(buf->id, 0, sizeof(buf->id));
+ got = wasm_driver_camera_frame(buf->vaddr, size, buf->id, c);
+ /* (no frame ids for a compressed stream) */
+ memset(buf->id, 0, sizeof(buf->id));
+ if (got <= 0 || got > size) {
+ if (got > size)
+ pr_warn_once("kwcam: the host gave a %ld-byte chunk for a %ld-byte buffer\n", got, size);
+ spin_lock_irqsave(&cam->qlock, flags);
+ list_add(&buf->list, &cam->buf_list);
+ spin_unlock_irqrestore(&cam->qlock, flags);
+ return;
+ }
+ vb = &buf->vb.vb2_buf;
+ now = ktime_get_ns();
+ age = min_t(u64, READ_ONCE(c->age_us), KWCAM_AGE_MAX_US) * NSEC_PER_USEC;
+ ts = now > age ? now - age : 0;
+ if (ts <= cam->last_ts)
+ ts = cam->last_ts + NSEC_PER_USEC;
+ cam->last_ts = ts;
+ cam->frames++;
+ vb2_set_plane_payload(vb, 0, got);
+ vb->timestamp = ts;
+ buf->vb.sequence = cam->sequence++;
+ buf->vb.field = V4L2_FIELD_NONE;
+ buf->vb.flags &= ~(V4L2_BUF_FLAG_KEYFRAME | V4L2_BUF_FLAG_PFRAME | V4L2_BUF_FLAG_BFRAME);
+ buf->vb.flags |= READ_ONCE(c->flags) & KWCAM_CHUNK_KEY ? V4L2_BUF_FLAG_KEYFRAME : V4L2_BUF_FLAG_PFRAME;
+ vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
+ }
+}
+
+static enum hrtimer_restart kwcam_tick(struct hrtimer *timer)
+{
+ struct kwcam *cam = container_of(timer, struct kwcam, timer);
+ struct kwcam_buffer *buf = NULL;
+ unsigned long flags;
+ u32 seq;
+
+ if (kwcam_compressed(cam->fmt.pixelformat)) {
+ if (!READ_ONCE(cam->streaming))
+ return HRTIMER_NORESTART;
+ kwcam_tick_chunks(cam);
+ hrtimer_forward_now(timer, ns_to_ktime(cam->tick_ns));
+ return HRTIMER_RESTART;
+ }
+ spin_lock_irqsave(&cam->qlock, flags);
+ if (!cam->streaming) {
+ spin_unlock_irqrestore(&cam->qlock, flags);
+ return HRTIMER_NORESTART;
+ }
+ seq = cam->sequence++;
+ if (!list_empty(&cam->buf_list)) {
+ buf = list_first_entry(&cam->buf_list, struct kwcam_buffer, list);
+ list_del(&buf->list);
+ } else {
+ cam->dropped++;
+ }
+ spin_unlock_irqrestore(&cam->qlock, flags);
+
+ if (buf) {
+ struct vb2_buffer *vb = &buf->vb.vb2_buf;
+ u8 *p = buf->vaddr;
+ long size = cam->fmt.sizeimage;
+
+ memset(buf->id, 0, sizeof(buf->id));
+ if (wasm_driver_camera_frame(p, size, buf->id, NULL) != size) {
+ kwcam_black(&cam->fmt, p);
+ memset(buf->id, 0, sizeof(buf->id));
+ cam->black++;
+ }
+ cam->frames++;
+ vb2_set_plane_payload(vb, 0, size);
+ vb->timestamp = ktime_get_ns();
+ buf->vb.sequence = seq;
+ buf->vb.field = V4L2_FIELD_NONE;
+ vb2_buffer_done(vb, VB2_BUF_STATE_DONE);
+ }
+ hrtimer_forward_now(timer, ns_to_ktime(cam->interval_ns));
+ return HRTIMER_RESTART;
+}
+
+/* CPU 0: tell the host and start the timer there, or stop both. */
+static long kwcam_host_stream(void *arg)
+{
+ struct kwcam *cam = arg;
+ bool on;
+ unsigned long flags;
+
+ spin_lock_irqsave(&cam->qlock, flags);
+ on = cam->streaming;
+ spin_unlock_irqrestore(&cam->qlock, flags);
+ if (on) {
+ wasm_driver_camera_stream(cam->fmt.pixelformat, cam->fmt.width,
+ cam->fmt.height, 1, cam->fps,
+ READ_ONCE(cam->bitrate_val), READ_ONCE(cam->gop_val));
+ hrtimer_start(&cam->timer, ns_to_ktime(cam->tick_ns),
+ HRTIMER_MODE_REL_PINNED);
+ } else {
+ hrtimer_cancel(&cam->timer);
+ wasm_driver_camera_stream(0, 0, 0, 0, 0, 0, 0);
+ }
+ return 0;
+}
+
+static void kwcam_stream(struct kwcam *cam, bool on)
+{
+ unsigned long flags;
+
+ spin_lock_irqsave(&cam->qlock, flags);
+ cam->streaming = on;
+ spin_unlock_irqrestore(&cam->qlock, flags);
+#ifdef CONFIG_SMP
+ kw_host_call(kwcam_host_stream, cam);
+#else
+ kwcam_host_stream(cam);
+#endif
+}
+
+static int kwcam_queue_setup(struct vb2_queue *q, unsigned int *nbuffers,
+ unsigned int *nplanes, unsigned int sizes[],
+ struct device *alloc_devs[])
+{
+ struct kwcam *cam = vb2_get_drv_priv(q);
+ unsigned int have = vb2_get_num_buffers(q);
+
+ /* vb2 needs max_num_buffers >= VB2_MAX_FRAME, so the limit is here. */
+ if (have >= KWCAM_MAX_BUFFERS)
+ return -ENOBUFS;
+ *nbuffers = min(*nbuffers, KWCAM_MAX_BUFFERS - have);
+ if (*nplanes)
+ return sizes[0] < cam->fmt.sizeimage ? -EINVAL : 0;
+ *nplanes = 1;
+ sizes[0] = cam->fmt.sizeimage;
+ return 0;
+}
+
+static int kwcam_buf_prepare(struct vb2_buffer *vb)
+{
+ struct kwcam *cam = vb2_get_drv_priv(vb->vb2_queue);
+ struct kwcam_buffer *buf = container_of(to_vb2_v4l2_buffer(vb),
+ struct kwcam_buffer, vb);
+
+ if (vb2_plane_size(vb, 0) < cam->fmt.sizeimage)
+ return -EINVAL;
+ /*
+ * The address the tick fills, taken here in process context: for an
+ * imported dma-buf the first vb2_plane_vaddr() maps it under its
+ * reservation lock, which the timer could not take, and an exporter
+ * that cannot map gives none, so such a buffer is refused.
+ */
+ buf->vaddr = vb2_plane_vaddr(vb, 0);
+ if (!buf->vaddr)
+ return -EFAULT;
+ vb2_set_plane_payload(vb, 0, cam->fmt.sizeimage);
+ return 0;
+}
+
+static void kwcam_buf_queue(struct vb2_buffer *vb)
+{
+ struct kwcam *cam = vb2_get_drv_priv(vb->vb2_queue);
+ struct kwcam_buffer *buf = container_of(to_vb2_v4l2_buffer(vb),
+ struct kwcam_buffer, vb);
+ unsigned long flags;
+
+ spin_lock_irqsave(&cam->qlock, flags);
+ list_add_tail(&buf->list, &cam->buf_list);
+ spin_unlock_irqrestore(&cam->qlock, flags);
+}
+
+static void kwcam_return_all(struct kwcam *cam, enum vb2_buffer_state state)
+{
+ struct kwcam_buffer *buf, *n;
+ unsigned long flags;
+
+ spin_lock_irqsave(&cam->qlock, flags);
+ list_for_each_entry_safe(buf, n, &cam->buf_list, list) {
+ list_del(&buf->list);
+ vb2_buffer_done(&buf->vb.vb2_buf, state);
+ }
+ spin_unlock_irqrestore(&cam->qlock, flags);
+}
+
+static int kwcam_start_streaming(struct vb2_queue *q, unsigned int count)
+{
+ struct kwcam *cam = vb2_get_drv_priv(q);
+
+ cam->sequence = 0;
+ cam->interval_ns = div_u64(NSEC_PER_SEC, cam->fps);
+ cam->tick_ns = cam->interval_ns;
+ if (kwcam_compressed(cam->fmt.pixelformat)) {
+ cam->tick_ns = max_t(u64, cam->interval_ns / KWCAM_CHUNK_TICKS, KWCAM_CHUNK_TICK_MIN_NS);
+ cam->last_ts = 0;
+ WRITE_ONCE(cam->want_key, 0);
+ }
+ kwcam_stream(cam, true);
+ return 0;
+}
+
+static void kwcam_stop_streaming(struct vb2_queue *q)
+{
+ struct kwcam *cam = vb2_get_drv_priv(q);
+
+ kwcam_stream(cam, false); /* the timer has stopped when it returns */
+ kwcam_return_all(cam, VB2_BUF_STATE_ERROR);
+}
+
+static const struct vb2_ops kwcam_qops = {
+ .queue_setup = kwcam_queue_setup,
+ .buf_prepare = kwcam_buf_prepare,
+ .buf_queue = kwcam_buf_queue,
+ .start_streaming = kwcam_start_streaming,
+ .stop_streaming = kwcam_stop_streaming,
+};
+
+static int kwcam_querycap(struct file *file, void *priv,
+ struct v4l2_capability *cap)
+{
+ strscpy(cap->driver, "kwcam", sizeof(cap->driver));
+ strscpy(cap->card, "unkernel host camera", sizeof(cap->card));
+ strscpy(cap->bus_info, "platform:kwcam", sizeof(cap->bus_info));
+ return 0;
+}
+
+static int kwcam_enum_fmt(struct file *file, void *priv, struct v4l2_fmtdesc *f)
+{
+ struct kwcam *cam = video_drvdata(file);
+
+ if (f->index >= cam->nformats)
+ return -EINVAL;
+ /* (the core adds the description and, for H.264, V4L2_FMT_FLAG_COMPRESSED) */
+ f->pixelformat = cam->formats[f->index];
+ return 0;
+}
+
+static bool kwcam_format_ok(struct kwcam *cam, u32 fourcc)
+{
+ u32 i;
+
+ for (i = 0; i < cam->nformats; i++)
+ if (cam->formats[i] == fourcc)
+ return true;
+ return false;
+}
+
+/* The controls that follow the stream until a program sets them: about 0.1 bit a pixel, a key frame a second. */
+static void kwcam_auto_ctrls(struct kwcam *cam)
+{
+ u64 bps = div_u64((u64)cam->fmt.width * cam->fmt.height * cam->fps, 10);
+
+ if (!cam->bitrate)
+ return;
+ cam->ctrl_internal = true;
+ if (cam->bitrate_auto)
+ v4l2_ctrl_s_ctrl(cam->bitrate, clamp_t(u64, bps, cam->bitrate->minimum, cam->bitrate->maximum));
+ if (cam->gop_auto)
+ v4l2_ctrl_s_ctrl(cam->gop, cam->fps);
+ cam->ctrl_internal = false;
+ /* (the handler's lock, which v4l2_ctrl_activate() wants: both are of one handler) */
+ v4l2_ctrl_lock(cam->bitrate);
+ v4l2_ctrl_activate(cam->bitrate, kwcam_compressed(cam->fmt.pixelformat));
+ v4l2_ctrl_activate(cam->gop, kwcam_compressed(cam->fmt.pixelformat));
+ v4l2_ctrl_unlock(cam->bitrate);
+}
+
+static int kwcam_s_ctrl(struct v4l2_ctrl *ctrl)
+{
+ struct kwcam *cam = container_of(ctrl->handler, struct kwcam, ctrls);
+
+ switch (ctrl->id) {
+ case V4L2_CID_MPEG_VIDEO_BITRATE:
+ if (!cam->ctrl_internal)
+ cam->bitrate_auto = false;
+ WRITE_ONCE(cam->bitrate_val, ctrl->val);
+ return 0;
+ case V4L2_CID_MPEG_VIDEO_GOP_SIZE:
+ if (!cam->ctrl_internal)
+ cam->gop_auto = false;
+ WRITE_ONCE(cam->gop_val, ctrl->val);
+ return 0;
+ case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME:
+ WRITE_ONCE(cam->want_key, 1);
+ return 0;
+ }
+ return -EINVAL;
+}
+
+static const struct v4l2_ctrl_ops kwcam_ctrl_ops = {
+ .s_ctrl = kwcam_s_ctrl,
+};
+
+static int kwcam_try_fmt(struct file *file, void *priv, struct v4l2_format *f)
+{
+ struct kwcam *cam = video_drvdata(file);
+ struct v4l2_pix_format *pix = &f->fmt.pix;
+ const struct kwcam_size *s;
+ u32 fourcc = pix->pixelformat;
+
+ if (!kwcam_format_ok(cam, fourcc))
+ fourcc = cam->formats[0];
+ s = v4l2_find_nearest_size(kwcam_sizes, ARRAY_SIZE(kwcam_sizes),
+ width, height, pix->width, pix->height);
+ kwcam_fill_fmt(pix, fourcc, s->width, s->height);
+ return 0;
+}
+
+static int kwcam_g_fmt(struct file *file, void *priv, struct v4l2_format *f)
+{
+ struct kwcam *cam = video_drvdata(file);
+
+ f->fmt.pix = cam->fmt;
+ return 0;
+}
+
+static int kwcam_s_fmt(struct file *file, void *priv, struct v4l2_format *f)
+{
+ struct kwcam *cam = video_drvdata(file);
+
+ kwcam_try_fmt(file, priv, f);
+ if (vb2_is_busy(&cam->queue))
+ return -EBUSY;
+ cam->fmt = f->fmt.pix;
+ kwcam_auto_ctrls(cam);
+ return 0;
+}
+
+static int kwcam_enum_framesizes(struct file *file, void *priv,
+ struct v4l2_frmsizeenum *fs)
+{
+ struct kwcam *cam = video_drvdata(file);
+
+ if (!kwcam_format_ok(cam, fs->pixel_format) ||
+ fs->index >= ARRAY_SIZE(kwcam_sizes))
+ return -EINVAL;
+ fs->type = V4L2_FRMSIZE_TYPE_DISCRETE;
+ fs->discrete.width = kwcam_sizes[fs->index].width;
+ fs->discrete.height = kwcam_sizes[fs->index].height;
+ return 0;
+}
+
+static int kwcam_enum_frameintervals(struct file *file, void *priv,
+ struct v4l2_frmivalenum *fi)
+{
+ struct kwcam *cam = video_drvdata(file);
+ u32 i;
+
+ if (!kwcam_format_ok(cam, fi->pixel_format) ||
+ fi->index >= ARRAY_SIZE(kwcam_rates))
+ return -EINVAL;
+ for (i = 0; i < ARRAY_SIZE(kwcam_sizes); i++)
+ if (kwcam_sizes[i].width == fi->width &&
+ kwcam_sizes[i].height == fi->height)
+ break;
+ if (i == ARRAY_SIZE(kwcam_sizes))
+ return -EINVAL;
+ fi->type = V4L2_FRMIVAL_TYPE_DISCRETE;
+ fi->discrete.numerator = 1;
+ fi->discrete.denominator = kwcam_rates[fi->index];
+ return 0;
+}
+
+static int kwcam_g_parm(struct file *file, void *priv, struct v4l2_streamparm *a)
+{
+ struct kwcam *cam = video_drvdata(file);
+
+ if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
+ return -EINVAL;
+ a->parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
+ a->parm.capture.timeperframe.numerator = 1;
+ a->parm.capture.timeperframe.denominator = cam->fps;
+ a->parm.capture.readbuffers = 2;
+ return 0;
+}
+
+static int kwcam_s_parm(struct file *file, void *priv, struct v4l2_streamparm *a)
+{
+ struct kwcam *cam = video_drvdata(file);
+ struct v4l2_fract *t = &a->parm.capture.timeperframe;
+ u32 best = kwcam_rates[0], i;
+ u64 want;
+
+ if (a->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
+ return -EINVAL;
+ /* The rate nearest to den/num (in milli-fps); 0/0 means the fastest. */
+ if (t->numerator && t->denominator) {
+ want = div_u64((u64)t->denominator * 1000, t->numerator);
+ for (i = 1; i < ARRAY_SIZE(kwcam_rates); i++)
+ if (abs((s64)kwcam_rates[i] * 1000 - (s64)want) <
+ abs((s64)best * 1000 - (s64)want))
+ best = kwcam_rates[i];
+ }
+ if (vb2_is_streaming(&cam->queue) && best != cam->fps)
+ return -EBUSY;
+ cam->fps = best;
+ kwcam_auto_ctrls(cam);
+ return kwcam_g_parm(file, priv, a);
+}
+
+static int kwcam_enum_input(struct file *file, void *priv, struct v4l2_input *in)
+{
+ if (in->index)
+ return -EINVAL;
+ in->type = V4L2_INPUT_TYPE_CAMERA;
+ strscpy(in->name, "Camera", sizeof(in->name));
+ return 0;
+}
+
+static int kwcam_g_input(struct file *file, void *priv, unsigned int *i)
+{
+ *i = 0;
+ return 0;
+}
+
+static int kwcam_s_input(struct file *file, void *priv, unsigned int i)
+{
+ return i ? -EINVAL : 0;
+}
+
+/* KWCAM_IOC_FRAME (uapi/linux/kwcam.h): the buffer a dma-buf of this device is, and its frame; under the queue's lock */
+static long kwcam_default(struct file *file, void *fh, bool valid_prio, unsigned int cmd, void *arg)
+{
+ struct kwcam *cam = video_drvdata(file);
+ struct kwcam_frame *fr = arg;
+ struct dma_buf *dbuf;
+ unsigned int i;
+ long ret = -ENOENT;
+
+ if (cmd != KWCAM_IOC_FRAME)
+ return -ENOTTY;
+ /* (a compressed stream's buffers hold chunks, not frames the host keeps) */
+ if (kwcam_compressed(cam->fmt.pixelformat))
+ return -ENOENT;
+ dbuf = dma_buf_get(fr->fd);
+ if (IS_ERR(dbuf))
+ return PTR_ERR(dbuf);
+ for (i = 0; dbuf->ops == &kwcam_dmabuf_ops && i < cam->queue.max_num_buffers; i++) {
+ struct vb2_buffer *vb = vb2_get_buffer(&cam->queue, i);
+ struct kwcam_buffer *buf;
+
+ if (!vb || vb->memory != VB2_MEMORY_MMAP || vb->planes[0].mem_priv != dbuf->priv)
+ continue;
+ buf = container_of(to_vb2_v4l2_buffer(vb), struct kwcam_buffer, vb);
+ memset(fr, 0, sizeof(*fr));
+ fr->fd = -1;
+ fr->index = vb->index;
+ fr->flags = (vb->state == VB2_BUF_STATE_DEQUEUED ? KWCAM_FRAME_DEQUEUED : 0) |
+ (kwcam_mem_writable(dbuf->priv) ? KWCAM_FRAME_WRITABLE : 0);
+ fr->sequence = buf->vb.sequence;
+ fr->pixelformat = cam->fmt.pixelformat;
+ fr->width = cam->fmt.width;
+ fr->height = cam->fmt.height;
+ fr->bytesperline = cam->fmt.bytesperline;
+ fr->bytesused = vb2_get_plane_payload(vb, 0);
+ memcpy(fr->id, buf->id, sizeof(fr->id));
+ ret = 0;
+ break;
+ }
+ dma_buf_put(dbuf);
+ return ret;
+}
+
+/* (the event ioctls are set only with the controls: a camera without H.264 has neither) */
+static struct v4l2_ioctl_ops kwcam_ioctl_ops = {
+ .vidioc_querycap = kwcam_querycap,
+ .vidioc_enum_fmt_vid_cap = kwcam_enum_fmt,
+ .vidioc_try_fmt_vid_cap = kwcam_try_fmt,
+ .vidioc_s_fmt_vid_cap = kwcam_s_fmt,
+ .vidioc_g_fmt_vid_cap = kwcam_g_fmt,
+ .vidioc_enum_framesizes = kwcam_enum_framesizes,
+ .vidioc_enum_frameintervals = kwcam_enum_frameintervals,
+ .vidioc_g_parm = kwcam_g_parm,
+ .vidioc_s_parm = kwcam_s_parm,
+ .vidioc_enum_input = kwcam_enum_input,
+ .vidioc_g_input = kwcam_g_input,
+ .vidioc_s_input = kwcam_s_input,
+ .vidioc_reqbufs = vb2_ioctl_reqbufs,
+ .vidioc_create_bufs = vb2_ioctl_create_bufs,
+ .vidioc_prepare_buf = vb2_ioctl_prepare_buf,
+ .vidioc_querybuf = vb2_ioctl_querybuf,
+ .vidioc_qbuf = vb2_ioctl_qbuf,
+ .vidioc_dqbuf = vb2_ioctl_dqbuf,
+ .vidioc_expbuf = vb2_ioctl_expbuf,
+ .vidioc_streamon = vb2_ioctl_streamon,
+ .vidioc_streamoff = vb2_ioctl_streamoff,
+ .vidioc_default = kwcam_default,
+};
+
+static const struct v4l2_file_operations kwcam_fops = {
+ .owner = THIS_MODULE,
+ .open = v4l2_fh_open,
+ .release = vb2_fop_release,
+ .unlocked_ioctl = video_ioctl2,
+ .read = vb2_fop_read,
+ .mmap = vb2_fop_mmap,
+ .poll = vb2_fop_poll,
+};
+
+static int __init kwcam_init(void)
+{
+ struct platform_device_info info = {
+ .name = "kwcam",
+ .id = PLATFORM_DEVID_NONE,
+ .dma_mask = DMA_BIT_MASK(32),
+ };
+ struct video_device *vdev;
+ struct vb2_queue *q;
+ struct kwcam *cam;
+ long host;
+ u32 i;
+ int err;
+
+ host = wasm_driver_camera_init();
+ if (host < 0) {
+ pr_info("kwcam: no host camera\n");
+ return 0;
+ }
+ cam = kzalloc_obj(*cam);
+ if (!cam)
+ return -ENOMEM;
+ for (i = 0; i < ARRAY_SIZE(kwcam_all_formats); i++)
+ if (!kwcam_all_formats[i].host || (host & kwcam_all_formats[i].host))
+ cam->formats[cam->nformats++] = kwcam_all_formats[i].fourcc;
+ cam->pdev = platform_device_register_full(&info);
+ if (IS_ERR(cam->pdev)) {
+ err = PTR_ERR(cam->pdev);
+ goto err_free;
+ }
+ mutex_init(&cam->lock);
+ spin_lock_init(&cam->qlock);
+ INIT_LIST_HEAD(&cam->buf_list);
+ hrtimer_setup(&cam->timer, kwcam_tick, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
+ kwcam_fill_fmt(&cam->fmt, cam->formats[0], 640, 480);
+ cam->fps = kwcam_rates[0];
+
+ err = v4l2_device_register(&cam->pdev->dev, &cam->v4l2_dev);
+ if (err)
+ goto err_pdev;
+
+ if (kwcam_format_ok(cam, V4L2_PIX_FMT_H264)) {
+ struct v4l2_ctrl_handler *hdl = &cam->ctrls;
+
+ v4l2_ctrl_handler_init(hdl, 4);
+ cam->bitrate = v4l2_ctrl_new_std(hdl, &kwcam_ctrl_ops, V4L2_CID_MPEG_VIDEO_BITRATE,
+ 50000, 20000000, 1, 1000000);
+ cam->gop = v4l2_ctrl_new_std(hdl, &kwcam_ctrl_ops, V4L2_CID_MPEG_VIDEO_GOP_SIZE,
+ 1, 1000, 1, 30);
+ v4l2_ctrl_new_std(hdl, &kwcam_ctrl_ops, V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME, 0, 0, 0, 0);
+ if (hdl->error) {
+ err = hdl->error;
+ v4l2_ctrl_handler_free(hdl);
+ cam->bitrate = cam->gop = NULL;
+ goto err_v4l2;
+ }
+ cam->bitrate_auto = cam->gop_auto = true;
+ kwcam_auto_ctrls(cam);
+ cam->ctrl_internal = true;
+ v4l2_ctrl_handler_setup(hdl);
+ cam->ctrl_internal = false;
+ cam->vdev.ctrl_handler = hdl;
+ kwcam_ioctl_ops.vidioc_subscribe_event = v4l2_ctrl_subscribe_event;
+ kwcam_ioctl_ops.vidioc_unsubscribe_event = v4l2_event_unsubscribe;
+ }
+
+ q = &cam->queue;
+ q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
+ q->io_modes = VB2_MMAP | VB2_DMABUF | VB2_READ;
+ q->dev = &cam->pdev->dev;
+ q->drv_priv = cam;
+ q->buf_struct_size = sizeof(struct kwcam_buffer);
+ q->ops = &kwcam_qops;
+ kwcam_memops = vb2_dma_contig_memops;
+ kwcam_memops.alloc = kwcam_mem_alloc;
+ kwcam_memops.put = kwcam_mem_put;
+ kwcam_memops.mmap = kwcam_mem_mmap;
+ kwcam_memops.get_dmabuf = kwcam_mem_get_dmabuf;
+ q->mem_ops = &kwcam_memops;
+ q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC |
+ V4L2_BUF_FLAG_TSTAMP_SRC_EOF;
+ q->lock = &cam->lock;
+ /* REQBUFS gives two at least; CREATE_BUFS gives what it asks for. */
+ q->min_reqbufs_allocation = 2;
+ err = vb2_queue_init(q);
+ if (err)
+ goto err_v4l2;
+
+ vdev = &cam->vdev;
+ strscpy(vdev->name, "kwcam", sizeof(vdev->name));
+ vdev->release = video_device_release_empty;
+ vdev->fops = &kwcam_fops;
+ vdev->ioctl_ops = &kwcam_ioctl_ops;
+ vdev->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_READWRITE |
+ V4L2_CAP_STREAMING;
+ vdev->lock = &cam->lock;
+ vdev->queue = q;
+ vdev->v4l2_dev = &cam->v4l2_dev;
+ video_set_drvdata(vdev, cam);
+ err = video_register_device(vdev, VFL_TYPE_VIDEO, -1);
+ if (err)
+ goto err_v4l2;
+ pr_info("kwcam: %s, YUV420, NV12, YUYV%s up to 1280x720 at 30 fps\n",
+ video_device_node_name(vdev), cam->bitrate ? " and H.264 (the host's encoder)" : "");
+ return 0;
+
+err_v4l2:
+ if (cam->bitrate)
+ v4l2_ctrl_handler_free(&cam->ctrls);
+ v4l2_device_unregister(&cam->v4l2_dev);
+err_pdev:
+ platform_device_unregister(cam->pdev);
+err_free:
+ kfree(cam);
+ return err;
+}
+device_initcall(kwcam_init);
+MODULE_IMPORT_NS("DMA_BUF");
diff --git a/include/uapi/linux/kwcam.h b/include/uapi/linux/kwcam.h
new file mode 100644
--- /dev/null
+++ b/include/uapi/linux/kwcam.h
@@ -0,0 +1,46 @@
+/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */
+/*
+ * kwcam: the camera of a unkernel instance, a V4L2 capture device
+ * (drivers/media/platform/kwcam.c, driver "kwcam").
+ *
+ * Copyright (C) 2026 Pooya Parsa <pooya@pi0.io>
+ *
+ * Each frame the host writes into a buffer comes with the host's id of it
+ * (128 random bits; zero for a black frame, when the host had none). A
+ * consumer that the host also serves (the VA-API driver, kwva) can name
+ * that frame to the host instead of sending its pixels: KWCAM_IOC_FRAME,
+ * on the device, takes a dma-buf exported from one of its buffers
+ * (VIDIOC_EXPBUF) and says which buffer it is, whether user space holds it
+ * now (dequeued: then its pixels are the frame `id` names, as the host
+ * wrote them), and whether the buffer is mapped writable anywhere (then a
+ * program may have changed them). A read-only mapping of a kwcam buffer
+ * (V4L2 mmap or the dma-buf's) cannot be made writable later (mprotect).
+ */
+#ifndef _UAPI_LINUX_KWCAM_H
+#define _UAPI_LINUX_KWCAM_H
+
+#include <linux/ioctl.h>
+#include <linux/types.h>
+
+/* struct kwcam_frame flags. */
+#define KWCAM_FRAME_DEQUEUED (1U << 0) /* user space holds the buffer */
+#define KWCAM_FRAME_WRITABLE (1U << 1) /* the buffer is (or was) mapped writable */
+
+struct kwcam_frame {
+ __s32 fd; /* in: a dma-buf exported from a buffer of this device */
+ __u32 index; /* out: the buffer's index */
+ __u32 flags; /* out: KWCAM_FRAME_* */
+ __u32 sequence; /* out: the frame's sequence number (v4l2_buffer.sequence) */
+ __u32 pixelformat; /* out: the stream's format (V4L2_PIX_FMT_*), */
+ __u32 width; /* size */
+ __u32 height;
+ __u32 bytesperline; /* and line pitch: the buffer's layout */
+ __u32 bytesused; /* out: bytes of the frame */
+ __u32 reserved[3];
+ __u8 id[16]; /* out: the host's id of the frame; all zero: none */
+};
+
+/* VIDIOC_PRIVATE + 0 ('V', BASE_VIDIOC_PRIVATE 192) */
+#define KWCAM_IOC_FRAME _IOWR('V', 192, struct kwcam_frame)
+
+#endif /* _UAPI_LINUX_KWCAM_H */