Linux Input/HID development
 help / color / mirror / Atom feed
* [PATCH 0/3] rust: input: add input/serio abstractions and port Gravis Stinger driver
@ 2026-11-06 19:17 clicedvly768
  2026-11-06 19:17 ` [PATCH 1/3] rust: input: add input device abstractions clicedvly768
                   ` (2 more replies)
  0 siblings, 3 replies; 7+ messages in thread
From: clicedvly768 @ 2026-11-06 19:17 UTC (permalink / raw)
  To: ojeda, dmitry.torokhov; +Cc: rust-for-linux, linux-input, clicedvly768

This series introduces safe Rust abstractions for the Linux input and
serio (Serial I/O) subsystems and demonstrates their real-world usage
by porting the legacy Gravis Stinger serial gamepad driver from C to
safe Rust.

Motivation and Design:
- In the Rust for Linux (RfL) philosophy, device drivers should not rely
  on raw FFI and unsafe blocks. Instead, the kernel crate provides safe,
  idiomatic Rust abstractions.
- The Gravis Stinger gamepad is an ideal candidate for demonstrating safe
  Rust driver development in the input subsystem: it uses a well-defined
  4-byte serial protocol at 9600 baud, 10 buttons, and 2 analog axes.
- The ported driver (`drivers/input/joystick/stinger.rs`) contains ZERO
  unsafe blocks, using RAII types (`AllocatedDevice`, `RegisteredDevice`,
  `serio::Registration`) for memory safety and device lifetime management.

Testing:
- Built with Clang/LLVM and rustc 1.99.1.
- Passes all strict kernel Rust checks: `make rustfmtcheck`,
  `make rustdoc`,
  and `make CLIPPY=1` with zero warnings.
- Tested end-to-end in a custom QEMU virtual test environment with serial
  port loopback (`serport` line discipline `N_MOUSE` and `SERIO_STINGER`).
- Verified event reporting (`EV_KEY`, `EV_ABS`, `EV_SYN`) via `evtest`
  and an automated Python protocol test suite across all 10 buttons and
  both axes (-64..64).

Structure of the series:
1. Patch 1: Add input device abstractions (`kernel::input`).
2. Patch 2: Add serio bus abstractions (`kernel::serio`).
3. Patch 3: Port `drivers/input/joystick/stinger.c` to `stinger.rs`.

clicedvly768 (3):
  rust: input: add input device abstractions
  rust: serio: add serio bus abstractions
  input: joystick: stinger: port Gravis Stinger driver to safe Rust

 drivers/input/joystick/Kconfig    |   1 +
 drivers/input/joystick/stinger.c  | 191 -------------------------
 drivers/input/joystick/stinger.rs | 174 +++++++++++++++++++++++
 rust/bindings/bindings_helper.h   |   2 +
 rust/helpers/helpers.c            |   2 +
 rust/helpers/input.c              |  18 +++
 rust/helpers/serio.c              |  23 +++
 rust/kernel/input.rs              | 174 +++++++++++++++++++++++
 rust/kernel/lib.rs                |   2 +
 rust/kernel/serio.rs              | 223 ++++++++++++++++++++++++++++++
 10 files changed, 619 insertions(+), 191 deletions(-)
 delete mode 100644 drivers/input/joystick/stinger.c
 create mode 100644 drivers/input/joystick/stinger.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

-- 
2.56.0

^ permalink raw reply	[flat|nested] 7+ messages in thread

* [PATCH 1/3] rust: input: add input device abstractions
  2026-11-06 19:17 [PATCH 0/3] rust: input: add input/serio abstractions and port Gravis Stinger driver clicedvly768
@ 2026-11-06 19:17 ` clicedvly768
  2026-11-06 19:29   ` sashiko-bot
  2026-11-06 19:17 ` [PATCH 2/3] rust: serio: add serio bus abstractions clicedvly768
  2026-11-06 19:17 ` [PATCH 3/3] input: joystick: stinger: port Gravis Stinger driver to safe Rust clicedvly768
  2 siblings, 1 reply; 7+ messages in thread
From: clicedvly768 @ 2026-11-06 19:17 UTC (permalink / raw)
  To: ojeda, dmitry.torokhov; +Cc: rust-for-linux, linux-input, clicedvly768

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 axes limits)
  before registration.
- `RegisteredDevice`: a registered input device handle providing safe
  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::*`).
- C helper wrappers for inline static functions in <linux/input.h>.

Signed-off-by: clicedvly768 <harepro29@gmail.com>
---
 rust/bindings/bindings_helper.h |   1 +
 rust/helpers/helpers.c          |   1 +
 rust/helpers/input.c            |  18 ++++
 rust/kernel/input.rs            | 174 ++++++++++++++++++++++++++++++++
 rust/kernel/lib.rs              |   1 +
 5 files changed, 195 insertions(+)
 create mode 100644 rust/helpers/input.c
 create mode 100644 rust/kernel/input.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 3791af0aadc7..301c75cfeb61 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -171,3 +171,4 @@ const unsigned long RUST_CONST_HELPER_GPU_BUDDY_TRIM_DISABLE = GPU_BUDDY_TRIM_DI
 #include "../../drivers/android/binder/rust_binder.h"
 #include "../../drivers/android/binder/rust_binder_events.h"
 #endif
+#include <linux/input.h>
diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
index d62c7be1ca7b..0bc33a7b4351 100644
--- a/rust/helpers/helpers.c
+++ b/rust/helpers/helpers.c
@@ -109,3 +109,4 @@
 #include "wait.c"
 #include "workqueue.c"
 #include "xarray.c"
+#include "input.c"
diff --git a/rust/helpers/input.c b/rust/helpers/input.c
new file mode 100644
index 000000000000..531733d32f9c
--- /dev/null
+++ b/rust/helpers/input.c
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/input.h>
+
+__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);
+}
diff --git a/rust/kernel/input.rs b/rust/kernel/input.rs
new file mode 100644
index 000000000000..dc617fdbdcfd
--- /dev/null
+++ b/rust/kernel/input.rs
@@ -0,0 +1,174 @@
+// 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, error::Result, prelude::*, str::CStr};
+use core::ptr::NonNull;
+
+/// Bus types for input devices.
+pub mod bus {
+    use super::*;
+
+    /// PCI bus.
+    pub const PCI: u16 = bindings::BUS_PCI as u16;
+    /// USB bus.
+    pub const USB: u16 = bindings::BUS_USB as u16;
+    /// RS232 serial bus.
+    pub const RS232: u16 = bindings::BUS_RS232 as u16;
+    /// I8042 PS/2 bus.
+    pub const I8042: u16 = bindings::BUS_I8042 as u16;
+}
+
+/// Linux input event types.
+pub mod event_type {
+    use super::*;
+
+    /// Synchronisation event.
+    pub const SYN: u32 = bindings::EV_SYN;
+    /// Key or button event.
+    pub const KEY: u32 = bindings::EV_KEY;
+    /// Relative movement event.
+    pub const REL: u32 = bindings::EV_REL;
+    /// Absolute movement event.
+    pub const ABS: u32 = bindings::EV_ABS;
+}
+
+/// An allocated input device that hasn't been registered yet.
+pub struct AllocatedDevice {
+    ptr: NonNull<bindings::input_dev>,
+}
+
+impl AllocatedDevice {
+    /// Allocates a new input device.
+    pub fn new() -> Result<Self> {
+        // SAFETY: `input_allocate_device` returns either a valid pointer or NULL.
+        let ptr = unsafe { bindings::input_allocate_device() };
+        let ptr = NonNull::new(ptr).ok_or(crate::error::code::ENOMEM)?;
+
+        Ok(Self { ptr })
+    }
+
+    /// Sets the human-readable device name.
+    pub fn set_name(&mut self, name: &'static CStr) {
+        // SAFETY: `self.ptr` is valid and `name` has static lifetime.
+        unsafe {
+            (*self.ptr.as_ptr()).name = name.as_char_ptr().cast();
+        }
+    }
+
+    /// Sets the physical location string.
+    pub fn set_phys(&mut self, phys: *const u8) {
+        // SAFETY: `self.ptr` is valid.
+        unsafe {
+            (*self.ptr.as_ptr()).phys = phys.cast();
+        }
+    }
+
+    /// Sets device identifier (bus type, vendor, product, version).
+    pub fn set_id(&mut self, bustype: u16, vendor: u16, product: u16, version: u16) {
+        // SAFETY: `self.ptr` is valid.
+        unsafe {
+            let dev = self.ptr.as_ptr();
+            (*dev).id.bustype = bustype;
+            (*dev).id.vendor = vendor;
+            (*dev).id.product = product;
+            (*dev).id.version = version;
+        }
+    }
+
+    /// Enables support for a capability (e.g. key or axis).
+    pub fn set_capability(&mut self, type_: u32, code: u32) {
+        // SAFETY: `self.ptr` is valid and type/code are valid capability values.
+        unsafe {
+            bindings::input_set_capability(self.ptr.as_ptr(), type_, code);
+        }
+    }
+
+    /// Sets parameter limits for an absolute axis.
+    pub fn set_abs_params(&mut self, axis: u32, min: i32, max: i32, fuzz: i32, flat: i32) {
+        // SAFETY: `self.ptr` is valid.
+        unsafe {
+            bindings::input_set_abs_params(self.ptr.as_ptr(), axis, min, max, fuzz, flat);
+        }
+    }
+
+    /// Registers the input device with the kernel subsystem.
+    ///
+    /// Consumes the `AllocatedDevice` and returns a registered RAII handle [`RegisteredDevice`].
+    pub fn register(self) -> Result<RegisteredDevice> {
+        let dev_ptr = self.ptr.as_ptr();
+        core::mem::forget(self);
+
+        // SAFETY: `dev_ptr` was allocated by `input_allocate_device()`.
+        let ret = unsafe { bindings::input_register_device(dev_ptr) };
+        if ret != 0 {
+            // SAFETY: Clean up on failure.
+            unsafe {
+                bindings::input_free_device(dev_ptr);
+            }
+            return Err(crate::error::Error::from_errno(ret));
+        }
+
+        // SAFETY: `dev_ptr` is known valid and non-null from `AllocatedDevice`.
+        let ptr = unsafe { NonNull::new_unchecked(dev_ptr) };
+        Ok(RegisteredDevice { ptr })
+    }
+}
+
+impl Drop for AllocatedDevice {
+    fn drop(&mut self) {
+        // SAFETY: Device was allocated but not registered; free it cleanly.
+        unsafe {
+            bindings::input_free_device(self.ptr.as_ptr());
+        }
+    }
+}
+
+/// A registered input device capable of reporting events.
+pub struct RegisteredDevice {
+    ptr: NonNull<bindings::input_dev>,
+}
+
+impl RegisteredDevice {
+    /// Reports a binary key/button press or release event.
+    pub fn report_key(&self, code: u32, value: bool) {
+        // SAFETY: `self.ptr` points to a valid registered `struct input_dev`.
+        unsafe {
+            bindings::input_report_key(self.ptr.as_ptr(), code, if value { 1 } else { 0 });
+        }
+    }
+
+    /// Reports an absolute axis coordinate.
+    pub fn report_abs(&self, axis: u32, value: i32) {
+        // SAFETY: `self.ptr` points to a valid registered `struct input_dev`.
+        unsafe {
+            bindings::input_report_abs(self.ptr.as_ptr(), axis, value);
+        }
+    }
+
+    /// Synchronizes input events (signals completion of an event packet).
+    pub fn sync(&self) {
+        // SAFETY: `self.ptr` points to a valid registered `struct input_dev`.
+        unsafe {
+            bindings::input_sync(self.ptr.as_ptr());
+        }
+    }
+}
+
+impl Drop for RegisteredDevice {
+    fn drop(&mut self) {
+        // SAFETY: `self.ptr` is a valid registered device.
+        // `input_unregister_device` automatically unregisters and frees it.
+        unsafe {
+            bindings::input_unregister_device(self.ptr.as_ptr());
+        }
+    }
+}
+
+// SAFETY: `RegisteredDevice` can be safely sent across threads (the input core is thread-safe).
+unsafe impl Send for RegisteredDevice {}
+// SAFETY: `RegisteredDevice` can be safely shared across threads.
+unsafe impl Sync for RegisteredDevice {}
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 1ab41129d557..35cbde5f6a97 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -314,3 +314,4 @@ pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f
         c"<Location::file_as_c_str() not supported>"
     }
 }
+pub mod input;
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 2/3] rust: serio: add serio bus abstractions
  2026-11-06 19:17 [PATCH 0/3] rust: input: add input/serio abstractions and port Gravis Stinger driver clicedvly768
  2026-11-06 19:17 ` [PATCH 1/3] rust: input: add input device abstractions clicedvly768
@ 2026-11-06 19:17 ` clicedvly768
  2026-11-06 19:35   ` sashiko-bot
  2026-11-06 19:17 ` [PATCH 3/3] input: joystick: stinger: port Gravis Stinger driver to safe Rust clicedvly768
  2 siblings, 1 reply; 7+ messages in thread
From: clicedvly768 @ 2026-11-06 19:17 UTC (permalink / raw)
  To: ojeda, dmitry.torokhov; +Cc: rust-for-linux, linux-input, clicedvly768

Add safe Rust abstractions for the serio (Serial I/O) bus subsystem.

This introduces:
- `DeviceId`: a transparent wrapper around `struct serio_device_id` for
  device matching tables.
- `Device`: a borrowed serio port device passed to driver callbacks.
- `IrqReturn`: typed enum for serio interrupt handler status.
- `Driver` trait: safe interface for serio drivers (`connect`,
  `interrupt`, `disconnect`).
- `Registration<T>`: safe RAII registration adapter that manages the
  underlying `struct serio_driver` pinned on the kernel heap, registering
  it via `serio_register_driver` and unregistering on drop.
- C helper wrappers for inline/macro serio functions in <linux/serio.h>.

Signed-off-by: clicedvly768 <harepro29@gmail.com>
---
 rust/bindings/bindings_helper.h |   3 +-
 rust/helpers/helpers.c          |   3 +-
 rust/helpers/serio.c            |  23 ++++
 rust/kernel/lib.rs              |   3 +-
 rust/kernel/serio.rs            | 223 ++++++++++++++++++++++++++++++++
 5 files changed, 252 insertions(+), 3 deletions(-)
 create mode 100644 rust/helpers/serio.c
 create mode 100644 rust/kernel/serio.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index 301c75cfeb61..0e44af5d770c 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -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>
@@ -88,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>
@@ -171,4 +173,3 @@ const unsigned long RUST_CONST_HELPER_GPU_BUDDY_TRIM_DISABLE = GPU_BUDDY_TRIM_DI
 #include "../../drivers/android/binder/rust_binder.h"
 #include "../../drivers/android/binder/rust_binder_events.h"
 #endif
-#include <linux/input.h>
diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
index 0bc33a7b4351..61cf3f77e85a 100644
--- a/rust/helpers/helpers.c
+++ b/rust/helpers/helpers.c
@@ -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"
@@ -95,6 +96,7 @@
 #include "scatterlist.c"
 #include "security.c"
 #include "serdev.c"
+#include "serio.c"
 #include "signal.c"
 #include "slab.c"
 #include "spinlock.c"
@@ -109,4 +111,3 @@
 #include "wait.c"
 #include "workqueue.c"
 #include "xarray.c"
-#include "input.c"
diff --git a/rust/helpers/serio.c b/rust/helpers/serio.c
new file mode 100644
index 000000000000..cd061495d9b1
--- /dev/null
+++ b/rust/helpers/serio.c
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/serio.h>
+
+__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);
+}
+
+__rust_helper int rust_helper_serio_register_driver(struct serio_driver *drv)
+{
+	return __serio_register_driver(drv, THIS_MODULE, KBUILD_MODNAME);
+}
+
+__rust_helper void rust_helper_serio_unregister_driver(struct serio_driver *drv)
+{
+	serio_unregister_driver(drv);
+}
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 35cbde5f6a97..e4a4525fafdd 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -88,6 +88,7 @@
 #[doc(hidden)]
 pub mod impl_flags;
 pub mod init;
+pub mod input;
 pub mod interop;
 pub mod interrupt;
 pub mod io;
@@ -132,6 +133,7 @@
 pub mod seq_file;
 #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
 pub mod serdev;
+pub mod serio;
 pub mod sizes;
 #[cfg(CONFIG_SOC_BUS)]
 pub mod soc;
@@ -314,4 +316,3 @@ pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f
         c"<Location::file_as_c_str() not supported>"
     }
 }
-pub mod input;
diff --git a/rust/kernel/serio.rs b/rust/kernel/serio.rs
new file mode 100644
index 000000000000..3b752ce4b64d
--- /dev/null
+++ b/rust/kernel/serio.rs
@@ -0,0 +1,223 @@
+// 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.
+
+use crate::{
+    bindings,
+    error::{to_result, Result},
+    prelude::*,
+    types::ForeignOwnable,
+};
+use core::{marker::PhantomData, pin::Pin, ptr::NonNull};
+
+/// Identifies supported serio hardware devices for auto-probing and matching.
+#[repr(transparent)]
+#[derive(Copy, Clone)]
+pub struct DeviceId(bindings::serio_device_id);
+
+impl DeviceId {
+    /// Creates a new serio device identifier.
+    pub const fn new(type_: u8, extra: u8, id: u8, proto: u8) -> Self {
+        Self(bindings::serio_device_id {
+            type_,
+            extra,
+            id,
+            proto,
+        })
+    }
+}
+
+/// Status returned by a serio driver interrupt handler.
+#[derive(Copy, Clone, PartialEq, Eq)]
+pub enum IrqReturn {
+    /// Interrupt was not handled by this driver.
+    None,
+    /// Interrupt was successfully handled.
+    Handled,
+}
+
+impl IrqReturn {
+    fn to_c(self) -> bindings::irqreturn_t {
+        match self {
+            Self::None => bindings::irqreturn::IRQ_NONE,
+            Self::Handled => bindings::irqreturn::IRQ_HANDLED,
+        }
+    }
+}
+
+/// A serio port device instance passed to driver callbacks.
+pub struct Device {
+    ptr: NonNull<bindings::serio>,
+}
+
+impl Device {
+    /// Returns the raw pointer to the underlying `struct serio`.
+    pub fn as_raw(&self) -> *mut bindings::serio {
+        self.ptr.as_ptr()
+    }
+
+    /// Reads the physical device path into a buffer.
+    pub fn phys(&self) -> &[u8; 32] {
+        // SAFETY: `self.ptr` points to a valid `struct serio`.
+        unsafe { &(*self.ptr.as_ptr()).phys }
+    }
+}
+
+/// 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: &'static [DeviceId];
+
+    /// Called when a matching serio port is detected.
+    fn connect(dev: &mut Device) -> Result<Self::Data>;
+
+    /// Called in interrupt context when a new byte arrives from the serio port.
+    fn interrupt(
+        data: &mut <Self::Data as ForeignOwnable>::BorrowedMut<'_>,
+        byte: u8,
+        flags: u32,
+    ) -> IrqReturn;
+
+    /// Called when the device is disconnected.
+    fn disconnect(_data: Self::Data) {}
+}
+
+/// Driver adapter that bridges the safe Rust [`Driver`] trait to the C serio bus subsystem.
+pub struct Registration<T: Driver> {
+    drv: Pin<KBox<bindings::serio_driver>>,
+    _p: PhantomData<T>,
+}
+
+impl<T: Driver> Registration<T> {
+    /// Registers a serio driver with the kernel.
+    pub fn new(name: &'static crate::str::CStr) -> Result<Self> {
+        let drv = bindings::serio_driver {
+            description: name.as_char_ptr().cast(),
+            id_table: T::ID_TABLE.as_ptr().cast::<bindings::serio_device_id>(),
+            manual_bind: false,
+            write_wakeup: None,
+            interrupt: Some(Self::interrupt_callback),
+            connect: Some(Self::connect_callback),
+            reconnect: None,
+            fast_reconnect: None,
+            disconnect: Some(Self::disconnect_callback),
+            cleanup: None,
+            driver: bindings::device_driver {
+                name: name.as_char_ptr().cast(),
+                ..Default::default()
+            },
+        };
+
+        let mut drv_box = Pin::new(KBox::new(drv, GFP_KERNEL)?);
+
+        // SAFETY: `drv_box` is pinned on the kernel heap at a permanent address.
+        let ret = unsafe { bindings::serio_register_driver(drv_box.as_mut().get_mut()) };
+        to_result(ret)?;
+
+        Ok(Self {
+            drv: drv_box,
+            _p: PhantomData,
+        })
+    }
+
+    /// # Safety
+    ///
+    /// Must only be invoked by the serio subsystem when a matching port is probed.
+    /// `serio` and `drv` must be valid non-null pointers provided by the kernel.
+    unsafe extern "C" fn connect_callback(
+        serio: *mut bindings::serio,
+        drv: *mut bindings::serio_driver,
+    ) -> core::ffi::c_int {
+        let Some(serio_nn) = NonNull::new(serio) else {
+            return -(crate::error::code::EINVAL.to_errno());
+        };
+
+        let mut dev = Device { ptr: serio_nn };
+
+        let data = match T::connect(&mut dev) {
+            Ok(d) => d,
+            Err(e) => return e.to_errno(),
+        };
+
+        let raw_data = data.into_foreign();
+        // SAFETY: `serio` is valid; store driver data pointer.
+        unsafe {
+            bindings::serio_set_drvdata(serio, raw_data.cast());
+        }
+
+        // SAFETY: Open serio port to start receiving characters.
+        let ret = unsafe { bindings::serio_open(serio, drv) };
+        if ret != 0 {
+            // SAFETY: Clean up driver data 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;
+        }
+
+        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: core::ffi::c_uchar,
+        flags: core::ffi::c_uint,
+    ) -> 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);
+        ret.to_c()
+    }
+
+    /// # Safety
+    ///
+    /// Must only be invoked by the serio subsystem when disconnecting a port.
+    /// `serio` must be a valid pointer.
+    unsafe extern "C" fn disconnect_callback(serio: *mut bindings::serio) {
+        // SAFETY: `serio` is valid.
+        let raw = unsafe { bindings::serio_get_drvdata(serio) };
+        if raw.is_null() {
+            return;
+        }
+
+        // SAFETY: Close port, clear drvdata, and pass owned data back to disconnect.
+        unsafe {
+            bindings::serio_close(serio);
+            bindings::serio_set_drvdata(serio, core::ptr::null_mut());
+            let data = <T::Data as ForeignOwnable>::from_foreign(raw);
+            T::disconnect(data);
+        }
+    }
+}
+
+impl<T: Driver> Drop for Registration<T> {
+    fn drop(&mut self) {
+        // SAFETY: Unregister driver with kernel.
+        unsafe {
+            bindings::serio_unregister_driver(self.drv.as_mut().get_mut());
+        }
+    }
+}
+
+// SAFETY: `Registration` can be safely sent to another thread.
+unsafe impl<T: Driver> Send for Registration<T> {}
+// SAFETY: `Registration` can be safely shared across threads.
+unsafe impl<T: Driver> Sync for Registration<T> {}
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* [PATCH 3/3] input: joystick: stinger: port Gravis Stinger driver to safe Rust
  2026-11-06 19:17 [PATCH 0/3] rust: input: add input/serio abstractions and port Gravis Stinger driver clicedvly768
  2026-11-06 19:17 ` [PATCH 1/3] rust: input: add input device abstractions clicedvly768
  2026-11-06 19:17 ` [PATCH 2/3] rust: serio: add serio bus abstractions clicedvly768
@ 2026-11-06 19:17 ` clicedvly768
  2026-11-06 19:42   ` sashiko-bot
  2 siblings, 1 reply; 7+ messages in thread
From: clicedvly768 @ 2026-11-06 19:17 UTC (permalink / raw)
  To: ojeda, dmitry.torokhov; +Cc: rust-for-linux, linux-input, clicedvly768

Rewrite the legacy Gravis Stinger serial gamepad driver in safe Rust,
replacing drivers/input/joystick/stinger.c with stinger.rs.

The new implementation:
- Uses the newly introduced `kernel::input` and `kernel::serio`
  abstractions.
- Contains zero `unsafe` blocks in the driver code itself.
- Preserves full protocol compatibility with the Gravis Stinger hardware
  (9600 baud, 8N1, 4-byte packet format with 10 buttons and 2 axes).
- Adds `depends on RUST` to CONFIG_JOYSTICK_STINGER in Kconfig.

Signed-off-by: clicedvly768 <harepro29@gmail.com>
---
 drivers/input/joystick/Kconfig    |   1 +
 drivers/input/joystick/stinger.c  | 191 ------------------------------
 drivers/input/joystick/stinger.rs | 174 +++++++++++++++++++++++++++
 3 files changed, 175 insertions(+), 191 deletions(-)
 delete mode 100644 drivers/input/joystick/stinger.c
 create mode 100644 drivers/input/joystick/stinger.rs

diff --git a/drivers/input/joystick/Kconfig b/drivers/input/joystick/Kconfig
index 7755e5b454d2..e672a3bc6dcc 100644
--- a/drivers/input/joystick/Kconfig
+++ b/drivers/input/joystick/Kconfig
@@ -188,6 +188,7 @@ config JOYSTICK_SPACEBALL
 	  module will be called spaceball.
 
 config JOYSTICK_STINGER
+	depends on RUST
 	tristate "Gravis Stinger gamepad"
 	select SERIO
 	help
diff --git a/drivers/input/joystick/stinger.c b/drivers/input/joystick/stinger.c
deleted file mode 100644
index 011f9b137dca..000000000000
--- a/drivers/input/joystick/stinger.c
+++ /dev/null
@@ -1,191 +0,0 @@
-// SPDX-License-Identifier: GPL-2.0-or-later
-/*
- *  Copyright (c) 2000-2001 Vojtech Pavlik
- *  Copyright (c) 2000 Mark Fletcher
- */
-
-/*
- * Gravis Stinger gamepad driver for Linux
- */
-
-#include <linux/kernel.h>
-#include <linux/module.h>
-#include <linux/slab.h>
-#include <linux/input.h>
-#include <linux/serio.h>
-
-#define DRIVER_DESC	"Gravis Stinger gamepad driver"
-
-MODULE_AUTHOR("Vojtech Pavlik <vojtech@ucw.cz>");
-MODULE_DESCRIPTION(DRIVER_DESC);
-MODULE_LICENSE("GPL");
-
-/*
- * Constants.
- */
-
-#define STINGER_MAX_LENGTH 8
-
-/*
- * Per-Stinger data.
- */
-
-struct stinger {
-	struct input_dev *dev;
-	int idx;
-	unsigned char data[STINGER_MAX_LENGTH];
-	char phys[32];
-};
-
-/*
- * stinger_process_packet() decodes packets the driver receives from the
- * Stinger. It updates the data accordingly.
- */
-
-static void stinger_process_packet(struct stinger *stinger)
-{
-	struct input_dev *dev = stinger->dev;
-	unsigned char *data = stinger->data;
-
-	if (!stinger->idx) return;
-
-	input_report_key(dev, BTN_A,	  ((data[0] & 0x20) >> 5));
-	input_report_key(dev, BTN_B,	  ((data[0] & 0x10) >> 4));
-	input_report_key(dev, BTN_C,	  ((data[0] & 0x08) >> 3));
-	input_report_key(dev, BTN_X,	  ((data[0] & 0x04) >> 2));
-	input_report_key(dev, BTN_Y,	  ((data[3] & 0x20) >> 5));
-	input_report_key(dev, BTN_Z,	  ((data[3] & 0x10) >> 4));
-	input_report_key(dev, BTN_TL,     ((data[3] & 0x08) >> 3));
-	input_report_key(dev, BTN_TR,     ((data[3] & 0x04) >> 2));
-	input_report_key(dev, BTN_SELECT, ((data[3] & 0x02) >> 1));
-	input_report_key(dev, BTN_START,   (data[3] & 0x01));
-
-	input_report_abs(dev, ABS_X, (data[1] & 0x3F) - ((data[0] & 0x01) << 6));
-	input_report_abs(dev, ABS_Y, ((data[0] & 0x02) << 5) - (data[2] & 0x3F));
-
-	input_sync(dev);
-
-	return;
-}
-
-/*
- * stinger_interrupt() is called by the low level driver when characters
- * are ready for us. We then buffer them for further processing, or call the
- * packet processing routine.
- */
-
-static irqreturn_t stinger_interrupt(struct serio *serio,
-	unsigned char data, unsigned int flags)
-{
-	struct stinger *stinger = serio_get_drvdata(serio);
-
-	/* All Stinger packets are 4 bytes */
-
-	if (stinger->idx < STINGER_MAX_LENGTH)
-		stinger->data[stinger->idx++] = data;
-
-	if (stinger->idx == 4) {
-		stinger_process_packet(stinger);
-		stinger->idx = 0;
-	}
-
-	return IRQ_HANDLED;
-}
-
-/*
- * stinger_disconnect() is the opposite of stinger_connect()
- */
-
-static void stinger_disconnect(struct serio *serio)
-{
-	struct stinger *stinger = serio_get_drvdata(serio);
-
-	serio_close(serio);
-	serio_set_drvdata(serio, NULL);
-	input_unregister_device(stinger->dev);
-	kfree(stinger);
-}
-
-/*
- * stinger_connect() is the routine that is called when someone adds a
- * new serio device that supports Stinger protocol and registers it as
- * an input device.
- */
-
-static int stinger_connect(struct serio *serio, struct serio_driver *drv)
-{
-	struct stinger *stinger;
-	struct input_dev *input_dev;
-	int err = -ENOMEM;
-
-	stinger = kmalloc_obj(*stinger);
-	input_dev = input_allocate_device();
-	if (!stinger || !input_dev)
-		goto fail1;
-
-	stinger->dev = input_dev;
-	snprintf(stinger->phys, sizeof(stinger->phys), "%s/serio0", serio->phys);
-
-	input_dev->name = "Gravis Stinger";
-	input_dev->phys = stinger->phys;
-	input_dev->id.bustype = BUS_RS232;
-	input_dev->id.vendor = SERIO_STINGER;
-	input_dev->id.product = 0x0001;
-	input_dev->id.version = 0x0100;
-	input_dev->dev.parent = &serio->dev;
-
-	input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
-	input_dev->keybit[BIT_WORD(BTN_A)] = BIT_MASK(BTN_A) | BIT_MASK(BTN_B) |
-		BIT_MASK(BTN_C) | BIT_MASK(BTN_X) | BIT_MASK(BTN_Y) |
-		BIT_MASK(BTN_Z) | BIT_MASK(BTN_TL) | BIT_MASK(BTN_TR) |
-		BIT_MASK(BTN_START) | BIT_MASK(BTN_SELECT);
-	input_set_abs_params(input_dev, ABS_X, -64, 64, 0, 4);
-	input_set_abs_params(input_dev, ABS_Y, -64, 64, 0, 4);
-
-	serio_set_drvdata(serio, stinger);
-
-	err = serio_open(serio, drv);
-	if (err)
-		goto fail2;
-
-	err = input_register_device(stinger->dev);
-	if (err)
-		goto fail3;
-
-	return 0;
-
- fail3:	serio_close(serio);
- fail2:	serio_set_drvdata(serio, NULL);
- fail1:	input_free_device(input_dev);
-	kfree(stinger);
-	return err;
-}
-
-/*
- * The serio driver structure.
- */
-
-static const struct serio_device_id stinger_serio_ids[] = {
-	{
-		.type	= SERIO_RS232,
-		.proto	= SERIO_STINGER,
-		.id	= SERIO_ANY,
-		.extra	= SERIO_ANY,
-	},
-	{ 0 }
-};
-
-MODULE_DEVICE_TABLE(serio, stinger_serio_ids);
-
-static struct serio_driver stinger_drv = {
-	.driver		= {
-		.name	= "stinger",
-	},
-	.description	= DRIVER_DESC,
-	.id_table	= stinger_serio_ids,
-	.interrupt	= stinger_interrupt,
-	.connect	= stinger_connect,
-	.disconnect	= stinger_disconnect,
-};
-
-module_serio_driver(stinger_drv);
diff --git a/drivers/input/joystick/stinger.rs b/drivers/input/joystick/stinger.rs
new file mode 100644
index 000000000000..daa199463631
--- /dev/null
+++ b/drivers/input/joystick/stinger.rs
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+
+//! Gravis Stinger gamepad driver written in safe Rust.
+//!
+//! Rust port of legacy C driver `drivers/input/joystick/stinger.c`.
+//!
+//! Authors:
+//! - Original C driver: Vojtech Pavlik <vojtech@ucw.cz>, Mark Fletcher
+//! - Rust port: Rust for Linux Contributors
+
+use kernel::{
+    bindings,
+    input::{bus, event_type, AllocatedDevice, RegisteredDevice},
+    prelude::*,
+    serio,
+    types::ForeignOwnable,
+};
+
+const DRIVER_NAME: &CStr = c"stinger";
+const DRIVER_DESC: &CStr = c"Gravis Stinger gamepad";
+
+const STINGER_MAX_LENGTH: usize = 8;
+
+/// Per-device state for an attached Gravis Stinger gamepad.
+struct Stinger {
+    input: RegisteredDevice,
+    idx: usize,
+    data: [u8; STINGER_MAX_LENGTH],
+}
+
+impl Stinger {
+    /// Decodes incoming 4-byte packets from the Gravis Stinger and reports input events.
+    fn process_packet(&self) {
+        if self.idx == 0 {
+            return;
+        }
+
+        let d0 = i32::from(self.data[0]);
+        let d1 = i32::from(self.data[1]);
+        let d2 = i32::from(self.data[2]);
+        let d3 = i32::from(self.data[3]);
+
+        // Report button states (active high bits in packet)
+        self.input
+            .report_key(bindings::BTN_A, ((d0 & 0x20) >> 5) != 0);
+        self.input
+            .report_key(bindings::BTN_B, ((d0 & 0x10) >> 4) != 0);
+        self.input
+            .report_key(bindings::BTN_C, ((d0 & 0x08) >> 3) != 0);
+        self.input
+            .report_key(bindings::BTN_X, ((d0 & 0x04) >> 2) != 0);
+        self.input
+            .report_key(bindings::BTN_Y, ((d3 & 0x20) >> 5) != 0);
+        self.input
+            .report_key(bindings::BTN_Z, ((d3 & 0x10) >> 4) != 0);
+        self.input
+            .report_key(bindings::BTN_TL, ((d3 & 0x08) >> 3) != 0);
+        self.input
+            .report_key(bindings::BTN_TR, ((d3 & 0x04) >> 2) != 0);
+        self.input
+            .report_key(bindings::BTN_SELECT, ((d3 & 0x02) >> 1) != 0);
+        self.input.report_key(bindings::BTN_START, (d3 & 0x01) != 0);
+
+        // Report 2-axis position: coordinates in range -64..64
+        self.input
+            .report_abs(bindings::ABS_X, (d1 & 0x3f) - ((d0 & 0x01) << 6));
+        self.input
+            .report_abs(bindings::ABS_Y, ((d0 & 0x02) << 5) - (d2 & 0x3f));
+
+        self.input.sync();
+    }
+}
+
+/// The safe serio driver implementation.
+struct StingerDriver;
+
+impl serio::Driver for StingerDriver {
+    type Data = KBox<Stinger>;
+
+    const ID_TABLE: &'static [serio::DeviceId] = &[
+        serio::DeviceId::new(
+            bindings::SERIO_RS232 as u8,
+            bindings::SERIO_ANY as u8,
+            bindings::SERIO_ANY as u8,
+            bindings::SERIO_STINGER as u8,
+        ),
+        serio::DeviceId::new(0, 0, 0, 0),
+    ];
+
+    fn connect(dev: &mut serio::Device) -> Result<Self::Data> {
+        let mut input_alloc = AllocatedDevice::new()?;
+
+        input_alloc.set_name(DRIVER_DESC);
+        input_alloc.set_phys(dev.phys().as_ptr());
+        input_alloc.set_id(bus::RS232, bindings::SERIO_STINGER as u16, 0x0001, 0x0100);
+
+        // Configure supported buttons
+        for btn in [
+            bindings::BTN_A,
+            bindings::BTN_B,
+            bindings::BTN_C,
+            bindings::BTN_X,
+            bindings::BTN_Y,
+            bindings::BTN_Z,
+            bindings::BTN_TL,
+            bindings::BTN_TR,
+            bindings::BTN_START,
+            bindings::BTN_SELECT,
+        ] {
+            input_alloc.set_capability(event_type::KEY, btn);
+        }
+
+        // Configure 2-axis joystick with flat margin of 4
+        input_alloc.set_capability(event_type::ABS, bindings::ABS_X);
+        input_alloc.set_capability(event_type::ABS, bindings::ABS_Y);
+        input_alloc.set_abs_params(bindings::ABS_X, -64, 64, 0, 4);
+        input_alloc.set_abs_params(bindings::ABS_Y, -64, 64, 0, 4);
+
+        let registered = input_alloc.register()?;
+
+        let stinger = KBox::new(
+            Stinger {
+                input: registered,
+                idx: 0,
+                data: [0; STINGER_MAX_LENGTH],
+            },
+            GFP_KERNEL,
+        )?;
+
+        Ok(stinger)
+    }
+
+    fn interrupt(
+        stinger: &mut <Self::Data as ForeignOwnable>::BorrowedMut<'_>,
+        data: u8,
+        _flags: u32,
+    ) -> serio::IrqReturn {
+        if stinger.idx < STINGER_MAX_LENGTH {
+            stinger.data[stinger.idx] = data;
+            stinger.idx += 1;
+        }
+
+        if stinger.idx == 4 {
+            stinger.process_packet();
+            stinger.idx = 0;
+        }
+
+        serio::IrqReturn::Handled
+    }
+
+    fn disconnect(_data: Self::Data) {
+        // Automatically drops `stinger`, unregistering and freeing the input device.
+    }
+}
+
+module! {
+    type: StingerModule,
+    name: "stinger",
+    authors: ["Rust for Linux Contributors"],
+    description: "Gravis Stinger gamepad driver in safe Rust",
+    license: "GPL",
+}
+
+struct StingerModule {
+    _reg: serio::Registration<StingerDriver>,
+}
+
+impl kernel::Module for StingerModule {
+    fn init(_module: &'static ThisModule) -> Result<Self> {
+        let reg = serio::Registration::<StingerDriver>::new(DRIVER_NAME)?;
+        pr_info!("Gravis Stinger safe Rust driver initialized\n");
+        Ok(Self { _reg: reg })
+    }
+}
-- 
2.56.0


^ permalink raw reply related	[flat|nested] 7+ messages in thread

* Re: [PATCH 1/3] rust: input: add input device abstractions
  2026-11-06 19:17 ` [PATCH 1/3] rust: input: add input device abstractions clicedvly768
@ 2026-11-06 19:29   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-11-06 19:29 UTC (permalink / raw)
  To: clicedvly768; +Cc: linux-input, dmitry.torokhov, ojeda, gary

Thank you for your contribution! Sashiko AI review found 5 potential
issues to consider:
- [High] rust: input: unconditional build breaks when CONFIG_INPUT is n
  or m
- [High] rust: input: unsound raw pointer parameter in
  AllocatedDevice::set_phys()
- [High] rust: input: out-of-bounds write in
  AllocatedDevice::set_abs_params()
- [Low] rust: input: missing #[inline] on small C-binding wrapper
  methods
- [Low] rust: input: non-vertical import style and unsorted
  include/module lists
--

commit 9cd0fd4d5edfd06c93102ba62a703d2a5e1c93f2
Author: clicedvly768 <harepro29@gmail.com>

rust: input: add input device abstractions

This commit adds Rust abstractions and C helper wrappers for allocating,
configuring, registering, and reporting events on Linux input devices
(struct input_dev).

> diff --git a/rust/kernel/input.rs b/rust/kernel/input.rs
> new file mode 100644
> index 0000000000000..dc617fdbdcfd3
> --- /dev/null
> +++ b/rust/kernel/input.rs
> @@ -0,0 +1,174 @@
> +// 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, error::Result, prelude::*, str::CStr};

[Severity: Low]
This isn't a bug, but the crate imports here use a single-line horizontal
list instead of the vertical import style from the Rust coding guidelines.
Also, #include <linux/input.h> in rust/bindings/bindings_helper.h,
#include "input.c" in rust/helpers/helpers.c, and pub mod input; in
rust/kernel/lib.rs are appended at the bottom of each file instead of in
their sorted sections (though commit "rust: serio: add serio bus
abstractions" later moves those three entries into alphabetical order).

[ ... ]

> +    /// Sets the human-readable device name.
> +    pub fn set_name(&mut self, name: &'static CStr) {
> +        // SAFETY: `self.ptr` is valid and `name` has static lifetime.
> +        unsafe {
> +            (*self.ptr.as_ptr()).name = name.as_char_ptr().cast();
> +        }
> +    }
> +
> +    /// Sets the physical location string.
> +    pub fn set_phys(&mut self, phys: *const u8) {
> +        // SAFETY: `self.ptr` is valid.
> +        unsafe {
> +            (*self.ptr.as_ptr()).phys = phys.cast();
> +        }
> +    }

[Severity: High]
Can safe Rust callers pass an invalid, short-lived, or non-NUL-terminated
pointer to AllocatedDevice::set_phys()?

The input core does not copy dev->phys and dereferences it as a
NUL-terminated C string during registration in input_dev_uevent() as well
as when reading /sys/class/input/inputN/phys, /proc/bus/input/devices, or
handling the EVIOCGPHYS ioctl, which can cause a use-after-free or
out-of-bounds read.  Like set_name() above, set_phys() should take
&'static CStr instead of *const u8.

[ ... ]

> +    /// Sets parameter limits for an absolute axis.
> +    pub fn set_abs_params(&mut self, axis: u32, min: i32, max: i32, fuzz: i32, flat: i32) {
> +        // SAFETY: `self.ptr` is valid.
> +        unsafe {
> +            bindings::input_set_abs_params(self.ptr.as_ptr(), axis, min, max, fuzz, flat);
> +        }
> +    }

[Severity: High]
Can AllocatedDevice::set_abs_params() write out of bounds when axis >=
ABS_CNT (0x40)?

Unlike input_set_capability(), input_set_abs_params() does not bounds-check
axis:

drivers/input/input.c:input_set_abs_params() {
    ...
	__set_bit(EV_ABS, dev->evbit);
	__set_bit(axis, dev->absbit);

	input_alloc_absinfo(dev);
	if (!dev->absinfo)
		return;

	absinfo = &dev->absinfo[axis];
    ...
}

Because dev->absbit and the kcalloc(ABS_CNT, ...) array in dev->absinfo are
only sized for ABS_CNT elements, a safe Rust caller passing axis > ABS_MAX
corrupts memory past dev->absbit in struct input_dev and past the end of
the heap-allocated dev->absinfo array.

[ ... ]

> +impl RegisteredDevice {
> +    /// Reports a binary key/button press or release event.
> +    pub fn report_key(&self, code: u32, value: bool) {
> +        // SAFETY: `self.ptr` points to a valid registered `struct input_dev`.
> +        unsafe {
> +            bindings::input_report_key(self.ptr.as_ptr(), code, if value { 1 } else { 0 });
> +        }
> +    }
> +
> +    /// Reports an absolute axis coordinate.
> +    pub fn report_abs(&self, axis: u32, value: i32) {
> +        // SAFETY: `self.ptr` points to a valid registered `struct input_dev`.
> +        unsafe {
> +            bindings::input_report_abs(self.ptr.as_ptr(), axis, value);
> +        }
> +    }
> +
> +    /// Synchronizes input events (signals completion of an event packet).
> +    pub fn sync(&self) {
> +        // SAFETY: `self.ptr` points to a valid registered `struct input_dev`.
> +        unsafe {
> +            bindings::input_sync(self.ptr.as_ptr());
> +        }
> +    }
> +}

[Severity: Low]
Should the small wrapper methods on AllocatedDevice and RegisteredDevice
that set struct fields or forward directly to C bindings be marked
#[inline]?

> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 4d5c96ddc49c7..559fc79b1e820 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -310,3 +310,4 @@ pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f
>          c"<Location::file_as_c_str() not supported>"
>      }
>  }
> +pub mod input;

[Severity: High]
Does building the kernel fail at link time when CONFIG_RUST=y and
CONFIG_INPUT is m or n?

CONFIG_INPUT is a tristate Kconfig symbol, and include/linux/input.h does
not provide inline stub fallbacks for input_event(),
input_allocate_device(), input_free_device(), input_register_device(),
input_unregister_device(), input_set_capability(), or
input_set_abs_params().  Because rust/kernel.o and rust/helpers/helpers.o
are always built into vmlinux, leaving pub mod input; in rust/kernel/lib.rs
and rust/helpers/input.c unguarded causes undefined symbol references
during vmlinux linking whenever CONFIG_INPUT!=y.  Gating pub mod input;
with #[cfg(CONFIG_INPUT = "y")] (or #[cfg(CONFIG_INPUT)] if modular callers
are supported where appropriate) and guarding rust/helpers/input.c with
#ifdef CONFIG_INPUT avoids the link failure.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261106191714.334055-1-harepro29@gmail.com?part=1

^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [PATCH 2/3] rust: serio: add serio bus abstractions
  2026-11-06 19:17 ` [PATCH 2/3] rust: serio: add serio bus abstractions clicedvly768
@ 2026-11-06 19:35   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-11-06 19:35 UTC (permalink / raw)
  To: clicedvly768; +Cc: linux-input, dmitry.torokhov, ojeda, gary

Thank you for your contribution! Sashiko AI review found 8 potential
issues to consider:
- [High] rust: serio: rust_helper_serio_register_driver() uses wrong
  THIS_MODULE
- [High] rust: serio: Driver::ID_TABLE slice lacks sentinel causing OOB
  read
- [Medium] rust: serio: unguarded serio and input build fails when
  CONFIG_SERIO=m/n
- [Medium] rust: serio: connect_callback() negates negative errno and
  opens port late
- [Medium] rust: serio: Registration stores serio_driver without Opaque
  causing UB
- [Low] rust: serio: IrqReturn duplicates kernel::irq::IrqReturn with
  wrong paths
- [Low] rust: serio: Device and Registration bypass generic driver
  infrastructure
- [Low] rust: serio: missing inline attributes, non-vertical imports,
  and core::ffi
--

commit a79cbd7ccd6c2d027f39fc787dc865ce37a52295
Author: clicedvly768 <harepro29@gmail.com>

rust: serio: add serio bus abstractions

This commit adds Rust abstractions and C helper wrappers for the serio
bus subsystem, including DeviceId, Device, IrqReturn, Driver, and
Registration.

> diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
> index 7a11f5fa461d2..84ffdb015b6d9 100644
> --- a/rust/helpers/helpers.c
> +++ b/rust/helpers/helpers.c
> @@ -66,6 +66,7 @@
>  #include "fs.c"
>  #include "fwctl.c"
>  #include "gpu.c"
> +#include "input.c"
>  #include "interrupt.c"
>  #include "io.c"
>  #include "irq.c"
> @@ -92,6 +93,7 @@
>  #include "scatterlist.c"
>  #include "security.c"
>  #include "serdev.c"
> +#include "serio.c"
>  #include "signal.c"
>  #include "slab.c"
>  #include "spinlock.c"

[ ... ]

> diff --git a/rust/helpers/serio.c b/rust/helpers/serio.c
> new file mode 100644
> index 0000000000000..cd061495d9b1d
> --- /dev/null
> +++ b/rust/helpers/serio.c
> @@ -0,0 +1,23 @@
> +// SPDX-License-Identifier: GPL-2.0
> +
> +#include <linux/serio.h>
> +
> +__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);
> +}
> +
> +__rust_helper int rust_helper_serio_register_driver(struct serio_driver *drv)
> +{
> +	return __serio_register_driver(drv, THIS_MODULE, KBUILD_MODNAME);
> +}

[Severity: High]
Does evaluating THIS_MODULE and KBUILD_MODNAME inside
rust_helper_serio_register_driver() leave drv->driver.owner as NULL for
loadable Rust serio drivers?

Because rust/helpers/serio.c is compiled into rust/helpers/helpers.o rather
than the registering driver module, THIS_MODULE expands to NULL (when
helpers.o is built-in) and KBUILD_MODNAME expands to "helpers".  When
__serio_register_driver() sets drv->driver.owner = owner, neither the
driver core nor serio_queue_event() (via try_module_get(drv->driver.owner))
can pin the driver module while ports are bound or kseriod events are
queued, allowing the module to be unloaded while still in use and causing a
use-after-free.

Since __serio_register_driver() and serio_unregister_driver() are already
exported non-inline C functions, these two helpers can be dropped and
Registration::new() can take a &'static ThisModule and pass
module.as_ptr() and name.as_char_ptr() directly to
bindings::__serio_register_driver().

> +
> +__rust_helper void rust_helper_serio_unregister_driver(struct serio_driver *drv)
> +{
> +	serio_unregister_driver(drv);
> +}
> diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
> index 559fc79b1e820..c9f82dce8f823 100644
> --- a/rust/kernel/lib.rs
> +++ b/rust/kernel/lib.rs
> @@ -86,6 +86,7 @@
>  #[doc(hidden)]
>  pub mod impl_flags;
>  pub mod init;
> +pub mod input;
>  pub mod interop;
>  pub mod interrupt;
>  pub mod io;
> @@ -128,6 +129,7 @@
>  pub mod seq_file;
>  #[cfg(CONFIG_RUST_SERIAL_DEV_BUS_ABSTRACTIONS)]
>  pub mod serdev;
> +pub mod serio;
>  pub mod sizes;
>  #[cfg(CONFIG_SOC_BUS)]
>  pub mod soc;

[Severity: Medium]
Does building with CONFIG_SERIO=m or CONFIG_SERIO=n (or CONFIG_INPUT=m/n)
fail to link vmlinux?

CONFIG_SERIO and CONFIG_INPUT are tristate Kconfig options, and
include/linux/serio.h and include/linux/input.h declare
__serio_register_driver(), serio_unregister_driver(), serio_open(),
serio_close(), and the input_*() functions without inline stubs when
disabled.  Because rust/kernel/lib.rs and rust/helpers/helpers.c are always
built into vmlinux when CONFIG_RUST=y, compiling rust/helpers/serio.c,
rust/helpers/input.c, kernel::serio, and kernel::input without Kconfig
guards causes undefined symbol references at link time whenever
CONFIG_SERIO or CONFIG_INPUT is n or m.

[ ... ]

> diff --git a/rust/kernel/serio.rs b/rust/kernel/serio.rs
> new file mode 100644
> index 0000000000000..3b752ce4b64de
> --- /dev/null
> +++ b/rust/kernel/serio.rs
> @@ -0,0 +1,223 @@
> +// 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.
> +
> +use crate::{
> +    bindings,
> +    error::{to_result, Result},
> +    prelude::*,
> +    types::ForeignOwnable,
> +};
> +use core::{marker::PhantomData, pin::Pin, ptr::NonNull};
> +
> +/// Identifies supported serio hardware devices for auto-probing and matching.
> +#[repr(transparent)]
> +#[derive(Copy, Clone)]
> +pub struct DeviceId(bindings::serio_device_id);
> +
> +impl DeviceId {
> +    /// Creates a new serio device identifier.
> +    pub const fn new(type_: u8, extra: u8, id: u8, proto: u8) -> Self {
> +        Self(bindings::serio_device_id {
> +            type_,
> +            extra,
> +            id,
> +            proto,
> +        })
> +    }
> +}

[Severity: Low]
This isn't a bug, but there are a few style and convention issues in this
file:

- The imports at the top use horizontal grouping instead of the kernel
  vertical import style.
- Small functions in the kernel crate (DeviceId::new(), IrqReturn::to_c(),
  Device::as_raw(), and Device::phys()) are missing #[inline] attributes.
- connect_callback() and interrupt_callback() use core::ffi::{c_int,
  c_uchar, c_uint} instead of the crate::ffi / prelude C integer types.

> +
> +/// Status returned by a serio driver interrupt handler.
> +#[derive(Copy, Clone, PartialEq, Eq)]
> +pub enum IrqReturn {
> +    /// Interrupt was not handled by this driver.
> +    None,
> +    /// Interrupt was successfully handled.
> +    Handled,
> +}
> +
> +impl IrqReturn {
> +    fn to_c(self) -> bindings::irqreturn_t {
> +        match self {
> +            Self::None => bindings::irqreturn::IRQ_NONE,
> +            Self::Handled => bindings::irqreturn::IRQ_HANDLED,
> +        }
> +    }
> +}

[Severity: Low]
Can this reuse kernel::irq::IrqReturn instead of defining a second
IrqReturn enum?  Also, bindgen generates bindings::irqreturn_IRQ_NONE and
bindings::irqreturn_IRQ_HANDLED rather than bindings::irqreturn::IRQ_*.

> +
> +/// A serio port device instance passed to driver callbacks.
> +pub struct Device {
> +    ptr: NonNull<bindings::serio>,
> +}

[Severity: Low]
Should Device and Registration integrate with the generic device and
driver abstractions in kernel::device and kernel::driver?

Wrapping Opaque<bindings::serio> with a device::DeviceContext parameter and
implementing AsRef<device::Device<Ctx>> (and using driver::RegistrationOps
/ driver::DriverLayout for registration) would allow serio drivers to
obtain a &device::Device for setting parent devices (such as
input_dev->dev.parent = &serio->dev), logging via dev_info! / dev_err!, and
using devres.

[ ... ]

> +/// 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: &'static [DeviceId];

[Severity: High]
Can passing a plain &'static [DeviceId] slice to C as drv->id_table cause
an out-of-bounds read in serio_match_port()?

drivers/input/serio/serio.c:serio_match_port() walks the table until it
reaches a zeroed sentinel entry:

drivers/input/serio/serio.c:serio_match_port() {
	while (ids->type || ids->proto) {
		if ((ids->type == SERIO_ANY || ids->type == serio->id.type) &&
...
		ids++;
	}
}

Because Driver is a safe trait and &[DeviceId] does not enforce a trailing
zero sentinel (and an empty slice passes a dangling pointer from
as_ptr()), any safe Driver implementation that does not manually append a
zeroed DeviceId entry will cause serio_match_port() to read past the end of
ID_TABLE when probing a non-matching port.  DeviceId should implement
kernel::device_id::RawDeviceId and use kernel::device_id::IdTable /
IdArray so the zero terminator is guaranteed at compile time.

[ ... ]

> +    /// # Safety
> +    ///
> +    /// Must only be invoked by the serio subsystem when a matching port is probed.
> +    /// `serio` and `drv` must be valid non-null pointers provided by the kernel.
> +    unsafe extern "C" fn connect_callback(
> +        serio: *mut bindings::serio,
> +        drv: *mut bindings::serio_driver,
> +    ) -> core::ffi::c_int {
> +        let Some(serio_nn) = NonNull::new(serio) else {
> +            return -(crate::error::code::EINVAL.to_errno());
> +        };
> +
> +        let mut dev = Device { ptr: serio_nn };
> +
> +        let data = match T::connect(&mut dev) {
> +            Ok(d) => d,
> +            Err(e) => return e.to_errno(),
> +        };
> +
> +        let raw_data = data.into_foreign();
> +        // SAFETY: `serio` is valid; store driver data pointer.
> +        unsafe {
> +            bindings::serio_set_drvdata(serio, raw_data.cast());
> +        }
> +
> +        // SAFETY: Open serio port to start receiving characters.
> +        let ret = unsafe { bindings::serio_open(serio, drv) };

[Severity: Medium]
Does connect_callback() return a positive errno on NULL and invoke
T::connect() before the port is opened?

Error::to_errno() already returns a negative errno (-22 for EINVAL), so
-(crate::error::code::EINVAL.to_errno()) returns +22 instead of -EINVAL.

In addition, calling T::connect() before serio_set_drvdata() and
serio_open() means the serio port is not open during T::connect(), and a
driver that registers an input device inside T::connect() exposes the input
device to userspace before serio_open() has succeeded.

[ ... ]

> +impl<T: Driver> Drop for Registration<T> {
> +    fn drop(&mut self) {
> +        // SAFETY: Unregister driver with kernel.
> +        unsafe {
> +            bindings::serio_unregister_driver(self.drv.as_mut().get_mut());
> +        }
> +    }
> +}

[Severity: Medium]
Does self.drv.as_mut().get_mut() violate Rust's aliasing rules while the
serio driver is still registered with the kernel?

Registration<T> stores bindings::serio_driver directly in
Pin<KBox<bindings::serio_driver>> without wrapping it in
kernel::types::Opaque.  While the driver is registered, C code in the
serio core holds pointers to struct serio_driver and accesses or mutates
its fields (such as drv->manual_bind in bind_mode_store() and
serio_unregister_driver()), so creating an exclusive &mut
bindings::serio_driver before serio_unregister_driver() completes is
undefined behavior.  Wrapping bindings::serio_driver in Opaque avoids
forming an exclusive reference to C-owned memory.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261106191714.334055-1-harepro29@gmail.com?part=2

^ permalink raw reply	[flat|nested] 7+ messages in thread

* Re: [PATCH 3/3] input: joystick: stinger: port Gravis Stinger driver to safe Rust
  2026-11-06 19:17 ` [PATCH 3/3] input: joystick: stinger: port Gravis Stinger driver to safe Rust clicedvly768
@ 2026-11-06 19:42   ` sashiko-bot
  0 siblings, 0 replies; 7+ messages in thread
From: sashiko-bot @ 2026-11-06 19:42 UTC (permalink / raw)
  To: clicedvly768; +Cc: linux-input, dmitry.torokhov, ojeda, gary

Thank you for your contribution! Sashiko AI review found 10 potential
issues to consider:
- [High] Input: stinger - built-in Rust input/serio fails link when
  INPUT/SERIO=m/n
- [Medium] Input: stinger - depends on RUST drops non-Rust support and
  breaks defconfig
- [Medium] Input: stinger - missing MODULE_DEVICE_TABLE breaks module
  autoloading
- [Medium] Input: stinger - missing input_dev parent in connect() breaks
  sysfs hierarchy
- [Medium] Input: stinger - connect() registers input_dev before
  serio_open()
- [Medium] Input: stinger - driver registration uses helper THIS_MODULE
  instead of owner
- [Medium] rust: input: unsound set_phys() and set_abs_params() on
  AllocatedDevice
- [Medium] rust: serio: missing sentinel guarantee on Driver::ID_TABLE
  slice
- [Medium] rust: serio: missing Opaque wrapper for serio_driver in
  Registration
- [Low] rust: serio: negated to_errno() in
  Registration::connect_callback()
--

commit c0702275451987ccba043dca381ae440cb19b04d
Author: clicedvly768 <harepro29@gmail.com>

input: joystick: stinger: port Gravis Stinger driver to safe Rust

This commit replaces the C Gravis Stinger serial gamepad driver
(drivers/input/joystick/stinger.c) with a Rust implementation
(drivers/input/joystick/stinger.rs) and makes CONFIG_JOYSTICK_STINGER
depend on CONFIG_RUST.

> diff --git a/drivers/input/joystick/Kconfig b/drivers/input/joystick/Kconfig
> index 7755e5b454d2c..e672a3bc6dccf 100644
> --- a/drivers/input/joystick/Kconfig
> +++ b/drivers/input/joystick/Kconfig
> @@ -188,6 +188,7 @@ config JOYSTICK_SPACEBALL
>  	  module will be called spaceball.
>  
>  config JOYSTICK_STINGER
> +	depends on RUST
>  	tristate "Gravis Stinger gamepad"
>  	select SERIO
>  	help

[Severity: Medium]
Does adding depends on RUST directly to JOYSTICK_STINGER while deleting
drivers/input/joystick/stinger.c cause a hardware support regression on
non-Rust configurations and architectures without HAVE_RUST?

For example, arch/powerpc/configs/ppc6xx_defconfig enables
CONFIG_JOYSTICK_STINGER=m without CONFIG_RUST, so the driver is silently
dropped from that defconfig. Documentation/input/joydev/joystick.rst also
still states that the device is supported by the stinger.c module.

[Severity: High]
Can enabling CONFIG_RUST=y with CONFIG_INPUT=m or CONFIG_SERIO=m (such as
CONFIG_JOYSTICK_STINGER=m, which only selects SERIO under if INPUT) break
the vmlinux link?

CONFIG_RUST is a bool option, so rust/kernel.o and rust/helpers/helpers.o
are always linked into vmlinux, and both unconditionally compile the input
and serio abstractions and C helpers without guarding on CONFIG_INPUT=y or
CONFIG_SERIO=y. When CONFIG_INPUT or CONFIG_SERIO is modular or disabled,
built-in code in rust/kernel/input.rs and rust/helpers/{input,serio}.c
references input_allocate_device(), input_register_device(), input_event(),
__serio_register_driver(), and serio_unregister_driver(), which are either
in loadable modules or not built at all.

[ ... ]

> diff --git a/drivers/input/joystick/stinger.rs b/drivers/input/joystick/stinger.rs
> new file mode 100644
> index 0000000000000..daa1994636315
> --- /dev/null
> +++ b/drivers/input/joystick/stinger.rs

[ ... ]

> +impl serio::Driver for StingerDriver {
> +    type Data = KBox<Stinger>;
> +
> +    const ID_TABLE: &'static [serio::DeviceId] = &[
> +        serio::DeviceId::new(
> +            bindings::SERIO_RS232 as u8,
> +            bindings::SERIO_ANY as u8,
> +            bindings::SERIO_ANY as u8,
> +            bindings::SERIO_STINGER as u8,
> +        ),
> +        serio::DeviceId::new(0, 0, 0, 0),
> +    ];

[Severity: Medium]
Does dropping MODULE_DEVICE_TABLE(serio, stinger_serio_ids) without a
replacement module_device_table! or module alias entry break automatic
module loading when CONFIG_JOYSTICK_STINGER=m?

Without the exported device table symbol, modpost no longer emits
MODULE_ALIAS("serio:ty02pr1Eid*ex*") into stinger.ko, so udev/kmod cannot
autoload the module when serio_uevent() reports a matching serio port.

[Severity: Medium]
Can a safe implementation of serio::Driver omit the trailing zero entry in
ID_TABLE and cause an out-of-bounds read in serio_match_port()?

In rust/kernel/serio.rs, Driver::ID_TABLE is typed as a plain slice
&'static [DeviceId] rather than a compile-time zero-terminated array, and
Registration::new() passes T::ID_TABLE.as_ptr() directly to the C serio
core:

rust/kernel/serio.rs:Registration::new() {
    let drv = bindings::serio_driver {
        description: name.as_char_ptr().cast(),
        id_table: T::ID_TABLE.as_ptr().cast::<bindings::serio_device_id>(),
}

Because serio_match_port() walks ids++ until both ids->type and ids->proto
are zero, any safe serio::Driver that omits the sentinel entry triggers an
out-of-bounds read past the slice.

> +
> +    fn connect(dev: &mut serio::Device) -> Result<Self::Data> {
> +        let mut input_alloc = AllocatedDevice::new()?;
> +
> +        input_alloc.set_name(DRIVER_DESC);
> +        input_alloc.set_phys(dev.phys().as_ptr());
> +        input_alloc.set_id(bus::RS232, bindings::SERIO_STINGER as u16, 0x0001, 0x0100);

[Severity: Medium]
Does StingerDriver::connect() register the input device with a NULL parent
instead of &serio->dev?

The C driver set input_dev->dev.parent = &serio->dev before calling
input_register_device(), whereas AllocatedDevice::new() wraps
input_allocate_device() without setting dev.parent. Registering with a NULL
parent places the device under /sys/devices/virtual/input/ instead of under
the serio port in sysfs, which breaks udev parent matching (such as ID_PATH
and seat assignment) and suspend/resume ordering.

[Severity: Medium]
Are AllocatedDevice::set_phys() and AllocatedDevice::set_abs_params() sound
as safe functions in rust/kernel/input.rs?

rust/kernel/input.rs:AllocatedDevice {
    pub fn set_phys(&mut self, phys: *const u8) {
        // SAFETY: `self.ptr` is valid.
        unsafe {
            (*self.ptr.as_ptr()).phys = phys.cast();
        }
    }
    ...
    pub fn set_abs_params(&mut self, axis: u32, min: i32, max: i32, fuzz: i32, flat: i32) {
        // SAFETY: `self.ptr` is valid.
        unsafe {
            bindings::input_set_abs_params(self.ptr.as_ptr(), axis, min, max, fuzz, flat);
        }
    }
}

set_phys() accepts an arbitrary raw pointer from safe code without any
validity, lifetime, or NUL-termination guarantee, even though the input core
dereferences dev->phys as a C string in input_dev_uevent(), sysfs, procfs,
and EVIOCGPHYS for the lifetime of the device. set_abs_params() passes an
unvalidated axis index to input_set_abs_params(), which executes
__set_bit(axis, dev->absbit) and indexes dev->absinfo[axis] without checking
that axis < ABS_CNT, allowing out-of-bounds writes from safe Rust.

> +
> +        // Configure supported buttons
> +        for btn in [
> +            bindings::BTN_A,
> +            bindings::BTN_B,
> +            bindings::BTN_C,
> +            bindings::BTN_X,
> +            bindings::BTN_Y,
> +            bindings::BTN_Z,
> +            bindings::BTN_TL,
> +            bindings::BTN_TR,
> +            bindings::BTN_START,
> +            bindings::BTN_SELECT,
> +        ] {
> +            input_alloc.set_capability(event_type::KEY, btn);
> +        }
> +
> +        // Configure 2-axis joystick with flat margin of 4
> +        input_alloc.set_capability(event_type::ABS, bindings::ABS_X);
> +        input_alloc.set_capability(event_type::ABS, bindings::ABS_Y);
> +        input_alloc.set_abs_params(bindings::ABS_X, -64, 64, 0, 4);
> +        input_alloc.set_abs_params(bindings::ABS_Y, -64, 64, 0, 4);
> +
> +        let registered = input_alloc.register()?;
> +
> +        let stinger = KBox::new(
> +            Stinger {
> +                input: registered,
> +                idx: 0,
> +                data: [0; STINGER_MAX_LENGTH],
> +            },
> +            GFP_KERNEL,
> +        )?;
> +
> +        Ok(stinger)
> +    }

[Severity: Medium]
Does StingerDriver::connect() publish the input device before the serio
port is opened?

In the C driver, stinger_connect() set the serio drvdata and called
serio_open() before calling input_register_device(). Here,
input_alloc.register() exposes the device to the input core and userspace
before KBox::new() allocates Stinger and before
Registration::connect_callback() calls serio_set_drvdata() and
serio_open():

rust/kernel/serio.rs:Registration::connect_callback() {
    let data = match T::connect(&mut dev) {
        Ok(d) => d,
        Err(e) => return e.to_errno(),
    };

    let raw_data = data.into_foreign();
    unsafe {
        bindings::serio_set_drvdata(serio, raw_data.cast());
    }
    let ret = unsafe { bindings::serio_open(serio, drv) };
}

Userspace can therefore open the input node before the underlying serio port
is opened, and a failure in KBox::new() or serio_open() registers and
immediately unregisters the input device, emitting spurious uevents.

[Severity: Low]
In Registration::connect_callback() in rust/kernel/serio.rs, does the null
check return a positive value instead of a negative errno?

rust/kernel/serio.rs:Registration::connect_callback() {
    let Some(serio_nn) = NonNull::new(serio) else {
        return -(crate::error::code::EINVAL.to_errno());
    };
}

Error::to_errno() already returns a negative errno (-22), so negating it
returns +22 instead of -EINVAL.

[ ... ]

> +struct StingerModule {
> +    _reg: serio::Registration<StingerDriver>,
> +}

[Severity: Medium]
Does dropping serio::Registration<T> violate Rust aliasing rules on
bindings::serio_driver?

rust/kernel/serio.rs:Registration {
    drv: Pin<KBox<bindings::serio_driver>>,
    _p: PhantomData<T>,
}

rust/kernel/serio.rs:Registration::drop() {
    unsafe {
        bindings::serio_unregister_driver(self.drv.as_mut().get_mut());
    }
}

Once serio_register_driver() publishes the driver, the C serio core and
sysfs attributes (such as bind_mode_store(), which writes
serio_drv->manual_bind without locking) hold pointers to the struct and may
read or mutate it concurrently. Storing bindings::serio_driver without
kernel::types::Opaque and calling self.drv.as_mut().get_mut() in drop()
creates an exclusive &mut reference while C still has active aliases.

> +
> +impl kernel::Module for StingerModule {
> +    fn init(_module: &'static ThisModule) -> Result<Self> {
> +        let reg = serio::Registration::<StingerDriver>::new(DRIVER_NAME)?;
> +        pr_info!("Gravis Stinger safe Rust driver initialized\n");
> +        Ok(Self { _reg: reg })
> +    }
> +}

[Severity: Medium]
Does serio::Registration::new() register the driver with the helper
translation unit's THIS_MODULE and KBUILD_MODNAME instead of the driver
module's owner and name?

StingerModule::init() ignores _module, and Registration::new() calls
rust_helper_serio_register_driver():

rust/helpers/serio.c:rust_helper_serio_register_driver() {
	return __serio_register_driver(drv, THIS_MODULE, KBUILD_MODNAME);
}

Because rust/helpers/serio.c is compiled into the built-in helpers object
rather than into stinger.ko, THIS_MODULE is NULL and KBUILD_MODNAME is
"helpers". When CONFIG_JOYSTICK_STINGER=m, drv->driver.owner is NULL and
drv->driver.mod_name is "helpers", so the driver core cannot pin the module
reference count and /sys/bus/serio/drivers/stinger/module linkage is
broken. Registration::new() should accept &'static ThisModule and pass
module.as_ptr() and module name to __serio_register_driver().

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261106191714.334055-1-harepro29@gmail.com?part=3

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2026-11-06 19:42 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-06 19:17 [PATCH 0/3] rust: input: add input/serio abstractions and port Gravis Stinger driver clicedvly768
2026-11-06 19:17 ` [PATCH 1/3] rust: input: add input device abstractions clicedvly768
2026-11-06 19:29   ` sashiko-bot
2026-11-06 19:17 ` [PATCH 2/3] rust: serio: add serio bus abstractions clicedvly768
2026-11-06 19:35   ` sashiko-bot
2026-11-06 19:17 ` [PATCH 3/3] input: joystick: stinger: port Gravis Stinger driver to safe Rust clicedvly768
2026-11-06 19:42   ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox