[PATCH 7/7] rust: samples: add the v4l2 sample driver

Daniel Almeida posted 7 patches 1 month, 2 weeks ago
[PATCH 7/7] rust: samples: add the v4l2 sample driver
Posted by Daniel Almeida 1 month, 2 weeks ago
This driver is the only user of the v4l2 abstractions at the moment. It
serves as a means to validate the abstractions by proving that the
device is actually registered as /dev/videoX, and it can be opened and
queried by v4l2-ctl, while also serving as a display of the current v4l2
support in Rust, as well as a blueprint for more elaborate Rust v4l2
drivers in the future.

Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
---
 MAINTAINERS                      |   1 +
 samples/rust/Kconfig             |  11 +++
 samples/rust/Makefile            |   1 +
 samples/rust/rust_driver_v4l2.rs | 145 +++++++++++++++++++++++++++++++++++++++
 4 files changed, 158 insertions(+)

diff --git a/MAINTAINERS b/MAINTAINERS
index 6fc5d57950e474d73d5d65271a0394efc5a8960b..14521bc0585503992da582f2cee361666985e39f 100644
--- a/MAINTAINERS
+++ b/MAINTAINERS
@@ -15440,6 +15440,7 @@ L:	linux-media@vger.kernel.org
 L:	rust-for-linux@vger.kernel.org
 S:	Supported
 F:	rust/media
+F:	sample/rust/rust_driver_v4l2.rs
 
 MEDIATEK BLUETOOTH DRIVER
 M:	Sean Wang <sean.wang@mediatek.com>
diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig
index 7f7371a004ee0a8f67dca99c836596709a70c4fa..64422acf1e9da9d05f904e14fd423b3b4aef173a 100644
--- a/samples/rust/Kconfig
+++ b/samples/rust/Kconfig
@@ -105,6 +105,17 @@ config SAMPLE_RUST_DRIVER_AUXILIARY
 
 	  If unsure, say N.
 
+config SAMPLE_RUST_DRIVER_V4L2
+	tristate "Video4Linux2 driver"
+	depends on MEDIA_SUPPORT && VIDEO_DEV
+	help
+	  This option builds the Rust V4L2 driver sample.
+
+	  To compile this as a module, choose M here:
+	  the module will be called rust_driver_v4l2.
+
+	  If unsure, say N.
+
 config SAMPLE_RUST_HOSTPROGS
 	bool "Host programs"
 	help
diff --git a/samples/rust/Makefile b/samples/rust/Makefile
index bd2faad63b4f3befe7d1ed5139fe25c7a8b6d7f6..57e21f0373938bb70b4cb400ea550010895b4c94 100644
--- a/samples/rust/Makefile
+++ b/samples/rust/Makefile
@@ -9,6 +9,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
 obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY)	+= rust_driver_auxiliary.o
+obj-$(CONFIG_SAMPLE_RUST_DRIVER_V4L2)		+= rust_driver_v4l2.o
 obj-$(CONFIG_SAMPLE_RUST_CONFIGFS)		+= rust_configfs.o
 
 rust_print-y := rust_print_main.o rust_print_events.o
diff --git a/samples/rust/rust_driver_v4l2.rs b/samples/rust/rust_driver_v4l2.rs
new file mode 100644
index 0000000000000000000000000000000000000000..a3ef98a613f2fed9e8589f0761ce7e43029c02b6
--- /dev/null
+++ b/samples/rust/rust_driver_v4l2.rs
@@ -0,0 +1,145 @@
+// SPDX-License-Identifier: GPL-2.0
+// SPDX-copyrightText: Copyright (C) 2025 Collabora Ltd.
+
+//! Rust V4L2 sample driver.
+//!
+//! This sample demonstrates how to:
+//! - Register a V4L2 device (struct v4l2_device),
+//! - Register a video node (struct video_device) using the Rust V4L2
+//!   abstractions,
+//! - Implement support for a V4L2 ioctl in a driver.
+//!
+//! It implements only `VIDIOC_QUERYCAP` and minimal open/close handling.
+
+use kernel::{
+    c_str,
+    device::Core,
+    media::v4l2::{
+        self,
+        caps::{self, DeviceCaps},
+        video,
+    },
+    of, platform,
+    prelude::*,
+    types::ARef,
+    ThisModule,
+};
+
+/// The private data associated with the V4L2 device.
+#[pin_data]
+struct Data {}
+
+/// The private data associated with a V4L2 device node, i.e. `struct
+/// video_device`.
+#[pin_data]
+struct VideoData {}
+
+/// The private data associated with a V4L2 file, i.e. `struct v4l2_fh`.
+#[pin_data]
+struct File {}
+
+impl v4l2::file::DriverFile for File {
+    type Driver = SampleDriver;
+
+    const MODULE: &'static ThisModule = &THIS_MODULE;
+
+    fn open(_vdev: &v4l2::video::Device<Self::Driver>) -> impl PinInit<Self, Error> {
+        try_pin_init!(Self {})
+    }
+}
+
+struct SampleDriver {
+    _pdev: ARef<platform::Device>,
+    _v4l2_reg: v4l2::device::Registration<Self>,
+    video_reg: video::Registration<Self>,
+}
+
+impl v4l2::device::Driver for SampleDriver {
+    type Data = Data;
+}
+
+#[vtable]
+impl video::Driver for SampleDriver {
+    type Data = VideoData;
+    type File = File;
+
+    const NODE_TYPE: video::NodeType = video::NodeType::Video;
+    const DIRECTION: video::Direction = video::Direction::Rx;
+    const NAME: &'static CStr = c_str!("rv4l2");
+    const CAPS: DeviceCaps = caps::device_caps::VIDEO_CAPTURE;
+
+    fn querycap(
+        _file: &v4l2::file::File<Self::File>,
+        _data: &<Self as video::Driver>::Data,
+        cap: &mut caps::Capabilities,
+    ) -> Result {
+        cap.set_driver(c_str!("rv4l2"))?;
+        cap.set_card(c_str!("rv4l2"))?;
+        cap.set_bus_info(c_str!("platform:rv4l2"))?;
+
+        cap.set_device_caps(Self::CAPS);
+        Ok(())
+    }
+}
+
+kernel::of_device_table!(
+    OF_TABLE,
+    MODULE_OF_TABLE,
+    <SampleDriver as platform::Driver>::IdInfo,
+    [(of::DeviceId::new(c_str!("test, rust-v4l2")), ())]
+);
+
+impl platform::Driver for SampleDriver {
+    type IdInfo = ();
+    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
+
+    fn probe(
+        pdev: &platform::Device<Core>,
+        _info: Option<&Self::IdInfo>,
+    ) -> Result<Pin<KBox<Self>>> {
+        let dev = pdev.as_ref();
+
+        let v4l2_reg =
+            v4l2::device::Registration::<Self>::new(dev, try_pin_init!(Data {}), GFP_KERNEL)?;
+
+        let video_reg = video::Registration::<Self>::new(
+            v4l2_reg.device(),
+            try_pin_init!(VideoData {}),
+            GFP_KERNEL,
+        )?;
+
+        let this = KBox::new(
+            Self {
+                _pdev: pdev.into(),
+                _v4l2_reg: v4l2_reg,
+                video_reg,
+            },
+            GFP_KERNEL,
+        )?;
+
+        dev_info!(
+            dev,
+            "Registered /dev/video{}\n",
+            this.video_reg.device().num()
+        );
+        Ok(this.into())
+    }
+
+    fn unbind(pdev: &platform::Device<Core>, _this: Pin<&Self>) {
+        dev_info!(pdev.as_ref(), "Unbinding Rust V4L2 sample driver\n");
+    }
+}
+
+impl Drop for SampleDriver {
+    fn drop(&mut self) {
+        dev_dbg!(self._pdev.as_ref(), "Rust V4L2 sample driver removed\n");
+    }
+}
+
+kernel::module_platform_driver! {
+    type: SampleDriver,
+    name: "rust_driver_v4l2",
+    authors: ["Daniel Almeida"],
+    description: "Rust V4L2 sample video driver",
+    license: "GPL v2",
+}

-- 
2.50.1
Re: [PATCH 7/7] rust: samples: add the v4l2 sample driver
Posted by Danilo Krummrich 1 month, 2 weeks ago
On Mon Aug 18, 2025 at 7:49 AM CEST, Daniel Almeida wrote:
> +/// The private data associated with the V4L2 device.
> +#[pin_data]
> +struct Data {}

I think you don't need #[pin_data] on this and the other empty structs. There
should be a blanket implementation for PinInit that got you covered.

> +/// The private data associated with a V4L2 device node, i.e. `struct
> +/// video_device`.
> +#[pin_data]
> +struct VideoData {}
> +
> +/// The private data associated with a V4L2 file, i.e. `struct v4l2_fh`.
> +#[pin_data]
> +struct File {}
> +
> +impl v4l2::file::DriverFile for File {
> +    type Driver = SampleDriver;
> +
> +    const MODULE: &'static ThisModule = &THIS_MODULE;
> +
> +    fn open(_vdev: &v4l2::video::Device<Self::Driver>) -> impl PinInit<Self, Error> {
> +        try_pin_init!(Self {})
> +    }
> +}
> +
> +struct SampleDriver {
> +    _pdev: ARef<platform::Device>,
> +    _v4l2_reg: v4l2::device::Registration<Self>,
> +    video_reg: video::Registration<Self>,

Is the drop order of those registrations relevant? (If so, it shouldn't be on
the driver to get that right.)

> +}
> +
> +impl v4l2::device::Driver for SampleDriver {
> +    type Data = Data;
> +}
> +
> +#[vtable]
> +impl video::Driver for SampleDriver {
> +    type Data = VideoData;
> +    type File = File;
> +
> +    const NODE_TYPE: video::NodeType = video::NodeType::Video;
> +    const DIRECTION: video::Direction = video::Direction::Rx;
> +    const NAME: &'static CStr = c_str!("rv4l2");
> +    const CAPS: DeviceCaps = caps::device_caps::VIDEO_CAPTURE;
> +
> +    fn querycap(
> +        _file: &v4l2::file::File<Self::File>,
> +        _data: &<Self as video::Driver>::Data,
> +        cap: &mut caps::Capabilities,
> +    ) -> Result {
> +        cap.set_driver(c_str!("rv4l2"))?;
> +        cap.set_card(c_str!("rv4l2"))?;
> +        cap.set_bus_info(c_str!("platform:rv4l2"))?;
> +
> +        cap.set_device_caps(Self::CAPS);
> +        Ok(())
> +    }
> +}
> +
> +kernel::of_device_table!(
> +    OF_TABLE,
> +    MODULE_OF_TABLE,
> +    <SampleDriver as platform::Driver>::IdInfo,
> +    [(of::DeviceId::new(c_str!("test, rust-v4l2")), ())]
> +);
> +
> +impl platform::Driver for SampleDriver {
> +    type IdInfo = ();
> +    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
> +
> +    fn probe(
> +        pdev: &platform::Device<Core>,
> +        _info: Option<&Self::IdInfo>,
> +    ) -> Result<Pin<KBox<Self>>> {
> +        let dev = pdev.as_ref();
> +
> +        let v4l2_reg =
> +            v4l2::device::Registration::<Self>::new(dev, try_pin_init!(Data {}), GFP_KERNEL)?;

As mentioned on the struct already, you shouldn't need try_pin_init!() here,
since there should be a blanket implementation for PinInit.

> +
> +        let video_reg = video::Registration::<Self>::new(
> +            v4l2_reg.device(),
> +            try_pin_init!(VideoData {}),
> +            GFP_KERNEL,
> +        )?;
> +
> +        let this = KBox::new(
> +            Self {
> +                _pdev: pdev.into(),
> +                _v4l2_reg: v4l2_reg,
> +                video_reg,
> +            },
> +            GFP_KERNEL,
> +        )?;
> +
> +        dev_info!(
> +            dev,
> +            "Registered /dev/video{}\n",
> +            this.video_reg.device().num()
> +        );
> +        Ok(this.into())
> +    }
> +
> +    fn unbind(pdev: &platform::Device<Core>, _this: Pin<&Self>) {
> +        dev_info!(pdev.as_ref(), "Unbinding Rust V4L2 sample driver\n");
> +    }
> +}
> +
> +impl Drop for SampleDriver {
> +    fn drop(&mut self) {
> +        dev_dbg!(self._pdev.as_ref(), "Rust V4L2 sample driver removed\n");

A driver being unbound / removed is the same thing.

unbind() is the correct callback for this. SampleDriver::drop() is for
additional cleanup needed for the driver's private data. It's just that this
cleanup also happens on driver unbind.

(I think I need to fix up the existing sample drivers that date from before we
had unbind() in place.)

I'd just remove this drop() implementation and the ARef<platform::Device> from
SampleDriver.

> +    }
> +}
> +
> +kernel::module_platform_driver! {
> +    type: SampleDriver,
> +    name: "rust_driver_v4l2",
> +    authors: ["Daniel Almeida"],
> +    description: "Rust V4L2 sample video driver",
> +    license: "GPL v2",
> +}
>
> -- 
> 2.50.1
Re: [PATCH 7/7] rust: samples: add the v4l2 sample driver
Posted by Elle Rhumsaa 1 month, 2 weeks ago
On Mon, Aug 18, 2025 at 02:49:53AM -0300, Daniel Almeida wrote:
> This driver is the only user of the v4l2 abstractions at the moment. It
> serves as a means to validate the abstractions by proving that the
> device is actually registered as /dev/videoX, and it can be opened and
> queried by v4l2-ctl, while also serving as a display of the current v4l2
> support in Rust, as well as a blueprint for more elaborate Rust v4l2
> drivers in the future.
> 
> Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
> ---
>  MAINTAINERS                      |   1 +
>  samples/rust/Kconfig             |  11 +++
>  samples/rust/Makefile            |   1 +
>  samples/rust/rust_driver_v4l2.rs | 145 +++++++++++++++++++++++++++++++++++++++
>  4 files changed, 158 insertions(+)
> 
> diff --git a/MAINTAINERS b/MAINTAINERS
> index 6fc5d57950e474d73d5d65271a0394efc5a8960b..14521bc0585503992da582f2cee361666985e39f 100644
> --- a/MAINTAINERS
> +++ b/MAINTAINERS
> @@ -15440,6 +15440,7 @@ L:	linux-media@vger.kernel.org
>  L:	rust-for-linux@vger.kernel.org
>  S:	Supported
>  F:	rust/media
> +F:	sample/rust/rust_driver_v4l2.rs
>  
>  MEDIATEK BLUETOOTH DRIVER
>  M:	Sean Wang <sean.wang@mediatek.com>
> diff --git a/samples/rust/Kconfig b/samples/rust/Kconfig
> index 7f7371a004ee0a8f67dca99c836596709a70c4fa..64422acf1e9da9d05f904e14fd423b3b4aef173a 100644
> --- a/samples/rust/Kconfig
> +++ b/samples/rust/Kconfig
> @@ -105,6 +105,17 @@ config SAMPLE_RUST_DRIVER_AUXILIARY
>  
>  	  If unsure, say N.
>  
> +config SAMPLE_RUST_DRIVER_V4L2
> +	tristate "Video4Linux2 driver"
> +	depends on MEDIA_SUPPORT && VIDEO_DEV
> +	help
> +	  This option builds the Rust V4L2 driver sample.
> +
> +	  To compile this as a module, choose M here:
> +	  the module will be called rust_driver_v4l2.
> +
> +	  If unsure, say N.
> +
>  config SAMPLE_RUST_HOSTPROGS
>  	bool "Host programs"
>  	help
> diff --git a/samples/rust/Makefile b/samples/rust/Makefile
> index bd2faad63b4f3befe7d1ed5139fe25c7a8b6d7f6..57e21f0373938bb70b4cb400ea550010895b4c94 100644
> --- a/samples/rust/Makefile
> +++ b/samples/rust/Makefile
> @@ -9,6 +9,7 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_PCI)		+= rust_driver_pci.o
>  obj-$(CONFIG_SAMPLE_RUST_DRIVER_PLATFORM)	+= rust_driver_platform.o
>  obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX)		+= rust_driver_faux.o
>  obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY)	+= rust_driver_auxiliary.o
> +obj-$(CONFIG_SAMPLE_RUST_DRIVER_V4L2)		+= rust_driver_v4l2.o
>  obj-$(CONFIG_SAMPLE_RUST_CONFIGFS)		+= rust_configfs.o
>  
>  rust_print-y := rust_print_main.o rust_print_events.o
> diff --git a/samples/rust/rust_driver_v4l2.rs b/samples/rust/rust_driver_v4l2.rs
> new file mode 100644
> index 0000000000000000000000000000000000000000..a3ef98a613f2fed9e8589f0761ce7e43029c02b6
> --- /dev/null
> +++ b/samples/rust/rust_driver_v4l2.rs
> @@ -0,0 +1,145 @@
> +// SPDX-License-Identifier: GPL-2.0
> +// SPDX-copyrightText: Copyright (C) 2025 Collabora Ltd.
> +
> +//! Rust V4L2 sample driver.
> +//!
> +//! This sample demonstrates how to:
> +//! - Register a V4L2 device (struct v4l2_device),
> +//! - Register a video node (struct video_device) using the Rust V4L2
> +//!   abstractions,
> +//! - Implement support for a V4L2 ioctl in a driver.
> +//!
> +//! It implements only `VIDIOC_QUERYCAP` and minimal open/close handling.
> +
> +use kernel::{
> +    c_str,
> +    device::Core,
> +    media::v4l2::{
> +        self,
> +        caps::{self, DeviceCaps},
> +        video,
> +    },
> +    of, platform,
> +    prelude::*,
> +    types::ARef,
> +    ThisModule,
> +};
> +
> +/// The private data associated with the V4L2 device.
> +#[pin_data]
> +struct Data {}
> +
> +/// The private data associated with a V4L2 device node, i.e. `struct
> +/// video_device`.
> +#[pin_data]
> +struct VideoData {}
> +
> +/// The private data associated with a V4L2 file, i.e. `struct v4l2_fh`.
> +#[pin_data]
> +struct File {}
> +
> +impl v4l2::file::DriverFile for File {
> +    type Driver = SampleDriver;
> +
> +    const MODULE: &'static ThisModule = &THIS_MODULE;
> +
> +    fn open(_vdev: &v4l2::video::Device<Self::Driver>) -> impl PinInit<Self, Error> {
> +        try_pin_init!(Self {})
> +    }
> +}
> +
> +struct SampleDriver {
> +    _pdev: ARef<platform::Device>,
> +    _v4l2_reg: v4l2::device::Registration<Self>,
> +    video_reg: video::Registration<Self>,
> +}
> +
> +impl v4l2::device::Driver for SampleDriver {
> +    type Data = Data;
> +}
> +
> +#[vtable]
> +impl video::Driver for SampleDriver {
> +    type Data = VideoData;
> +    type File = File;
> +
> +    const NODE_TYPE: video::NodeType = video::NodeType::Video;
> +    const DIRECTION: video::Direction = video::Direction::Rx;
> +    const NAME: &'static CStr = c_str!("rv4l2");
> +    const CAPS: DeviceCaps = caps::device_caps::VIDEO_CAPTURE;
> +
> +    fn querycap(
> +        _file: &v4l2::file::File<Self::File>,
> +        _data: &<Self as video::Driver>::Data,
> +        cap: &mut caps::Capabilities,
> +    ) -> Result {
> +        cap.set_driver(c_str!("rv4l2"))?;
> +        cap.set_card(c_str!("rv4l2"))?;
> +        cap.set_bus_info(c_str!("platform:rv4l2"))?;
> +
> +        cap.set_device_caps(Self::CAPS);
> +        Ok(())
> +    }
> +}
> +
> +kernel::of_device_table!(
> +    OF_TABLE,
> +    MODULE_OF_TABLE,
> +    <SampleDriver as platform::Driver>::IdInfo,
> +    [(of::DeviceId::new(c_str!("test, rust-v4l2")), ())]
> +);
> +
> +impl platform::Driver for SampleDriver {
> +    type IdInfo = ();
> +    const OF_ID_TABLE: Option<of::IdTable<Self::IdInfo>> = Some(&OF_TABLE);
> +
> +    fn probe(
> +        pdev: &platform::Device<Core>,
> +        _info: Option<&Self::IdInfo>,
> +    ) -> Result<Pin<KBox<Self>>> {
> +        let dev = pdev.as_ref();
> +
> +        let v4l2_reg =
> +            v4l2::device::Registration::<Self>::new(dev, try_pin_init!(Data {}), GFP_KERNEL)?;
> +
> +        let video_reg = video::Registration::<Self>::new(
> +            v4l2_reg.device(),
> +            try_pin_init!(VideoData {}),
> +            GFP_KERNEL,
> +        )?;
> +
> +        let this = KBox::new(
> +            Self {
> +                _pdev: pdev.into(),
> +                _v4l2_reg: v4l2_reg,
> +                video_reg,
> +            },
> +            GFP_KERNEL,
> +        )?;
> +
> +        dev_info!(
> +            dev,
> +            "Registered /dev/video{}\n",
> +            this.video_reg.device().num()
> +        );
> +        Ok(this.into())
> +    }
> +
> +    fn unbind(pdev: &platform::Device<Core>, _this: Pin<&Self>) {
> +        dev_info!(pdev.as_ref(), "Unbinding Rust V4L2 sample driver\n");
> +    }
> +}
> +
> +impl Drop for SampleDriver {
> +    fn drop(&mut self) {
> +        dev_dbg!(self._pdev.as_ref(), "Rust V4L2 sample driver removed\n");
> +    }
> +}
> +
> +kernel::module_platform_driver! {
> +    type: SampleDriver,
> +    name: "rust_driver_v4l2",
> +    authors: ["Daniel Almeida"],
> +    description: "Rust V4L2 sample video driver",
> +    license: "GPL v2",
> +}
> 
> -- 
> 2.50.1

Reviewed-by: Elle Rhumsaa <elle@weathered-steel.dev>