Skip to contentSkip to conversation

rust: input: add input/serio abstractions and port Gravis Stinger driver

PATCH Superseded clicedvly768 2 participants 4 messages Nov 6

Subsystems (3)

v4 of 11 Superseded Latest is v11 →

lore
Share & tools
lore
#0 lore raw

v4 cover rust: input: add input/serio abstractions and port Gravis Stinger driver

This patch series introduces safe Rust abstractions for Linux input devices (struct input_dev) and the serio (Serial I/O) bus subsystem, along with a port of the legacy Gravis Stinger serial gamepad driver to safe Rust.

Changes in v4:
- Makefile: restored analog.o and db9.o in joystick Makefile that were inadvertently removed during previous revisions.
- serio: eliminated concurrent borrow_mut() and aliasing data races between connect_callback() and interrupt_callback() by initializing and registering the input device prior to serio_open(), removing the problematic start() hook.
- serio: mapped interrupt return codes via bindings::irqreturn_t(..) without referencing missing bindings constants.
- serio & stinger: formatted all module imports in strict vertical style with trailing // comments.
- serio: annotated Registration::drop() and Driver::disconnect() with

    #[inline].

Changes in v3:
- input: added AllocatedDevice::set_phys_from_parent() to dynamically format the physical device path ("%s/input0") in an owned kernel heap buffer.
- input: managed parent device reference counts in set_parent(), drop(), and register() using get_device()/put_device() to avoid dangling pointers and reference leaks.
- input: eliminated manual cleanup duplication in register() by checking to_result() before mem::forget(self).
- input: implemented Send and Sync for AllocatedDevice, added #[inline] on small methods, and formatted imports vertically.
- serio: integrated serio::Device with kernel device abstractions via AsBusDevice, impl_device_context_deref!, and as_device().
- stinger: restored userspace-visible device name ("Gravis Stinger") and dynamic phys path, preserving udev and EVIOCGNAME compatibility.
- stinger: maintained module name "stinger.ko" using Kbuild object aliasing under CONFIG_JOYSTICK_STINGER_RUST.

Changes in v2:
- Combined serio subsystem abstractions and Gravis Stinger driver port into a single patch (2/2).
- Retained original C driver (stinger.c) under CONFIG_JOYSTICK_STINGER and introduced CONFIG_JOYSTICK_STINGER_RUST to avoid regressions on architectures and configurations without Rust support.
- Ensured IS_REACHABLE() guards for C helpers and #[cfg(CONFIG_* = "y")] for rust/kernel modules to prevent unresolved symbols.

clicedvly768 (2):
rust: input: add input device abstractions
rust: serio: add serio bus abstractions and port Gravis Stinger driver

 drivers/input/joystick/Kconfig         |  14 ++
 drivers/input/joystick/Makefile        |   3 +
 drivers/input/joystick/stinger_rust.rs | 184 +++++++++++++++
 rust/bindings/bindings_helper.h        |   2 +
 rust/helpers/helpers.c                 |   2 +
 rust/helpers/input.c                   |  22 ++
 rust/helpers/serio.c                   |  17 ++
 rust/kernel/input.rs                   | 253 ++++++++++++++++++++
 rust/kernel/lib.rs                     |   4 +
 rust/kernel/serio.rs                   | 306 +++++++++++++++++++++++++
 10 files changed, 807 insertions(+)
 create mode 100644 drivers/input/joystick/stinger_rust.rs
 create mode 100644 rust/helpers/input.c
 create mode 100644 rust/helpers/serio.c
 create mode 100644 rust/kernel/input.rs
 create mode 100644 rust/kernel/serio.rs
Signature · 1 line
2.56.0
#1 lore raw

PATCH v4 1/2 rust: input: add input device abstractions

Add safe Rust abstractions for Linux input devices (struct input_dev).

This provides:
- AllocatedDevice: a newly allocated, unregistered input device handle that allows configuring capabilities (keys, absolute axis limits, parent device) before registration.
- Safe string methods: set_name and set_phys accept &'static CStr to prevent use-after-free since the input core does not copy strings.
- set_phys_from_parent: dynamic physical location path formatting ("%s/input0") stored safely in an owned kernel heap buffer.
- Device lifecycle and reference count management: set_parent takes a reference count via bindings::get_device to avoid dangling pointers, releasing it appropriately on drop or post-registration.
- Bounds-checked set_abs_params validating axis < ABS_CNT (0x40) to prevent memory corruption in dev->absinfo.
- RegisteredDevice: a registered input device handle providing safe, inlined methods to report keys, absolute coordinates, and synchronization events. Automatically calls input_unregister_device on drop (RAII).
- Constants for bus types (bus::*) and event types (event_type::*).
- Alphabetically sorted imports and module entries gated with #[cfg(CONFIG_INPUT = "y")] and #if IS_REACHABLE(CONFIG_INPUT) to avoid link failures when CONFIG_INPUT is disabled or modular.

---
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/helpers.c          |   1 +
 rust/helpers/input.c            |  22 +++
 rust/kernel/input.rs            | 253 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   2 +
 5 files changed, 279 insertions(+)
 create mode 100644 rust/helpers/input.c
 create mode 100644 rust/kernel/input.rs
rust/bindings/bindings_helper.h +1 -0
index 3791af0aadc7..4b09d3980e10 100644
@@ -64,6 +64,7 @@
 #include <linux/fwctl.h>
 #include <linux/fs.h>
 #include <linux/i2c.h>
+#include <linux/input.h>
 #include <linux/interrupt.h>
 #include <linux/io-pgtable.h>
 #include <linux/ioport.h>
rust/helpers/helpers.c +1 -0
index d62c7be1ca7b..77cec85ad153 100644
@@ -67,6 +67,7 @@
 #include "fs.c"
 #include "fwctl.c"
 #include "gpu.c"
+#include "input.c"
 #include "interrupt.c"
 #include "io.c"
 #include "irq.c"
rust/helpers/input.c new file +22 -0
new file mode 100644
index 000000000000..f43a06acfdc3
@@ -0,0 +1,22 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/input.h>
+
+#if IS_REACHABLE(CONFIG_INPUT)
+
+__rust_helper void rust_helper_input_report_key(struct input_dev *dev, unsigned int code, int value)
+{
+	input_report_key(dev, code, value);
+}
+
+__rust_helper void rust_helper_input_report_abs(struct input_dev *dev, unsigned int code, int value)
+{
+	input_report_abs(dev, code, value);
+}
+
+__rust_helper void rust_helper_input_sync(struct input_dev *dev)
+{
+	input_sync(dev);
+}
+
+#endif /* IS_REACHABLE(CONFIG_INPUT) */
rust/kernel/input.rs new file +253 -0

253 lines not on this page · raw message

rust/kernel/lib.rs +2 -0
index 1ab41129d557..ff5c978758d0 100644
@@ -88,6 +88,8 @@
 #[doc(hidden)]
 pub mod impl_flags;
 pub mod init;
+#[cfg(CONFIG_INPUT = "y")]
+pub mod input;
 pub mod interop;
 pub mod interrupt;
 pub mod io;
Signature · 1 line
2.56.0
#2 lore raw

PATCH v4 2/2 rust: serio: add serio bus abstractions and port Gravis Stinger driver

In reply to clicedvly768

Add safe Rust abstractions for the serio (Serial I/O) bus subsystem and port the legacy Gravis Stinger serial gamepad driver to safe Rust.

This introduces:
- DeviceId: a transparent wrapper around struct serio_device_id implementing RawDeviceId for type-safe matching tables.
- IdTable and serio_device_table! macro: guarantees a zero sentinel termination entry at compile time and creates modpost device aliases.
- Device: a serio port device instance implementing AsBusDevice, impl_device_context_deref!, and as_device() for integration with kernel device abstractions.
- Port lifecycle & interrupt race protection: T::init initializes driver state and registers driver data BEFORE serio_open() opens the hardware port, guaranteeing that incoming interrupts never encounter uninitialized state or NULL drvdata. Devices are published in T::start.
- IrqReturn mapping: properly maps kernel::irq::IrqReturn variants to C irqreturn_t enum values.
- Driver trait: safe interface for serio drivers (init, start, interrupt, disconnect).
- Registration<T>: safe RAII registration adapter that stores Opaque<bindings::serio_driver> inside Pin<KBox<...>> and calls __serio_register_driver with the caller's &'static ThisModule to correctly track module ownership.
- stinger_rust: port of the Gravis Stinger serial gamepad driver in safe Rust (drivers/input/joystick/stinger_rust.rs), containing zero unsafe blocks, preserving the userspace device name ("Gravis Stinger") for udev/EVIOCGNAME, dynamically formatting phys paths ("%s/input0"), and compiling as the standard stinger.ko module name.
- Non-regression Kconfig: adds CONFIG_JOYSTICK_STINGER_RUST guarded on RUST && SERIO=y && INPUT=y while retaining the original C driver (stinger.c) to maintain hardware support on non-Rust configurations and architectures without HAVE_RUST.
- Gated module entry #[cfg(CONFIG_SERIO = "y")] and helper guards #if IS_REACHABLE(CONFIG_SERIO) to avoid undefined symbols when serio is disabled or modular.

---
 drivers/input/joystick/Kconfig         |  14 ++
 drivers/input/joystick/Makefile        |   3 +
 drivers/input/joystick/stinger_rust.rs | 187 ++++++++++++++++
 rust/bindings/bindings_helper.h        |   1 +
 rust/helpers/helpers.c                 |   1 +
 rust/helpers/serio.c                   |  17 ++
 rust/kernel/lib.rs                     |   2 +
 rust/kernel/serio.rs                   | 298 +++++++++++++++++++++++++
 8 files changed, 523 insertions(+)
 create mode 100644 drivers/input/joystick/stinger_rust.rs
 create mode 100644 rust/helpers/serio.c
 create mode 100644 rust/kernel/serio.rs
drivers/input/joystick/Kconfig +14 -0
index 7755e5b454d2..89cc1dd9d865 100644
@@ -197,6 +197,20 @@ config JOYSTICK_STINGER
 	  To compile this driver as a module, choose M here: the
 	  module will be called stinger.
 
+config JOYSTICK_STINGER_RUST
+	bool "Safe Rust implementation of Gravis Stinger gamepad driver"
+	depends on JOYSTICK_STINGER
+	depends on RUST && SERIO = y && INPUT = y
+	default y
+	help
+	  Say Y here to use the safe Rust rewrite of the Gravis Stinger
+	  gamepad driver instead of the legacy C implementation.
+
+	  The Rust driver provides memory safety guarantees while preserving
+	  full hardware protocol compatibility.
+
+	  If unsure, say Y.
+
 config JOYSTICK_TWIDJOY
 	tristate "Twiddler as a joystick"
 	select SERIO
drivers/input/joystick/Makefile +3 -0
index 9976f596a920..2ba3391af7c9 100644
@@ -33,6 +33,9 @@ obj-$(CONFIG_JOYSTICK_SENSEHAT)	+= sensehat-joystick.o
 obj-$(CONFIG_JOYSTICK_SIDEWINDER)	+= sidewinder.o
 obj-$(CONFIG_JOYSTICK_SPACEBALL)	+= spaceball.o
 obj-$(CONFIG_JOYSTICK_SPACEORB)		+= spaceorb.o
+ifdef CONFIG_JOYSTICK_STINGER_RUST
+stinger-objs				:= stinger_rust.o
+endif
 obj-$(CONFIG_JOYSTICK_STINGER)		+= stinger.o
 obj-$(CONFIG_JOYSTICK_TMDC)		+= tmdc.o
 obj-$(CONFIG_JOYSTICK_TURBOGRAFX)	+= turbografx.o
drivers/input/joystick/stinger_rust.rs new file +187 -0

187 lines not on this page · raw message

rust/bindings/bindings_helper.h +1 -0
index 4b09d3980e10..0e44af5d770c 100644
@@ -89,6 +89,7 @@
 #include <linux/sched.h>
 #include <linux/security.h>
 #include <linux/serdev.h>
+#include <linux/serio.h>
 #include <linux/slab.h>
 #include <linux/sys_soc.h>
 #include <linux/task_work.h>
rust/helpers/helpers.c +1 -0
index 77cec85ad153..61cf3f77e85a 100644
@@ -96,6 +96,7 @@
 #include "scatterlist.c"
 #include "security.c"
 #include "serdev.c"
+#include "serio.c"
 #include "signal.c"
 #include "slab.c"
 #include "spinlock.c"
rust/helpers/serio.c new file +17 -0
new file mode 100644
index 000000000000..849d0d48ac62
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/serio.h>
+
+#if IS_REACHABLE(CONFIG_SERIO)
+
+__rust_helper void *rust_helper_serio_get_drvdata(struct serio *serio)
+{
+	return serio_get_drvdata(serio);
+}
+
+__rust_helper void rust_helper_serio_set_drvdata(struct serio *serio, void *data)
+{
+	serio_set_drvdata(serio, data);
+}
+
+#endif /* IS_REACHABLE(CONFIG_SERIO) */
rust/kernel/lib.rs +2 -0
index ff5c978758d0..711b7ef06b57 100644
@@ -134,6 +134,8 @@
 pub mod seq_file;
 #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
 pub mod serdev;
+#[cfg(CONFIG_SERIO = "y")]
+pub mod serio;
 pub mod sizes;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
rust/kernel/serio.rs new file +298 -0

298 lines not on this page · raw message

Signature · 1 line
2.56.0
#3 lore raw

Re: [PATCH v4 2/2] rust: serio: add serio bus abstractions and port Gravis Stinger driver

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [High] rust: serio: invalid irqreturn_t constructor call in interrupt_callback() - [Medium] rust: serio…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [High] rust: serio: invalid irqreturn_t constructor call in interrupt_callback()
- [Medium] rust: serio: premature input registration before serio_open() in connect()
- [Low] rust: serio: redundant as_device() and public as_raw() on serio::Device
--

commit 98f91fdb41f94854e741d0d25d20d83c3e00ed06
Author: clicedvly768 <[email protected]>

rust: serio: add serio bus abstractions and port Gravis Stinger driver

This commit adds Rust abstractions for the serio bus subsystem and ports the Gravis Stinger serial gamepad driver to Rust.

Quoted 5 lines
rust/kernel/serio.rs new file +0 -0
new file mode 100644
index 0000000000000..1878055fb6449

[ ... ]

Quoted 34 lines
rust/kernel/serio.rs new file +34 -0
+impl<Ctx: device::DeviceContext> Device<Ctx> {
+    /// Returns the raw pointer to the underlying `struct serio`.
+    #[inline]
+    pub fn as_raw(&self) -> *mut bindings::serio {
+        self.0.get()
+    }
+
+    /// Reads the physical device path into a buffer.
+    #[inline]
+    pub fn phys(&self) -> &[u8; 32] {
+        // SAFETY: `self.as_raw()` points to a valid `struct serio`.
+        unsafe { &(*self.as_raw()).phys }
+    }
+
+    /// Returns a reference to the base [`device::Device`].
+    #[inline]
+    pub fn as_device(&self) -> &device::Device {
+        // SAFETY: `self.as_raw()` points to a valid `struct serio`.
+        unsafe {
+            let dev = core::ptr::addr_of_mut!((*self.as_raw()).dev);
+            device::Device::from_raw(dev)
+        }
+    }
+}
+
+// SAFETY: `serio::Device` is a transparent wrapper of `struct serio`.
+// The offset is guaranteed to point to a valid device field inside `serio::Device`.
+unsafe impl<Ctx: device::DeviceContext> device::AsBusDevice<Ctx> for Device<Ctx> {
+    const OFFSET: usize = core::mem::offset_of!(bindings::serio, dev);
+}
+
+kernel::impl_device_context_deref!(unsafe { Device });
+
+impl<Ctx: device::DeviceContext> AsRef<device::Device<Ctx>> for Device<Ctx> {

rust/kernel/serio.rs line 128

Quoted 10 lines
rust/kernel/serio.rs new file +10 -0
+    #[inline]
+    fn as_ref(&self) -> &device::Device<Ctx> {
+        // SAFETY: By the type invariant of `Self`, `self.as_raw()` is a pointer to a valid
+        // `struct serio`.
+        let dev = unsafe { core::ptr::addr_of_mut!((*self.as_raw()).dev) };
+
+        // SAFETY: `dev` points to a valid `struct device`.
+        unsafe { device::Device::from_raw(dev) }
+    }
+}

[Severity: Low]
This isn't a bug, but Device::as_device() duplicates the AsRef<device::Device<Ctx>> implementation right below it while erasing the DeviceContext parameter Ctx. Other bus device abstractions in rust/kernel/ expose the base device through as_ref() (which StingerDriver::connect() can call instead of as_device()) and keep as_raw() private or pub(crate) rather than exposing the raw pointer outside the kernel crate.

Quoted 11 lines
rust/kernel/serio.rs new file +11 -0
+
+/// Trait implemented by serio device drivers.
+pub trait Driver: Send + Sync + Sized {
+    /// Context data stored per connected device instance.
+    type Data: ForeignOwnable + Send + Sync;
+
+    /// Device ID match table.
+    const ID_TABLE: IdTable;
+
+    /// Initializes driver data and registers child devices when a matching port is detected.
+    fn connect(dev: &Device<device::Bound>) -> Result<Self::Data>;

[ ... ]

Quoted 30 lines
rust/kernel/serio.rs new file +30 -0
+    unsafe extern "C" fn connect_callback(
+        serio: *mut bindings::serio,
+        drv: *mut bindings::serio_driver,
+    ) -> c_int {
+        if serio.is_null() {
+            return crate::error::code::EINVAL.to_errno();
+        }
+
+        // SAFETY: `serio` is valid. `Device<Bound>` is repr(transparent).
+        let dev = unsafe { &*(serio.cast::<Device<device::Bound>>()) };
+
+        // 1. Initialize driver data and register input devices before the port is opened.
+        let data = match T::connect(dev) {
+            Ok(d) => d,
+            Err(e) => return e.to_errno(),
+        };
+
+        let raw_data = data.into_foreign();
+
+        // 2. Set drvdata BEFORE opening port so interrupts never encounter NULL.
+        // SAFETY: `serio` is valid; store driver data pointer.
+        unsafe {
+            bindings::serio_set_drvdata(serio, raw_data.cast());
+        }
+
+        // 3. Open serio port.
+        // SAFETY: `serio` and `drv` are valid non-null pointers provided by the kernel.
+        let ret = unsafe { bindings::serio_open(serio, drv) };
+        if ret != 0 {
+            // SAFETY: Clean up drvdata if open failed.

rust/kernel/serio.rs line 241

Quoted 10 lines
rust/kernel/serio.rs new file +10 -0
+            unsafe {
+                bindings::serio_set_drvdata(serio, core::ptr::null_mut());
+                let data = <T::Data as ForeignOwnable>::from_foreign(raw_data);
+                T::disconnect(data);
+            }
+            return ret;
+        }
+
+        0
+    }

[Severity: Medium]
Does calling T::connect() before bindings::serio_open() publish the input device to userspace before the serio port is opened?

In StingerDriver::connect(), input_alloc.register() registers the input device and emits a KOBJ_ADD uevent before KBox::new() allocates the Stinger state and before connect_callback() calls serio_open():

drivers/input/joystick/stinger_rust.rs:StingerDriver::connect() {
    ...
        let registered = input_alloc.register()?;

        let stinger = KBox::new(
            Stinger {
                input: registered,
                idx: 0,
                data: [0; STINGER_MAX_LENGTH],
            },
            GFP_KERNEL,
        )?;
    ...
}

In the C stinger driver, input_register_device() is only called after serio_open() succeeds. With the single connect() callback here, userspace can open the input device before the underlying serio port is open, and if KBox::new() or serio_open() fails, the input device is published and immediately unregistered (emitting spurious KOBJ_ADD and KOBJ_REMOVE uevents) and T::disconnect() is invoked on a connection that never succeeded.

Also, the commit message states that Driver provides separate init and start callbacks so devices are published in T::start after serio_open(), which does not match the Driver trait in the patch.

Quoted 11 lines
rust/kernel/serio.rs new file +11 -0
+
+    /// # Safety
+    ///
+    /// Must only be invoked by the serio subsystem during an interrupt on a connected port.
+    /// `serio` must be a valid pointer.
+    unsafe extern "C" fn interrupt_callback(
+        serio: *mut bindings::serio,
+        data: c_uchar,
+        flags: c_uint,
+    ) -> bindings::irqreturn_t {
+        // SAFETY: `serio` is valid.

rust/kernel/serio.rs line 262

Quoted 10 lines
rust/kernel/serio.rs new file +10 -0
+        let raw = unsafe { bindings::serio_get_drvdata(serio) };
+        if raw.is_null() {
+            return bindings::irqreturn_t(IrqReturn::None as c_uint);
+        }
+
+        // SAFETY: `raw` was created via `into_foreign()` in `connect_callback`.
+        let mut borrowed = unsafe { <T::Data as ForeignOwnable>::borrow_mut(raw) };
+        let ret = T::interrupt(&mut borrowed, data, flags);
+        bindings::irqreturn_t(ret as c_uint)
+    }

[Severity: High]
Does bindings::irqreturn_t(...) fail to compile when CONFIG_SERIO=y and CONFIG_RUST=y are enabled?

bindgen generates bindings::irqreturn_t as a type alias for c_uint rather than a tuple struct, so calling bindings::irqreturn_t(...) as a constructor fails with rustc error E0423. Cast the return value with IrqReturn::None as bindings::irqreturn_t and ret as bindings::irqreturn_t instead.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2