From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.216.50 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796144135; b=ma/1VvKFfnlyblMfcuCZrk8uuNGn/yfiNu1i4lTvSgW+0Bu+h7hTdeML/DJJikIj+bBk Eq9V7WiHnwC7LfDf9flskIxcVL30ktRRWEEzQJxpux7kkR4penBquEshv03rXMBW+Kiy+ MpA07KRcYDrr+PNCah8VUUezGuYbWTSYo53P3f9hhZRnoe0jEILF0WwPmZxQCAwKN/yP8 NtKkM3PHVpeD+XS3eML0jdXoPtYVKbg1/dC433PaT2v03fhRgqelntpz5TsOUubDVdyv3 zc4FmiQxrCEaTYP/LD8J6r/EQxhZhHaf5zalSDKGvXjjmw0g6/dF0IzhlY65LK650Ww== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796144135; h=DMARC-Filter:Received:DKIM-Signature:X-Google-DKIM-Signature: X-Forwarded-Encrypted:X-Gm-Message-State:X-Gm-Gg:X-Received:Received: From:To:Cc:Subject:Date:Message-ID:X-Mailer:In-Reply-To:References: MIME-Version:Content-Transfer-Encoding; bh=+ZiZY8eRJeol/P6Cm2zfcon817KlgiPZf8ZceJNp1PM=; b=PyXs6aJCFmNtFqHani/TxWXSAjbq/xADzPKFq1dDAODlVyL/dmVPJ6tYPyJ+PG9q7wW+ 9MTyxT7p0UX63VHgp1SoT7c7X8WOYs1pope7FLpYc1/2eNIiGbjsuIMsoew4Y9RvQriIx Z+XUusKCovWDCuIf5e8DsDJVSGbej8UsF1jvN4ei0jOfD7SSwhcEwcNlQhrnuDniq0uzN fFBk48x/4gln1IFmZjiMEpq66J+gt+a3APbzdhlWQ3cU1I3iIjqhzr7luzmijQnAelF9l ujd1R7TaUa7KXHBHpNM9sOg77ORbo9235UUwUIDjmA9qh5WMAgiRHngWQylZFHba7xg== ARC-Authentication-Results: i=1; smtp.subspace.kernel.org; dmarc=pass header.from=gmail.com; spf=pass smtp.mailfrom=gmail.com; dkim=pass header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=z7DqpAuq; arc=none smtp.remote-ip=209.85.216.50 Received: from mail-pj1-f50.google.com (mail-pj1-f50.google.com [209.85.216.50]) (using TLSv1.3 with cipher TLS_AES_128_GCM_SHA256 (128/128 bits) key-exchange X25519 server-signature ECDSA (prime256v1) server-digest SHA256) (No client certificate requested) by smtp.subspace.kernel.org (Postfix) with ESMTPS id F3B1460A3831 for ; Tue, 1 Dec 2026 16:55:34 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org F3B1460A3831 Authentication-Results: smtp.subspace.kernel.org; dmarc=pass (p=none dis=none) header.from=gmail.com Authentication-Results: smtp.subspace.kernel.org; spf=pass smtp.mailfrom=gmail.com Authentication-Results: smtp.subspace.kernel.org; dkim=pass (2048-bit key) header.d=gmail.com header.i=@gmail.com header.a=rsa-sha256 header.s=20260707 header.b=z7DqpAuq Received: by mail-pj1-f50.google.com with SMTP id 98e67ed59e1d1-3b520f1604fso2502805a91.2 for ; Tue, 01 Dec 2026 08:55:34 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796144134; x=1796748934; darn=vger.kernel.org; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:from:to:cc:subject:date :message-id:reply-to:content-type; bh=+ZiZY8eRJeol/P6Cm2zfcon817KlgiPZf8ZceJNp1PM=; b=z7DqpAuqDY/VEe1a/l7ZbMt0o786izkbtvfE0+2HDYoCY7qdgvQNuNERokVSebGXMB 2dpU50D46iS1WD/2HBtAgGJ7njArw4PLXbcgvxW03XrNBEg0G0QcKc5DbHJaQZcqoKpY jp2fCE0Pf4sSZ17u+9e8FUSzKYXY/IaJgxfwayBSIyPRglt8VS4nOiM9Ltxwz9B3S/XP ldIYI8uN8gZWi3IOwu5nvgTyBtYVeeoOYpWaLoE9GRSr2djkaLclKRh2VzFDg9kdPXIU +2GrDGj/pw3A5+UnW5hnyADorsHmVDBmMUqxvApFbLrAl1fJdn8xOmCGXHPEIUbl+m9N 8irQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796144134; x=1796748934; h=content-transfer-encoding:mime-version:references:in-reply-to :message-id:date:subject:cc:to:from:x-gm-gg:x-gm-message-state:from :to:cc:subject:date:message-id:reply-to:content-type; bh=+ZiZY8eRJeol/P6Cm2zfcon817KlgiPZf8ZceJNp1PM=; b=1DXxVfj/doZpoUM6BWJt6aANzjmSVacFijRLjxVFm/X7/5dPB8SkksUb3Hkmqso+XH 0qMb4zUqQGJCPGegcViv9w0Vvot77eQ87EGMfNZb7/MSfCnmbNdIORo86Qx0hyYjDmWy Ioe0h6iimqpqtj+x1IqQwmAZ2rP/uuPFzbR2fY0gUkmoyzXminD52FF4JitYr8pUx7JL 4ZfTNZ97jJoFULb957Bk6T52FVNYrC7ZL6JyfG+c2uCpehXOmyxUfNXA+k9ufhlME5Cm VAsKu74gySBYfqdwkMKAgaXSDmGlB29ZSXwHPBr63bibXK7F8uXH3SO1xpjkjkq0yOvu wdvw== X-Forwarded-Encrypted: i=1; AL+hErGDqRd1aKbAEJJgdi601w36SFCB/WOU1It4kmawa54sq2Mn4Ur1j6GN+3SQO5UAD2NHc1gnXXiqDnLlKL4=@vger.kernel.org X-Gm-Message-State: APuU4Z8CQT/41wXLmhb/xnZ7WqFZwg2Z14x34ycJo1RrrG5YgQLxWAhH YrH666Umn8fpRhH3pljz0z2dtDb/OYBEjvKRerJixcjZlpg9V70NHHR8 X-Gm-Gg: AZFdTZcRYecVyO9X5Tb5QNj3DPEpfCIxpjAcNDMNv0hMKzbbq7SXOs+XuvB85SW8dPN UffjFrgQjA8sKNp5MFMeCi8NSvT4TbEEK1o9kVAbjDmXKqfsftnvkKxJN02EDbVv0aCa8Lkwm1d A+4HnShhxWT+LnayYzJRxge1Evk4Z5RIof++vpv9narjI785SvAhZjvLFRIMpYkm+k5l0LKrgWc XTOfVxbCzOjcEGkPQagbunvqmjA4joYt8H0iISgMyjjwr48yZGgCUJBvqfZPwH1o1ZayiHFmw5X gObihPdue/enh+XdarlTc9nJ7bSnGIiv+vCsCHoCwx9QPd1c1/W55H3+dHRSbL4d+pTAgAxpSc7 TQC76rQphW4oR7VimsW9/ripZbqyNSOOYj3hYJ+jGmcwn4RmivEua0xqe3aSGK/RiIGWECWKemL V4eimxyxR3GEdjOXk8BqxzqXt+bCLiZ+089qsNXe/Z1w/A2c1qF0mRwBKUjelh8r4GUgl1vf0/c 2wWbKFyV4+WnMdULPdEnrWZGSLJfYmcb2q7eR7yD8xtePWkZRVDXHLBuX6TLRTTBWUIqnfm/zke qHRVQI9oPhts07W0gHVfh1l32ilHkbmcE8YdiStkgT9UGEqo0nl5r5U17ks3qV3f6Ryu X-Received: by 2002:a17:90b:4a48:b0:3b3:c675:d923 with SMTP id 98e67ed59e1d1-3b41c908109mr34943136a91.28.1796144134024; Tue, 01 Dec 2026 08:55:34 -0800 (PST) Received: from localhost.localdomain ([36.68.98.203]) by smtp.gmail.com with ESMTPSA id 98e67ed59e1d1-3b44b73b2b3sm29159174a91.2.2026.12.01.08.55.28 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 01 Dec 2026 08:55:33 -0800 (PST) From: Muchamad Coirul Anwar To: Jonathan Cameron , Miguel Ojeda , Igor Korotin , Danilo Krummrich Cc: David Lechner , =?UTF-8?q?Nuno=20S=C3=A1?= , Andy Shevchenko , Andi Shyti , Daniel Almeida , Alice Ryhl , Mark Brown , Joshua Crofts , Markus Probst , Shuai Liu <847807867@qq.com>, linux-iio@vger.kernel.org, linux-i2c@vger.kernel.org, rust-for-linux@vger.kernel.org, driver-core@lists.linux.dev, linux-kernel@vger.kernel.org Subject: [RFC PATCH v8 3/4] rust: add minimal IIO subsystem abstractions Date: Tue, 1 Dec 2026 23:55:07 +0700 Message-ID: <20261201165508.39336-4-muchamadcoirulanwar@gmail.com> X-Mailer: git-send-email 2.50.0 In-Reply-To: <20261201165508.39336-1-muchamadcoirulanwar@gmail.com> References: <20261201165508.39336-1-muchamadcoirulanwar@gmail.com> X-Mailing-List: linux-kernel@vger.kernel.org List-Id: List-Post: List-Help: List-Subscribe: List-Unsubscribe: List-Owner: Precedence: list MIME-Version: 1.0 Content-Transfer-Encoding: 8bit Add minimal Rust abstractions needed to register direct-mode IIO devices exposing read_raw channel information. Provide a type-safe IioChanInfo selector, IioVal return types, and an IioDriver trait. Add a C callback trampoline that validates the channel information selector, invokes the Rust driver, and converts IioVal into the representation expected by the IIO core. Use typestate to distinguish unregistered and registered devices. Registration is unsafe because callers must not leak the returned device (e.g. via mem::forget). It returns an owned registered device bound to the parent lifetime, whose destructor unregisters it before destroying its Rust private data and releasing the allocation reference. Allow private data to borrow resources tied to the bound parent lifetime. This lets drivers capture bus-specific resources during probe and use them directly from subsystem callbacks without recovering them from a generic parent device. Accept only INDIO_DIRECT_MODE. Other modes require additional state and teardown handling not provided by this initial abstraction. The initial abstraction intentionally supports read_raw only. It does not expose write_raw, buffers, triggers, events, extended attributes, or available-value attributes. Suggested-by: Shuai Liu <847807867@qq.com> Link: https://lore.kernel.org/all/tencent_173B7731E90B9624F9F82613DC3031B70907@qq.com/ Link: https://lore.kernel.org/all/179286358623.55649.5397316745104390556@linux.dev/ Link: https://lore.kernel.org/all/179538281024.9825.4132712997497273037@linux.dev/ Co-developed-by: Igor Korotin Signed-off-by: Igor Korotin Signed-off-by: Muchamad Coirul Anwar --- include/linux/iio/iio.h | 6 +- rust/bindings/bindings_helper.h | 2 + rust/kernel/iio.rs | 519 ++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 2 + 4 files changed, 527 insertions(+), 2 deletions(-) create mode 100644 rust/kernel/iio.rs diff --git a/include/linux/iio/iio.h b/include/linux/iio/iio.h index 9b63785d5aec..e2ffb2b35126 100644 --- a/include/linux/iio/iio.h +++ b/include/linux/iio/iio.h @@ -450,8 +450,10 @@ struct iio_trigger; /* forward declaration */ * @read_raw: function to request a value from the device. * mask specifies which value. Note 0 means a reading of * the channel in question. Return value will specify the - * type of value returned by the device. val and val2 will - * contain the elements making up the returned value. + * type of value returned by the device. val and val2 + * point to writable integer storage valid for the + * duration of the callback. The return value determines + * which outputs contain meaningful data. * @read_raw_multi: function to return values from the device. * mask specifies which value. Note 0 means a reading of * the channel in question. Return value will specify the diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h index 3791af0aadc7..c2e2fb32ebe3 100644 --- a/rust/bindings/bindings_helper.h +++ b/rust/bindings/bindings_helper.h @@ -64,6 +64,8 @@ #include #include #include +#include +#include #include #include #include diff --git a/rust/kernel/iio.rs b/rust/kernel/iio.rs new file mode 100644 index 000000000000..4fb9959f6ee6 --- /dev/null +++ b/rust/kernel/iio.rs @@ -0,0 +1,519 @@ +// SPDX-License-Identifier: GPL-2.0 +// Copyright (C) 2026 Muchamad Coirul Anwar +//! IIO subsystem abstractions. +//! +//! Provides [`Device`] for allocating and registering an IIO device, and +//! [`IioDriver`] for implementing `read_raw` callbacks. Implementing the +//! trait requires validating the raw channel specifications. + +use crate::{ + bindings::{ + __iio_device_register, + iio_chan_spec, + iio_dev, + iio_device_alloc, + iio_device_free, + iio_device_unregister, + iio_info, + INDIO_DIRECT_MODE, // + }, + device::{ + self, + Bound, // + }, + error::{ + code::*, + to_result, + Result, // + }, + prelude::*, + ThisModule, // +}; + +use core::{ + marker::PhantomData, + mem::{ + forget, + size_of, // + }, + num::NonZeroI32, + ptr::drop_in_place, // +}; + +/// IIO value type: single integer (`IIO_VAL_INT`). +pub const IIO_VAL_INT: c_int = crate::bindings::IIO_VAL_INT as c_int; + +/// IIO value type: integer plus micro part (`IIO_VAL_INT_PLUS_MICRO`). +pub const IIO_VAL_INT_PLUS_MICRO: c_int = crate::bindings::IIO_VAL_INT_PLUS_MICRO as c_int; + +/// IIO value type: integer plus nano part (`IIO_VAL_INT_PLUS_NANO`). +pub const IIO_VAL_INT_PLUS_NANO: c_int = crate::bindings::IIO_VAL_INT_PLUS_NANO as c_int; + +/// IIO value type: fractional (`IIO_VAL_FRACTIONAL`). +pub const IIO_VAL_FRACTIONAL: c_int = crate::bindings::IIO_VAL_FRACTIONAL as c_int; + +/// Generates a Rust enum wrapper for C `enum iio_chan_info_enum`. +/// +/// This macro creates a type-safe enum with automatic `TryFrom` +/// conversion. Drivers match directly on `IioChanInfo` variants in +/// `read_raw`, and the compiler enforces match exhaustiveness. +/// Additional variants can be added as drivers require them. +macro_rules! build_iio_chan_info_enum { + ( + $( + $(#[$meta:meta])* + $rust_name:ident = $c_const:ident + ),* $(,)? + ) => { + /// Channel information selector for [`IioDriver::read_raw`]. + /// + /// Wraps supported C `enum iio_chan_info_enum` values identifying + /// the requested channel information. + /// + /// Conversion from an unsupported value returns `EINVAL`. + #[repr(u32)] + #[derive(Debug, Clone, Copy, PartialEq, Eq)] + pub enum IioChanInfo { + $( + $(#[$meta])* + $rust_name = bindings::$c_const, + )* + } + impl TryFrom for IioChanInfo { + type Error = Error; + + #[inline] + fn try_from(value: u32) -> Result { + match value { + $( bindings::$c_const => Ok(IioChanInfo::$rust_name), )* + _ => Err(EINVAL), + } + } + } + }; +} + +build_iio_chan_info_enum! { + /// Raw unprocessed value from the channel (`IIO_CHAN_INFO_RAW`). + /// + /// For sensors, this is typically the ADC reading or register value + /// before any scaling or offset correction. + Raw = iio_chan_info_enum_IIO_CHAN_INFO_RAW, + + /// Scale factor for converting raw values to channel units + /// (`IIO_CHAN_INFO_SCALE`). + /// + /// Apply any offset before scaling: `(raw + offset) * scale`. + /// The unit is defined by the IIO ABI for the channel type. + Scale = iio_chan_info_enum_IIO_CHAN_INFO_SCALE, +} + +/// Represents the return value of a `read_raw` operation. +/// +/// Each variant corresponds to an `IIO_VAL_*` constant and tells the +/// IIO core how to format `val` and `val2` for userspace. +pub enum IioVal { + /// A single integer value. + Int(i32), + + /// A fractional value represented as `val / val2`. + /// The denominator is `NonZeroI32` to prevent division-by-zero in + /// `iio_format_value()`. + Fractional(i32, NonZeroI32), + + /// An integer part and a fractional part in millionths + /// (`IIO_VAL_INT_PLUS_MICRO`). + /// + /// For negative values, put the sign on the integer part, or on the + /// fractional part when the integer part is zero. For example, + /// `IntPlusMicro(-1, 500_000)` represents -1.5, and + /// `IntPlusMicro(0, -500_000)` represents -0.5. + IntPlusMicro(i32, i32), + + /// An integer part and a fractional part in billionths + /// (`IIO_VAL_INT_PLUS_NANO`). + /// + /// Uses the same sign convention as [`IioVal::IntPlusMicro`]. + IntPlusNano(i32, i32), +} + +/// Trait implemented by IIO driver private data. +/// +/// # Safety +/// +/// The channel specifications returned by `channels()` must satisfy the +/// IIO core's requirements. Channel types, modifiers, strings, and +/// pointer/count pairs must be valid. Referenced storage must remain +/// valid for every access by the IIO core. In particular, `type_` and +/// (when `modified` is set) `channel2` must be valid enum discriminants, +/// as the IIO core indexes name tables with them without bounds checks. +/// +/// Channels must not expose events, buffers, extended attributes, +/// available-value attributes, parent channel links (`parent`), or +/// `has_ext_scan_type` / `ext_scan_type`. All unsupported pointer and flag +/// fields must be null/zero. This abstraction currently supports only +/// channel information handled by its `read_raw` callback. +pub unsafe trait IioDriver: Send + Sync { + /// Called by the IIO core to read channel information. + /// + /// `chan` identifies the channel, and `info` selects the requested + /// information, such as its raw value or scale. Implementors must + /// capture bus-specific resources during initialization rather than + /// deriving them from a generic parent reference. + fn read_raw(&self, chan: *const iio_chan_spec, info: IioChanInfo) -> Result; + + /// Returns the channel specifications for this driver. + /// + /// An empty slice is rejected by `Device::build_device()`. + fn channels(&self) -> &'static [iio_chan_spec]; +} + +/// C-compatible trampoline for the `iio_info.read_raw` callback. +/// +/// # Safety +/// +/// Callers must ensure that: +/// - `indio_dev` points to a valid `iio_dev` allocated with space for `T`. +/// Its private data contains an initialized `T` that remains valid and +/// may be shared for the duration of this callback. +/// - `chan` points to a valid channel specification for `indio_dev`. +/// - `val` and `val2` are non-null, properly aligned pointers to writable +/// `c_int` storage valid for the duration of this callback. +/// - The parent of `indio_dev` remains bound for the entire callback. +/// Registration ownership and callback teardown must enforce this. +unsafe extern "C" fn read_raw_callback( + indio_dev: *mut iio_dev, + chan: *const iio_chan_spec, + val: *mut c_int, + val2: *mut c_int, + info: c_long, +) -> c_int { + // SAFETY: `indio_dev` is valid and was allocated with space for `T` in its + // private data area. The `priv_` field was initialized in `Device::build_device()`. + let priv_ptr = unsafe { (*indio_dev).priv_.cast::() }; + + // SAFETY: The callback contract guarantees that `priv_ptr` points to an + // initialized `T` that remains valid for the duration of this callback. + let driver = unsafe { &*priv_ptr }; + + // `info` is `long` from C. Negative values and values > u32::MAX + // are unsupported iio_chan_info variants; both map to EINVAL. + let info_enum = match u32::try_from(info) + .ok() + .and_then(|value| IioChanInfo::try_from(value).ok()) + { + Some(info) => info, + None => return EINVAL.to_errno(), + }; + + match driver.read_raw(chan, info_enum) { + Ok(IioVal::Int(v)) => { + // SAFETY: `val` is valid per the function's Safety contract above. + // `val2` is not written; `IIO_VAL_INT` signals to the IIO core + // that only `val` carries meaningful data. + unsafe { + *val = v; + } + IIO_VAL_INT + } + Ok(IioVal::Fractional(v, v2)) => { + // SAFETY: both `val` and `val2` are valid per the Safety contract. + unsafe { + *val = v; + *val2 = v2.get(); + } + IIO_VAL_FRACTIONAL + } + Ok(IioVal::IntPlusMicro(v, v2)) => { + // SAFETY: both `val` and `val2` are valid per the Safety contract. + unsafe { + *val = v; + *val2 = v2; + } + IIO_VAL_INT_PLUS_MICRO + } + Ok(IioVal::IntPlusNano(v, v2)) => { + // SAFETY: both `val` and `val2` are valid per the Safety contract. + unsafe { + *val = v; + *val2 = v2; + } + IIO_VAL_INT_PLUS_NANO + } + Err(e) => e.to_errno(), + } +} + +// Device: IIO device wrapper with typestate. + +/// Marker type for an unregistered IIO device. +pub struct Unregistered; + +/// Marker type for a registered IIO device. +pub struct Registered; + +/// An initialized IIO device awaiting registration. +/// +/// The device borrows its parent for `'parent`. This keeps the parent valid +/// from allocation through registration and until this wrapper is destroyed. +pub struct UnregisteredDevice<'parent, T: IioDriver> { + device: Device<'parent, T>, +} + +/// An owned IIO device with in-place initialized driver data. +/// +/// Dropping a registered device unregisters it before destroying the driver +/// data. Dropping either state then releases the allocation reference with +/// `iio_device_free`. +/// +/// # Invariants +/// +/// - `indio_dev` points to an `iio_dev` allocated by `iio_device_alloc`, +/// and this wrapper owns its allocation reference. +/// - Its private storage contains exactly one initialized `T` that remains +/// at a fixed address until destroyed. +/// - The parent used for allocation remains valid and bound for `'parent`. +/// - `registered` is true exactly when this wrapper owns a successful +/// registration that has not been undone. +/// - While registered, the private data, callback code, vtable, channel +/// specifications, names, and their referenced storage satisfy the +/// publication contract of `UnregisteredDevice::register`. +/// - Registered destruction revokes supported callback access before +/// destroying `T`. +pub struct Device<'parent, T: IioDriver, State = Unregistered> { + indio_dev: *mut iio_dev, + registered: bool, + _parent: PhantomData<&'parent device::Device>, + _data: PhantomData<(T, State)>, +} + +// SAFETY: +// - moving the wrapper does not move the separately allocated `iio_dev` +// or its pinned private `T`; +// - `IioDriver` requires `T: Send`; +// - ownership of registration, private-data destruction, and allocation +// release moves together with the wrapper; +// - the parent borrow remains valid for `'parent`. +unsafe impl<'parent, T: IioDriver, State> Send for Device<'parent, T, State> {} + +// SAFETY: +// - `IioDriver` requires `T: Sync` for shared callback access; +// - the wrapper exposes no mutable projection of `T` or `iio_dev`; +// - shared operations are performed through the IIO core and the +// synchronization required by the driver's `T` implementation; +// - the parent borrow remains valid for `'parent`. +unsafe impl<'parent, T: IioDriver, State> Sync for Device<'parent, T, State> {} + +impl<'parent, T: IioDriver, State> Drop for Device<'parent, T, State> { + fn drop(&mut self) { + if self.registered { + // SAFETY: `__iio_device_register` succeeded. + // + // iio_device_unregister() deletes the character device, disables + // buffers, clears `info` while holding `info_exist_lock`, and removes + // the remaining buffer sysfs state. Device removal also removes and + // drains its sysfs files. In-kernel read helpers that use + // `info_exist_lock` cannot race this `info` teardown. + // + // Any callback path not covered by those mechanisms requires a + // separate teardown proof before this abstraction can expose it. + unsafe { iio_device_unregister(self.indio_dev) }; + } + + // SAFETY: `priv_` was fully initialized in `build_device` via + // `pin_init::raw_try_init`. `drop_in_place` runs `T`'s destructor + // (including any pinned fields like Mutex). After that, `iio_device_free` + // calls `put_device` which decrements the kref. The underlying `iio_dev` + // memory is only freed when kref reaches 0. + unsafe { + let priv_ptr = (*self.indio_dev).priv_.cast::(); + drop_in_place(priv_ptr); + iio_device_free(self.indio_dev); + } + } +} + +impl<'parent, T: IioDriver> Device<'parent, T> { + // All remaining fields are optional pointers or callback slots initialized + // to NULL via `pin_init::zeroed()`, which the IIO core checks before use. + const VTABLE: iio_info = iio_info { + read_raw: Some(read_raw_callback::), + ..pin_init::zeroed() + }; + + /// Allocates an unregistered IIO device and initializes its driver data + /// in place. + /// + /// `parent` becomes the IIO device's parent. `name` supplies its name. + /// Only `INDIO_DIRECT_MODE` is supported. + /// + /// Returns `EINVAL` if `modes` is not `INDIO_DIRECT_MODE`, if the + /// private-data size or channel count cannot be represented by the + /// corresponding C type, if `T` is zero-sized, if the channel list is + /// empty, or if the private storage is not suitably aligned. + /// Allocation and initialization errors are propagated. + /// + /// Call [`UnregisteredDevice::register`] to register the device. + pub fn build_device( + parent: &'parent device::Device, + name: &'static CStr, + modes: u32, + init: impl PinInit, + ) -> Result> + where + Error: From, + { + if modes != INDIO_DIRECT_MODE { + return Err(EINVAL); + } + + let modes = c_int::try_from(modes).map_err(|_| EINVAL)?; + + let priv_size = c_int::try_from(size_of::()).map_err(|_| EINVAL)?; + if priv_size == 0 { + return Err(EINVAL); + } + + // SAFETY: `parent.as_raw()` returns a valid `struct device` pointer. + // `iio_device_alloc` allocates an `iio_dev` with `sizeof(T)` bytes of + // private data. Returns NULL on failure. + let indio_dev = unsafe { iio_device_alloc(parent.as_raw(), priv_size) }; + if indio_dev.is_null() { + return Err(ENOMEM); + } + + // SAFETY: `indio_dev` is non-null and was just successfully allocated by + // `iio_device_alloc`. Accessing `priv_` yields a pointer to zeroed + // memory (kzalloc'd) sized for `T`. + let priv_ptr = unsafe { (*indio_dev).priv_.cast::() }; + if !priv_ptr.is_aligned() { + // SAFETY: `indio_dev` was allocated by `iio_device_alloc` and `priv_` + // has not been initialized, so no destructor needs to run. + unsafe { iio_device_free(indio_dev) }; + return Err(EINVAL); + } + + // SAFETY: `priv_ptr` is aligned and points to exclusively owned storage + // large enough for `T`. The private data remains at a fixed address in + // the separate IIO allocation until it is dropped. On initialization + // failure, the error path only frees the allocation. + let init_result = unsafe { pin_init::raw_try_init(priv_ptr, init) }; + if let Err(e) = init_result { + // SAFETY: `pin_init` guarantees partial-init rollback internally. + // `priv_` memory was not fully initialized, so we only free the + // container without running `T`'s destructor. + unsafe { iio_device_free(indio_dev) }; + return Err(Error::from(e)); + } + + // INVARIANT: + // - `indio_dev` points to an allocation returned by `iio_device_alloc`; + // - this wrapper owns one allocation reference; + // - its private storage contains one fully initialized, pinned `T`; + // - `_parent` records the bound parent borrow used for allocation; + // - `_data` records ownership of `T` and the unregistered typestate; + // - registration has not succeeded, so `registered` is false. + let device = Self { + indio_dev, + registered: false, + _parent: PhantomData, + _data: PhantomData, + }; + + // SAFETY: `priv_ptr` points to the initialized `T` owned by `device`. + // It remains valid for this shared borrow. + let channels = unsafe { (*priv_ptr).channels() }; + if channels.is_empty() { + return Err(EINVAL); + } + + let num_channels = c_int::try_from(channels.len()).map_err(|_| EINVAL)?; + + // SAFETY: `priv_ptr` is now fully initialized. We set up the IIO + // device fields: + // - `name` and `channels` provide static storage references. + // - The caller of `register()` must uphold the publication lifetime + // requirements for module-backed metadata and its referenced storage. + // - The reference to `VTABLE` is promoted to static storage. + // - `modes` was checked to be `INDIO_DIRECT_MODE`, so registration + // does not expose unsupported buffer or trigger paths. + // - `T`'s `IioDriver` safety contract guarantees that the channel + // specifications and their referenced storage satisfy the IIO + // core's requirements. + unsafe { + (*indio_dev).name = name.as_char_ptr(); + (*indio_dev).info = &Self::VTABLE; + (*indio_dev).channels = channels.as_ptr(); + (*indio_dev).num_channels = num_channels; + (*indio_dev).modes = modes; + } + + Ok(UnregisteredDevice { device }) + } +} + +impl<'parent, T: IioDriver> UnregisteredDevice<'parent, T> { + /// Registers the IIO device. + /// + /// The returned owner unregisters the device when dropped. + /// + /// Dropping the returned [`Device`] calls `iio_device_unregister()`, which + /// drains sysfs callbacks (`device_del()` / `kernfs_drain()`) and clears + /// `indio_dev->info` under `info_exist_lock` so synchronized in-kernel + /// `read_raw` consumers cannot race private-data teardown. Note that some + /// preexisting C `inkern.c` metadata helpers do not take `info_exist_lock` + /// or a reference on `driver_module`; this abstraction relies on the same + /// module-lifetime assumptions as C IIO drivers. + /// + /// # Safety + /// + /// The caller must guarantee all of the following: + /// + /// - The returned [`Device`] must not be passed to `core::mem::forget()` or + /// otherwise leaked; its destructor must run before `'parent` ends and + /// before any resource borrowed by `T` becomes invalid or unbound. + /// Note that some buses (such as I2C via `devres_release_group()` in + /// `i2c_device_remove()`) release bus-managed devres resources during + /// `remove()` before `post_unbind_rust` drops driver data; drivers whose + /// callbacks rely on such resources must ensure the [`Device`] is + /// dropped (or access revoked) before those resources are released. + /// - `module` must be the module that defines `T`, its `IioDriver` + /// implementation, `name`, and the channel specifications returned by + /// `T::channels()`, and the module must not be unloaded while this + /// registration remains active (i.e. the returned [`Device`] must be + /// dropped during driver unbind / module exit). + /// - No other code path may unregister or destroy the underlying `iio_dev`. + #[inline] + pub unsafe fn register( + self, + module: &'static ThisModule, + ) -> Result> { + let Self { device } = self; + + // SAFETY: + // - `device.indio_dev` is fully initialized and owns its allocation reference; + // - its parent remains valid through the borrow recorded by `device`; + // - name, channels, modes, and the read callback have been installed; + // - the caller upholds this method's publication and lifetime requirements. + to_result(unsafe { __iio_device_register(device.indio_dev, module.as_ptr()) })?; + + // INVARIANT: + // - `__iio_device_register` succeeded exactly once; + // - ownership of the allocation and initialized `T` transfers from + // `device` to `registered`; + // - the parent borrow and private-data ownership are preserved; + // - this wrapper exclusively owns unregister, destruction of `T`, and + // release of the allocation reference; + // - `registered` is true exactly while that successful registration is + // owned by this wrapper. + let registered: Device<'parent, T, Registered> = Device { + indio_dev: device.indio_dev, + registered: true, + _parent: PhantomData, + _data: PhantomData, + }; + forget(device); + + Ok(registered) + } +} diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 1ab41129d557..ebd22ebdf796 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -85,6 +85,8 @@ #[cfg(CONFIG_I2C = "y")] pub mod i2c; pub mod id_pool; +#[cfg(CONFIG_IIO = "y")] +pub mod iio; #[doc(hidden)] pub mod impl_flags; pub mod init; -- 2.50.0