hwmon: (tmp108) add Rust TMP108 driver
Subsystems (2)
A message that is not in the archive (sent off-list or not yet received): [email protected]
PATCH 1/2 rust: hwmon: add hwmon abstractions
Quoted 1 line
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: skxby <[email protected]>
Date: Fri, 16 Oct 2026 15:12:27 +0800
Subject: [PATCH 1/2] rust: hwmon: add hwmon abstractions
Add Rust abstractions for the hwmon subsystem.
The main type is Registration<T>, which owns and pins its inner state, registers the hwmon device, and unregisters it on drop. A Driver trait provides callbacks for the temperature and chip attribute families; the chip callbacks are optional, following the existing #[vtable] idiom used by other subsystems. Channel configuration masks are derived from the modeled attribute enums.
This is a rework of the abstraction proposed in the RFC "rust: hwmon:
add basic hwmon abstractions" [1], brought up to the current rust tree:
registration does not use devm, the sensor type enumeration covers the chip family in addition to the temperature family, and the resource is released explicitly on the registration error path.
[1] https://lore.kernel.org/all/[email protected]/
--- rust/bindings/bindings_helper.h | 1 + rust/kernel/hwmon.rs | 491 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 3 files changed, 494 insertions(+) create mode 100644 rust/kernel/hwmon.rs
rust/bindings/bindings_helper.h +1 -0
@@ -62,6 +62,7 @@#include <linux/firmware.h> #include <linux/fwctl.h> #include <linux/fs.h> +#include <linux/hwmon.h> #include <linux/i2c.h> #include <linux/interrupt.h> #include <linux/io-pgtable.h>
rust/kernel/hwmon.rs new file +491 -0
491 lines not on this page · raw message
rust/kernel/lib.rs +2 -0
@@ -80,6 +80,8 @@ pub mod fs;pub mod fwctl;#[cfg( CONFIG_GPU_BUDDY = "y" )] pub mod gpu; +#[cfg( CONFIG_HWMON = "y" )] +pub mod hwmon;#[cfg( CONFIG_I2C = "y" )] pub mod i2c;pub mod id_pool;
[email protected]
AI reviewRe: [PATCH 1/2] rust: hwmon: add hwmon abstractions
Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider: - [High] hwmon: use-after-free of hwdev->name due to unconstrained &CStr lifetime - [High] hwmon…
Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:
- [High] hwmon: use-after-free of hwdev->name due to unconstrained &CStr lifetime
- [High] hwmon: out-of-bounds read due to missing null-terminator in chip_config
- [High] hwmon: linker error for drivers omitting #[optional] chip_read/write
- [Medium] hwmon: missing hwmon_lock() API and incorrect locking documentation
- [Medium] hwmon: manual pointer wiring bypasses required pin-init API
- [Low] hwmon: abstraction limits drivers to a single temperature channel
- [Low] hwmon: missing #[inline] attribute on Registration drop method
--
commit a2d95b04547e27fa736c176ee2cb6a3c7255a3eb
Author: skxby <[email protected]> Date: Fri Oct 16 15:12:27 2026 +0800
rust: hwmon: add hwmon abstractions
Add Rust abstractions for the hwmon subsystem, supporting temp[1-*] attributes and chip-level attributes. Registration owns its inner state and uses a Driver trait for callbacks.
Quoted 5 lines
rust/kernel/hwmon.rs new file +0
-0
[ ... ]
rust/kernel/hwmon.rs line 139
Quoted 5 lines
rust/kernel/hwmon.rs new file +5
-0+/// The hwmon driver trait. +/// +/// # Concurrency and Driver Responsibilities +/// +/// The hwmon C core provides **no internal locking** for attribute access. When user-space
^^^^^^^^^^^^^^^^^^^^^^
[Severity: Medium]
This isn't a bug, but is this statement accurate?
The documentation incorrectly claims that the 'hwmon C core provides no internal locking for attribute access'. The C core uses a per-device mutex (guard(mutex)(&hwdev->lock)) during sysfs attribute reads and writes.
Furthermore, the hwmon subsystem guidelines explicitly state that drivers should use hwmon_lock() and hwmon_unlock() to implement locking required for interrupt handling. This abstraction fails to expose or wrap these functions, making it impossible for Rust drivers to comply with this official rule.
Quoted 2 lines
rust/kernel/hwmon.rs new file +2
-0+/// reads or writes `/sys/class/hwmon/hwmon*/temp*_*`, the core directly invokes the +/// registered callbacks with a **shared `&self` reference** to `HwmonInner<T>`.
[ ... ]
Quoted 8 lines
rust/kernel/hwmon.rs new file +8
-0+unsafe extern "C" fn read_callback ( + dev: *mut bindings::device , + type_:u32 , + attr:u32 , + channel:c_int , + val: *mut c_long , + ) ->c_int { +from_result (|| {
[ ... ]
rust/kernel/hwmon.rs line 250
Quoted 2 lines
rust/kernel/hwmon.rs new file +2
-0+let result =match SensorType ::try_from (type_)? { +SensorType ::Chip =>T ::chip_read (&inner.driver,ChipAttr ::try_from (attr)?)?,
^^^^^^^^^^^
[Severity: High]
Does this code cause a compilation failure for drivers that do not implement the optional chip methods?
The Driver trait marks chip_read and chip_write as #[optional]. The #[vtable] macro replaces missing optional methods with a build_error!() call. Here, the calls to T::chip_read and T::chip_write are unconditional within the dynamically evaluated SensorType::Chip branch.
Because the compiler cannot prove this branch is dead at compile time, the build_error!() call is retained in the binary, causing a fatal linker error for any driver that chooses not to implement these methods.
Should the calls be guarded by if T::HAS_CHIP_READ and if T::HAS_CHIP_WRITE?
Quoted 5 lines
rust/kernel/hwmon.rs new file +5
-0+// C core guarantees `channel >= 0`. + SensorType::Temp => { +T ::read (&inner.driver,TempAttr ::try_from (attr)?, channelas u32 )? + } + };
[ ... ]
rust/kernel/hwmon.rs line 352
Quoted 6 lines
rust/kernel/hwmon.rs new file +6
-0+fn new_placeholder (driver:T ) ->Self { +// A driver that exposes no chip attribute must not advertise the chip channel +// either: leaving `chip_config` zeroed makes the channel carry no attributes, and +// `is_visible` would not be consulted for it in the first place. +let chip_config =if T ::HAS_CHIP_IS_VISIBLE { + [CHIP_ATTR_MASK ]
^^^^^^^^^^^^^^^^
[Severity: High]
Can this out-of-bounds read adjacent memory when the C core reads the configuration?
The C hwmon core strictly requires the hwmon_channel_info.config array to be null-terminated (ending with a 0). Here, chip_config is defined as [u32; 1] and initialized to [CHIP_ATTR_MASK]. It lacks a trailing 0 terminator.
When hwmon_device_register_with_info reads the channel configuration, it will fail to stop at the end of chip_config and read past the array bounds into adjacent memory, which can cause the C core to misinterpret memory as attribute masks.
Quoted 5 lines
rust/kernel/hwmon.rs new file +5
-0+ }else { + [0 ] + }; + +Self {
rust/kernel/hwmon.rs line 367
Quoted 10 lines
rust/kernel/hwmon.rs new file +10
-0+ driver, + ops: bindings::hwmon_ops { + is_visible: Some(Adapter::<T>::is_visible_callback), + visible: 0, + read: Some(Adapter::<T>::read_callback), + read_string: None, + write: Some(Adapter::<T>::write_callback), + }, + chip_config, + temp_config: [TEMP_ATTR_MASK, 0],
^^^^^^^^^^^^^^^^^
[Severity: Low]
Does this hardcoded array strictly limit the abstraction to a single temperature channel?
The commit message asserts that the abstraction supports registering temperature sensors with the full standard temp[1-*] attribute set. However, this single configuration mask means the C core will only create attributes for temp1_* and will never query channel > 0, preventing drivers from registering multiple temperature sensors.
Quoted 4 lines
rust/kernel/hwmon.rs new file +4
-0+ chip_channel: bindings::hwmon_channel_info { + type_:0 , + config: core::ptr::null (), + },
[ ... ]
rust/kernel/hwmon.rs line 411
Quoted 4 lines
rust/kernel/hwmon.rs new file +4
-0+pub fn new (parent: &Device <Bound >, name: &CStr , data:T ) ->Result <Self > { +let mut boxed =KBox ::new (HwmonInner ::new_placeholder (data),GFP_KERNEL )?; + +// Wire self-referential pointers before pinning. We obtain a mutable raw pointer
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[Severity: Medium]
Does this manual pointer wiring bypass the required pin-init API?
The Rust subsystem guidelines require that try_pin_init! or pin_init! be used to initialize structs that require pinning. The abstraction bypasses this safe pin-init framework by allocating a KBox, acquiring a raw pointer, mutating fields unsafely to wire self-referential pointers, and manually calling Pin::new_unchecked.
Quoted 3 lines
rust/kernel/hwmon.rs new file +3
-0+// from the uniquely-owned `KBox` -- no intermediate `&mut` reference is created, +// so no aliasing rules are violated. +let inner_ptr: *mut HwmonInner <T > = &raw mut *boxed;
[ ... ]
rust/kernel/hwmon.rs line 451
Quoted 8 lines
rust/kernel/hwmon.rs new file +8
-0+// SAFETY: `chip_info` and all nested pointers target memory within the same +// allocation, which remains valid until `hwmon_device_unregister` in `Drop`. +// `parent.as_raw()` and `name.as_char_ptr()` are valid. The name is copied by +// the kernel (via `dev_set_name` -> `kvasprintf_const`), so no lifetime issue. + let hwmon_dev = from_err_ptr(unsafe { + bindings::hwmon_device_register_with_info( + parent.as_raw(), + name.as_char_ptr(),
^^^^^^^^^^^^^^^^^^
[Severity: High]
Can this cause a use-after-free of hwdev->name?
The Registration::new function accepts a name: &CStr parameter without a lifetime constraint tying it to the Registration object. The C core stores this pointer directly in hwdev->name (which is returned by the sysfs name_show attribute) without copying the string.
If a caller passes a temporary string (e.g., a short-lived CString), the string will be freed after registration. When userspace later reads /sys/class/hwmon/hwmon*/name, the C core will dereference the freed memory.
rust/kernel/hwmon.rs line 463
Quoted 12 lines
rust/kernel/hwmon.rs new file +12
-0+ drvdata, + &raw const (*inner_ptr).chip_info, + core::ptr::null_mut(), + ) + })?; + +Ok (Self { hwmon_dev, inner }) + } +} + +impl <T :Driver >Drop for Registration <T > { +fn drop (&mut self) {
^^^^^^^
[Severity: Low]
This isn't a bug, but should this method have an #[inline] attribute?
According to the Rust subsystem guidelines, small functions or functions forwarding to a C binding call in abstractions should be annotated with #[inline]. This method forwards directly to bindings::hwmon_device_unregister but lacks this required annotation.
Quoted 5 lines
rust/kernel/hwmon.rs new file +5
-0+// SAFETY: `hwmon_dev` was returned by a successful registration. This call waits for +// all in-flight callbacks before returning. +unsafe { bindings::hwmon_device_unregister (self.hwmon_dev) }; + } +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH 2/2 hwmon: (tmp108) add Rust TMP108 driver
In reply to a message not in the archiveQuoted 1 line
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: skxby <[email protected]>
Date: Fri, 16 Oct 2026 15:12:27 +0800
Subject: [PATCH 2/2] hwmon: (tmp108) add Rust TMP108 driver
Add a Rust driver for the TI TMP108 temperature sensor, mirroring the existing C driver (drivers/hwmon/tmp108.c).
The driver exposes seven temperature attributes (input, min, max, min_hyst, max_hyst, min_alarm, max_alarm) plus update_interval on the chip channel. Numeric and error semantics follow the C driver:
millidegree conversion with truncation, write clamping, absolute-value hysteresis, four conversion-rate buckets selected with the same closest-descending search, and EAGAIN while a one-shot conversion is not ready.
--- samples/rust/Kconfig | 21 ++ samples/rust/Makefile | 2 + samples/rust/tmp108.rs | 573 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 596 insertions(+) create mode 100755 samples/rust/tmp108.rs
samples/rust/Kconfig +21 -0
@@ -172,6 +172,27 @@ config SAMPLE_RUST_DRIVER_SERDEV If unsure, say N. +config SAMPLE_RUST_HWMON + tristate "Hwmon Driver" + depends on HWMON=y + help + This option builds the Rust hwmon driver sample. + + To compile this as a module, choose M here: + the module will be called rust_driver_hwmon. + + If unsure, say N. + +config SAMPLE_RUST_TMP108 + tristate "TMP108 Driver" + depends on HWMON=y + depends on I2C=y + help + This option builds the Rust TMP108 temperature sensor driver. + + To compile this as a module, choose M here: + the module will be called tmp108. + config SAMPLE_RUST_SOC tristate "SoC Driver" select SOC_BUS
samples/rust/Makefile +2 -0
@@ -16,6 +16,8 @@ obj-$(CONFIG_SAMPLE_RUST_DRIVER_FAUX) += rust_driver_faux.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_AUXILIARY) += rust_driver_auxiliary.o obj-$(CONFIG_SAMPLE_RUST_DRIVER_SERDEV) += rust_driver_serdev.o obj-$(CONFIG_SAMPLE_RUST_CONFIGFS) += rust_configfs.o +obj-$(CONFIG_SAMPLE_RUST_HWMON) += rust_driver_hwmon.o +obj-$(CONFIG_SAMPLE_RUST_TMP108) += tmp108.o obj-$(CONFIG_SAMPLE_RUST_SOC) += rust_soc.o rust_print-y := rust_print_main.o rust_print_events.o
samples/rust/tmp108.rs new file +573 -0
573 lines not on this page · raw message
[email protected]
AI reviewThank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] hwmon: tmp108: panic via arithmetic underflow in write_update_interval() - [Medium] hwmon/tmp108…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] hwmon: tmp108: panic via arithmetic underflow in write_update_interval()
- [Medium] hwmon/tmp108: missing hardware initialization in init
- [Low] hwmon: hardware monitoring driver registered from outside drivers/hwmon/ violates layering
- [Low] kconfig: SAMPLE_RUST_TMP108 tristate config depends on HWMON=y preventing module builds --
commit 78120c93b1be27841c1bf9909b41399a14b830f6
Author: skxby <[email protected]>
hwmon: (tmp108) add Rust TMP108 driver
Add a Rust driver for the TI TMP108 temperature sensor, mirroring the existing C driver (drivers/hwmon/tmp108.c).
Quoted 4 lines
samples/rust/Kconfig +0
-0
[ ... ]
samples/rust/Kconfig config SAMPLE_RUST_DRIVER_SERDEV · line 189
Quoted 4 lines
samples/rust/Kconfig +4
-0+config SAMPLE_RUST_TMP108 + tristate "TMP108 Driver" + depends on HWMON=y + depends on I2C=y
[Severity: Low]
Does this introduce a Kconfig regression? If CONFIG_HWMON=m or CONFIG_I2C=m, this prevents the sample driver from being built at all, even as a module.
Should standard dependency strings like depends on HWMON and depends on I2C be used to inherit module constraints properly?
Quoted 5 lines
samples/rust/tmp108.rs new file +0
-0
[ ... ]
Quoted 1 line
+fn
find_closest_descending(x: c_long, samples: &[u16])-> usize {
[ ... ]
samples/rust/tmp108.rs line 155
Quoted 4 lines
samples/rust/tmp108.rs new file +4
-0+while i >=1 { +let mid = (samples[i]as c_long + samples[i -1 ]as c_long ) /2 ; +if x <= mid { +let left = x - samples[i]as c_long ;
[Severity: High]
Can this code panic due to an arithmetic underflow regression?
If userspace writes a large negative value (e.g., LONG_MIN) to the update_interval sysfs attribute, it is passed unmodified to this function.
Subtracting a positive sample value from c_long::MIN will underflow here.
In debug builds or when CONFIG_RUST_OVERFLOW_CHECKS=y is set, this triggers a panic, crashing the kernel. In release builds, it silently wraps around and sets an incorrect hardware conversion rate.
Could we clamp the value before subtraction, or use saturating math?
[ ... ]
samples/rust/tmp108.rs line 326
Quoted 2 lines
samples/rust/tmp108.rs new file +2
-0+fn write_update_interval (&self, value:c_long ) ->Result { +let idx =find_closest_descending (value, &SAMPLE_TIMES );
[Severity: High]
Is it possible to pass an unclamped value here?
Since the value passed from userspace via sysfs is not clamped before calling find_closest_descending(), an extreme negative value can reach the subtraction above and cause an underflow panic.
[ ... ]
Quoted 1 line
+ fn
init(_module: &'static ThisModule)-> Result<Self> {
[ ... ]
samples/rust/tmp108.rs line 541
Quoted 6 lines
samples/rust/tmp108.rs new file +6
-0+// Registration failure path: if `Registration::new` fails and `?` returns early, the +// already-created i2c client is never unregistered. Such a leftover client keeps the +// bus address 0x48 occupied forever, making every subsequent insmod fail with EBUSY. +// The failure branch must therefore unregister the client explicitly (cleanup on the +// hwmon side is handled by the hwmon core itself). +let hwmon =match Registration ::new (parent,c"tmp108" ,Tmp108 ::new (client)) {
[Severity: Low]
Does registering a hardware monitoring device from outside drivers/hwmon/ violate subsystem layering rules?
The HWMON subsystem guidelines state that hardware monitoring drivers should reside in drivers/hwmon/. While this is a sample driver, directly using the hwmon registration API from samples/rust/ bypasses this architectural layout rule.
[Severity: Medium]
Are we missing hardware initialization for the TMP108 device during init?
Unlike the C driver, this code registers the hwmon device without enabling the regulator or configuring the CONF register (e.g., writing TMP108_MODE_CONTINUOUS and clearing TMP108_CONF_TM).
If the chip is in shutdown mode from the bootloader, continuous conversions will not occur, and accessing sysfs attributes like temp1_input could return stale temperature readings to userspace.
Quoted 10 lines
samples/rust/tmp108.rs new file +10
-0+ Ok(hwmon) => hwmon, + Err(e) => { +// SAFETY: client was created successfully in this function (non-null, +// non-ERR_PTR) and is not yet owned by hwmon (registration failed), so no +// in-flight callback touches the pointer. +unsafe { bindings::i2c_unregister_device (client) }; +return Err (e); + } + }; +
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2