rust: input: add input/serio abstractions and port Gravis Stinger driver
Subsystems (3)
v3 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 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: eliminated race condition in connect_callback(): initialized driver state in T::init(), set drvdata prior to serio_open(), and published input devices in T::start().
- serio: integrated serio::Device with kernel device abstractions via AsBusDevice, impl_device_context_deref!, and as_device().
- serio: mapped IrqReturn variants to C irqreturn_t constants.
- 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.
- stinger: formatted imports vertically and fixed line-length warnings.
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 | 5 +- drivers/input/joystick/stinger_rust.rs | 179 +++++++++++++++ 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 | 248 ++++++++++++++++++++ rust/kernel/lib.rs | 4 + rust/kernel/serio.rs | 301 +++++++++++++++++++++++++ 10 files changed, 792 insertions(+), 2 deletions(-) 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
PATCH v3 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 | 248 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 5 files changed, 274 insertions(+) create mode 100644 rust/helpers/input.c create mode 100644 rust/kernel/input.rs
rust/bindings/bindings_helper.h +1 -0
@@ -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
@@ -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
@@ -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 +248 -0
248 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -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
PATCH v3 2/2 rust: serio: add serio bus abstractions and port Gravis Stinger driver
In reply to clicedvly768Add 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 | 5 +- drivers/input/joystick/stinger_rust.rs | 179 +++++++++++++++ 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 | 301 +++++++++++++++++++++++++ 8 files changed, 518 insertions(+), 2 deletions(-) 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
@@ -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 -2
@@ -10,9 +10,7 @@ obj-$(CONFIG_JOYSTICK_ADC) += adc-joystick.o obj-$(CONFIG_JOYSTICK_ADI) += adi.o obj-$(CONFIG_JOYSTICK_AMIGA) += amijoy.o obj-$(CONFIG_JOYSTICK_AS5011) += as5011.o -obj-$(CONFIG_JOYSTICK_ANALOG) += analog.o obj-$(CONFIG_JOYSTICK_COBRA) += cobra.o -obj-$(CONFIG_JOYSTICK_DB9) += db9.o obj-$(CONFIG_JOYSTICK_FSIA6B) += fsia6b.o obj-$(CONFIG_JOYSTICK_GAMECON) += gamecon.o obj-$(CONFIG_JOYSTICK_GF2K) += gf2k.o
@@ -33,6 +31,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 +179 -0
179 lines not on this page · raw message
rust/bindings/bindings_helper.h +1 -0
@@ -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
@@ -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
@@ -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
@@ -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 +301 -0
301 lines not on this page · raw message
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH v3 1/2] rust: input: add input device abstractions
In reply to clicedvly768Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Low] rust: input: non-vertical crate import formatting in input.rs --
Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Low] rust: input: non-vertical crate import formatting in input.rs --
commit d03870e71b5fd937f97b178433700c90c89f7646
Author: clicedvly768 <[email protected]>
rust: input: add input device abstractions
This commit adds safe Rust abstractions for Linux input devices, including AllocatedDevice for pre-registration configuration and RegisteredDevice for event reporting and cleanup.
Quoted 6 lines
rust/kernel/input.rs new file +0
-0
rust/kernel/input.rs line 8
Quoted 8 lines
rust/kernel/input.rs new file +8
-0@@ -0,0 +1,248 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Input subsystem abstractions for safe Rust drivers. +//! +//! Provides a safe Rust object-oriented interface around Linux `struct input_dev`, +//! ensuring safe allocation, capability configuration, registration, and RAII cleanup. + +use crate ::{bindings, device, error::to_result, prelude::*};
[Severity: Low]
This isn't a bug, but multi-item crate imports in kernel Rust code should use the vertical layout with a trailing empty comment (//) per Documentation/rust/coding-guidelines.rst so rustfmt keeps each imported item on its own line.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
[email protected]
AI reviewRe: [PATCH v3 2/2] rust: serio: add serio bus abstractions and port Gravis Stinger driver
In reply to clicedvly768Thank you for your contribution! Sashiko AI review found 5 potential issues to consider: - [High] Input: joystick - unintended removal of analog.o and db9.o from Makefile - [High] rust: serio…
Thank you for your contribution! Sashiko AI review found 5 potential issues to consider:
- [High] Input: joystick - unintended removal of analog.o and db9.o from Makefile
- [High] rust: serio: concurrent borrow_mut() and data race between start() and interrupt()
- [Medium] rust: serio: non-existent bindings::irqreturn::IRQ_* paths in interrupt_callback()
- [Low] rust: serio: non-vertical import style in serio.rs and stinger_rust.rs
- [Low] rust: serio: missing #[inline] on Registration::drop() and Driver defaults
--
commit 26aa0ef3bea4ec16308e3ef9c8b5857b4bc682ad
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.
drivers/input/joystick/Makefile obj-$(CONFIG_JOYSTICK_ADC) += adc-joystick.o · line 14
Quoted 12 lines
drivers/input/joystick/Makefile +0
-2@@ -10,9 +10,7 @@ obj-$(CONFIG_JOYSTICK_ADC) += adc-joystick.o obj-$(CONFIG_JOYSTICK_ADI) += adi.o obj-$(CONFIG_JOYSTICK_AMIGA) += amijoy.o obj-$(CONFIG_JOYSTICK_AS5011) += as5011.o -obj-$(CONFIG_JOYSTICK_ANALOG) += analog.o obj-$(CONFIG_JOYSTICK_COBRA) += cobra.o -obj-$(CONFIG_JOYSTICK_DB9) += db9.o obj-$(CONFIG_JOYSTICK_FSIA6B) += fsia6b.o
[Severity: High]
Were the build rules for analog.o and db9.o removed by mistake? Dropping these lines causes builds with CONFIG_JOYSTICK_ANALOG or CONFIG_JOYSTICK_DB9 enabled to stop compiling both drivers.
[ ... ]
Quoted 13 lines
rust/kernel/serio.rs new file +7
-0@@ -0,0 +1,301 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Serio (Serial I/O) bus abstractions for safe Rust drivers. +//! +//! Provides a safe Rust interface for serio devices and drivers in the Linux kernel, +//! supporting input devices such as serial gamepads (e.g. Gravis Stinger), mice, and keyboards. +
rust/kernel/serio.rs line 17
Quoted 10 lines
rust/kernel/serio.rs new file +10
-0+use crate ::{ + bindings, device, + device_id::{IdTable as GenericIdTable ,RawDeviceId }, + error::{to_result,Result }, + ffi::{c_int, c_uchar, c_uint}, + prelude::*, + types::{ForeignOwnable ,Opaque }, +ThisModule , +}; +use core::{marker::PhantomData , pin::Pin };
[Severity: Low]
This isn't a bug, but the imports here and in drivers/input/joystick/stinger_rust.rs group multiple items on a single line instead of using the kernel Rust vertical import style with one item per line and a trailing // comment.
[ ... ]
Quoted 38 lines
rust/kernel/serio.rs new file +38
-0+// 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. +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; + } + +// 4. Start driver and publish devices now that port is open and interrupts are active. +// SAFETY: `raw_data` was created via `into_foreign()` above and remains valid. +let mut borrowed =unsafe { <T ::Data as ForeignOwnable >::borrow_mut (raw_data) }; +if let Err (e) =T ::start (&mut borrowed) { +// SAFETY: Close port and clean up on start failure. +unsafe { + bindings::serio_close (serio); + bindings::serio_set_drvdata (serio, core::ptr::null_mut ()); +let data = <T ::Data as ForeignOwnable >::from_foreign (raw_data); +T ::disconnect (data); + } +return e.to_errno (); + } + +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,
rust/kernel/serio.rs line 261
Quoted 10 lines
rust/kernel/serio.rs new file +10
-0+ ) -> bindings::irqreturn_t { +// SAFETY: `serio` is valid. +let raw =unsafe { bindings::serio_get_drvdata (serio) }; +if raw.is_null () { +return bindings::irqreturn::IRQ_NONE ; + } + +// 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);
[Severity: High]
Can Registration::interrupt_callback() and Registration::connect_callback() call ForeignOwnable::borrow_mut() on raw_data at the same time?
Once bindings::serio_open() returns in connect_callback(), port interrupts are enabled while connect_callback() runs T::start(&mut borrowed) in process context without holding serio->lock:
CPU0 CPU1 (<hardirq>)Registration::connect_callback()
bindings::serio_open(serio, drv) ForeignOwnable::borrow_mut(raw_data) StingerDriver::start(&mut borrowed)
alloc.register()
Registration::interrupt_callback()
ForeignOwnable::borrow_mut(raw) StingerDriver::interrupt()
stinger.process_packet()
self.input.as_ref()
stinger.input = Some(...) <-- aliasing &mut / data race
This creates two concurrent mutable references to Stinger (undefined behavior in Rust) and races the unsynchronized write to stinger.input in StingerDriver::start() against reads of self.input in Stinger::process_packet(), allowing a torn read of RegisteredDevice.
In addition, on the T::start() error path, ForeignOwnable::from_foreign(raw_data) is called while borrowed is still in scope, violating the ForeignOwnable::borrow_mut() safety requirement that all borrows end before from_foreign() is called.
rust/kernel/serio.rs line 266
Quoted 5 lines
rust/kernel/serio.rs new file +5
-0+match ret { +IrqReturn ::None => bindings::irqreturn::IRQ_NONE , +IrqReturn ::Handled => bindings::irqreturn::IRQ_HANDLED , + } + }
[Severity: Medium]
Does bindings::irqreturn::IRQ_NONE compile when CONFIG_SERIO=y is enabled? Bindgen generates bindings::irqreturn as a type alias for c_uint and emits top-level constants bindings::irqreturn_IRQ_NONE and bindings::irqreturn_IRQ_HANDLED (as used in rust/kernel/irq/request.rs), so referencing associated constants on bindings::irqreturn fails to build.
[ ... ]
rust/kernel/serio.rs line 296
Quoted 8 lines
rust/kernel/serio.rs new file +8
-0+impl <T :Driver >Drop for Registration <T > { +fn drop (&mut self) { +// SAFETY: Unregister driver with kernel. `self.drv` is valid and registered. +unsafe { + bindings::serio_unregister_driver (self.drv.get ()); + } + } +}
[Severity: Low]
Should Registration::drop() and the default methods Driver::start() and Driver::disconnect() be marked #[inline]? In the kernel crate, small functions and functions that forward directly to a C binding call are annotated with #[inline].
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2