From mboxrd@z Thu Jan 1 00:00:00 1970 Authentication-Results: smtp.subspace.kernel.org; arc=none smtp.remote-ip=209.85.216.51 ARC-Seal: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; cv=none; t=1796144130; b=S9PGIE/RRn90+MYOv5L4Q8XUg/anZ3T4WpLigsuCehmMxr5zAG2ig+wjPwyJlNKT+5LS v/81UgqdlwnPhhzMZwafWEwLSjSJAGzfCF/rxM1WfzF6U5Y50AKSbuCD3OSlpRSBv709v PwaV5kHTLVom3uGMN8fa7DkKV8UTBsgY7qvswJ0HazgNMqQJIqUz06DD7eTDe/JjY5uDJ U6kALlPoHfzrFTl7BBVVgZtRT3+VxQH9Kcfeb0NZO+B3loj0MwJN2pqxFA8dyHUwJbxQs aZxXU0eM7gf4ZxP4CZJJrosL8/HkbiE4ev5TybypV3Rmy4xhOqHtO2xe/VgBwCdj68A== ARC-Message-Signature: i=1; d=subspace.kernel.org; s=arc20261015; a=rsa-sha256; c=relaxed/relaxed; t=1796144130; 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=1TM4I69yvvmWjCJqZLD5ta5VdIAfZbpVKAEW1xg3N4w=; b=P/6YKJw4bodbEhdcXlUjHeiGRVdqA4gmUxJCGQoiCMa1NGID7dhm2+3cm0ipWTzLbhPx cF5Q6dPh4cc8xK7lqkPdU6rQsxQdZzIiXVpbGEmDKDVwc6DtleMfW2thVaXl3tXA7y6W+ an6qQmfBao1Gug8q4w0qVCzkVivUgcQvaYQPgpjuGVmD63ZuZYhShBpiWemEon2Q8KPxr iozy8WxOSzlzMizyOx0LoMWs24PEduOv0n/MBYGp5RijRAw6tfewmxclGEad1wv39Ydj6 VhHl/fWgSy5BTv4N1vtt29/ByKN5sl/h3zO/bGPHT6i9icO0mSwi+GO8ahlJ762y0xQ== 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=T8M8z6nC; arc=none smtp.remote-ip=209.85.216.51 Received: from mail-pj1-f51.google.com (mail-pj1-f51.google.com [209.85.216.51]) (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 B28AA60A260F for ; Tue, 1 Dec 2026 16:55:29 +0000 (UTC) DMARC-Filter: OpenDMARC Filter v1.4.2 smtp.subspace.kernel.org B28AA60A260F 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=T8M8z6nC Received: by mail-pj1-f51.google.com with SMTP id 98e67ed59e1d1-3b421e8d111so7683119a91.3 for ; Tue, 01 Dec 2026 08:55:29 -0800 (PST) DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20260707; t=1796144129; x=1796748929; 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=1TM4I69yvvmWjCJqZLD5ta5VdIAfZbpVKAEW1xg3N4w=; b=T8M8z6nCmk0ZOed8Rt9GgsGzNyZeCYO9L/en0VIU0vgi1RtGdbMJAEtPGHfuKQKWZG SCpquRLij7579P/rCYXx58IZaVK9ESLhWXJom+KWjuSq01Uzv4a7tq0qM1x4tKmOcXxB JrAMIewFfne/C4PUoihkpLpX8y/M7a2ha9DSgsVfO/kQcj3XmmfRN4tQ7IwiUoTObdlS XcrATv2PYhwe4z82B3tZs/wzWYolqrmbjp5wD47Vh9zqXoJs+ET6pZa1MuQOgi80ajZ/ C7dtdrZNTBQ5c3kaK3vFH6lH75KDyajynzzebjs2QF/Us1WqnKRU9trA5laknl+q/ZWn 37VQ== X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20260707; t=1796144129; x=1796748929; 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=1TM4I69yvvmWjCJqZLD5ta5VdIAfZbpVKAEW1xg3N4w=; b=uTnx/s8kMx59hWwZyG6XtGXoDI5EyOk7TilBqetOzIIlbyPG4zPgGuo7gFzPqnuPuc aqyj8I2NyXtDIE59FZLZfzVovgLKmnn+c9By6lKCZMMzaASTo+BZLBQ8+HUBi9wihhCg F0lqJavHG3NcewAekcb5QjzPvSTuF5jfKz5lF4CPBxzdNPH+SnDQg9BpPGmo7bNHN8yN sHeYHN7Z/kZc4fTmABMX8LFODdHDUsF3U714UdnrjFeaF4LOIBVscV24OCtGJpzxGdol nsmLHEpXWfYDueFS3rn97VK8iOC1E6HJcgW694v0cSIwvtgBFofV1MSwNPN0hUFrK8Nq cKYQ== X-Forwarded-Encrypted: i=1; AL+hErHufHHTPAJTwPJU9NRKmfNTu6Dhx2xdmqbn4L9qDuHdBK3P5TP/aNnLnD9bRzdwQqAcXqWDECRs/LeI7Gw=@vger.kernel.org X-Gm-Message-State: APuU4Z/+binlze6KMjW6kx0OMoOmpVx9mCzVUu+wwdQezHWnZe+ReOVX RoMr3wMJFoQGvhjlMHqs7yVy/VvBn6hsyDCddNqIEoI+zwh+bV5devX6 X-Gm-Gg: AZFdTZdE/ekX9uAj3tawEfpMLqu/6COVRz87HbCujOGk6e7Z3rnuggs5PXq6lScdmKB v4aCydnLUus5Ccs9DDz4NgGlRMxJJr+BLUtIjJet93dIVZdKA/fvADVMSrsgporRfx7aNiXgzkS vQpD8hmIYliG7A/dKNWtopvesNEAhPYW2TJtBN6H7XzDxosazqbVQOur92EpgT6GaOXgLiiDzxm ABJuQdXHs7fY9bSuY7lp6ssjPBz6ktBjKdpfMmPxEuRilJrXWSjlpUi8gJtTPN8zM6pcEcXPPJQ VIoZjdHwKaZ6b0WOlAnyy8ug3B21sdfTGWXic2HvaO+0lbpQ1MrSpUYu3VwEXzXDZNkjcvPSNbj saNOoXLeOP9P4vXkEVygwh7K6f8V2Ujwxm/VAj7f//XQGUO52D8CaltsviCD4+/dtlpTKyZ+Efi QgVefq6v7QxPIKD+3hzTUDQJ5dMOvFxE6BCxHHl8wHagD/TtBrUD7hQB8zkjpVaHEs2NU8dcAXV tvIzF0t06FJcMVFPAsvFX/8J+0zRK0PG/iOSzE0nDlC5DSrjk5pWUX2ADQm/8ptdnw4a5nd5ylH UXdIqs32AnCCa+Z9oA83XR5iXKV4Tqcxal+65DGDNT4VdiJ7Luii2iiLwg6xaKqhQka4 X-Received: by 2002:a17:90b:4c07:b0:3b4:f92:ade7 with SMTP id 98e67ed59e1d1-3b41cb20eb8mr39928047a91.52.1796144128512; Tue, 01 Dec 2026 08:55:28 -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.23 (version=TLS1_3 cipher=TLS_CHACHA20_POLY1305_SHA256 bits=256/256); Tue, 01 Dec 2026 08:55:27 -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 2/4] i2c: rust: implement SMBus access via IoBackend Date: Tue, 1 Dec 2026 23:55:06 +0700 Message-ID: <20261201165508.39336-3-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 Implement fallible SMBus byte and word access for bound I2C clients using the generic I/O backend infrastructure. I2C transactions may fail due to NACK, arbitration loss, or timeout, so use FallibleIoCapable rather than the infallible IoCapable interface. Propagate errors returned by the I2C core to callers. Provide smbus_io() for byte-addressed register access and standalone word helpers for layouts not represented by the Region-based view. Also provide smbus_read_word_swapped() for devices that transmit the high byte of a multi-byte value first. Restrict these operations to I2cClient, ensuring that bus I/O is only available while the client remains bound, and implement Sync for I2cClient since its exposed SMBus operations serialize through the I2C core bus lock. Suggested-by: Shuai Liu <847807867@qq.com> Link: https://lore.kernel.org/all/tencent_173B7731E90B9624F9F82613DC3031B70907@qq.com/ Suggested-by: Markus Probst Link: https://lore.kernel.org/all/947615fd284c416891ac6de5d16cdd00ec5267ab.camel@posteo.de/ Signed-off-by: Muchamad Coirul Anwar --- Igor reviewed this patch in v7, but since I added `Sync` on `I2cClient` and updated some docs afterward, I did not carry his `Reviewed-by:` tag forward. Another review would be appreciated. rust/kernel/i2c.rs | 243 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 242 insertions(+), 1 deletion(-) diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs index b4ff25c830fc..25a8fa2f6329 100644 --- a/rust/kernel/i2c.rs +++ b/rust/kernel/i2c.rs @@ -13,8 +13,15 @@ devres::Devres, driver, error::*, + io::{ + FallibleIoCapable, + IoBackend, + IoBase, + Region, // + }, of, prelude::*, + ptr::KnownSize, sync::aref::{ ARef, AlwaysRefCounted, // @@ -520,9 +527,15 @@ fn as_ref(&self) -> &device::Device { unsafe impl Send for I2cClient {} // SAFETY: `I2cClient` can be shared among threads because all methods of `I2cClient` -// (i.e. `I2cClient) are thread safe. +// (i.e. `I2cClient`) are thread safe. unsafe impl Sync for I2cClient {} +// SAFETY: `I2cClient` exposes only thread-safe `&self` operations: +// SMBus transfers serialize via the I2C core bus lock and read only immutable +// client fields (`adapter`, `addr`, `flags`), and dereferencing to +// `I2cClient` or `AsRef>` inherits their `Sync` impls. +unsafe impl Sync for I2cClient {} + /// The registration of an i2c client device. /// /// This type represents the registration of a [`struct i2c_client`]. When an instance of this @@ -573,3 +586,231 @@ unsafe impl Send for Registration {} // SAFETY: `Registration` offers no interior mutability (no mutation through &self // and no mutable access is exposed) unsafe impl Sync for Registration {} + +/// I/O backend for SMBus register access via I2C. +/// +/// This backend implements only [`FallibleIoCapable`] and not +/// [`crate::io::IoCapable`], because I2C/SMBus transactions can fail +/// regardless of address validity. The infallible [`crate::io::Io::read`], +/// [`crate::io::Io::write`], and [`crate::io::Io::update`] methods are +/// therefore unavailable for this backend. +pub struct I2cBackend; + +/// An SMBus view associated with a bound I2C client. +/// +/// The pointer encodes a command offset and is never dereferenced as +/// memory. Its type and, for dynamically sized targets, metadata describe +/// the extent of the view. +/// +/// # Invariants +/// +/// The view is derived from the client's SMBus command region. +/// Projections preserve the bounds of the source view. +/// `client` remains valid and bound for the lifetime of the view. +pub struct I2cView<'a, T: ?Sized> { + client: &'a I2cClient, + ptr: *mut T, +} + +impl Copy for I2cView<'_, T> {} + +impl Clone for I2cView<'_, T> { + #[inline] + fn clone(&self) -> Self { + *self + } +} + +impl IoBackend for I2cBackend { + type View<'a, T: ?Sized + KnownSize> = I2cView<'a, T>; + + #[inline] + fn as_ptr<'a, T: ?Sized + KnownSize>(view: Self::View<'a, T>) -> *mut T { + view.ptr + } + + #[inline] + unsafe fn project_view<'a, T: ?Sized + KnownSize, U: ?Sized + KnownSize>( + view: Self::View<'a, T>, + ptr: *mut U, + ) -> Self::View<'a, U> { + // INVARIANT: Per safety requirement. + I2cView { + client: view.client, + ptr, + } + } +} + +impl FallibleIoCapable for I2cBackend { + #[inline] + fn io_try_read<'a>(view: I2cView<'a, u8>) -> Result { + // By `I2cView`'s invariant, `addr() + 1 <= 256`, so `addr()` is at most + // 255 and the `as u8` cast is lossless. + let reg = Self::as_ptr(view).addr() as u8; + view.client.smbus_read_byte(reg) + } + + #[inline] + fn io_try_write<'a>(view: I2cView<'a, u8>, value: u8) -> Result { + // By `I2cView`'s invariant, `addr() + 1 <= 256`, so `addr()` is at most + // 255 and the `as u8` cast is lossless. + let reg = Self::as_ptr(view).addr() as u8; + view.client.smbus_write_byte(reg, value) + } +} + +/// The `Region<256>` view is byte-addressed. Consequently, its generic +/// 16-bit operations reject odd command bytes and command byte `0xFF`. +/// Devices whose command bytes each select an independent 16-bit register +/// should use [`I2cClient::smbus_read_word`] or +/// [`I2cClient::smbus_read_word_swapped`] directly. +impl FallibleIoCapable for I2cBackend { + #[inline] + fn io_try_read<'a>(view: I2cView<'a, u16>) -> Result { + // By `I2cView`'s invariant, `addr() + 2 <= 256`, so `addr()` is at most + // 254 and the `as u8` cast is lossless. + let reg = Self::as_ptr(view).addr() as u8; + view.client.smbus_read_word(reg) + } + + #[inline] + fn io_try_write<'a>(view: I2cView<'a, u16>, value: u16) -> Result { + // By `I2cView`'s invariant, `addr() + 2 <= 256`, so `addr()` is at most + // 254 and the `as u8` cast is lossless. + let reg = Self::as_ptr(view).addr() as u8; + view.client.smbus_write_word(reg, value) + } +} + +impl<'a, T: ?Sized + KnownSize> IoBase<'a> for I2cView<'a, T> { + type Backend = I2cBackend; + type Target = T; + + #[inline] + fn as_view(self) -> I2cView<'a, T> { + self + } +} + +// SAFETY: The bound client borrow remains valid when the view is moved +// between threads. The view exposes only SMBus transactions, which use +// the I2C core's bus locking, and pointer projections that never +// dereference the encoded address as memory. `T: Sync` preserves the +// shared-view restriction. +unsafe impl Send for I2cView<'_, T> {} + +// SAFETY: Sharing a view permits concurrent SMBus transactions, which +// use the I2C core's bus locking. The bound client remains valid for +// the view's lifetime, and the encoded pointer is never dereferenced +// as memory. `T: Sync` preserves the shared-view restriction. +unsafe impl Sync for I2cView<'_, T> {} + +impl I2cClient { + /// Returns an I/O handle for SMBus register access on this I2C client. + /// + /// The returned handle provides fallible read and write methods for the + /// SMBus command byte range (`0x00..=0xFF`). A command byte is a data byte which + /// often selects a register on the device. The 7-bit device address is handled + /// separately by the I2C core. + /// + /// [`crate::io::Io::try_read16`] and + /// [`crate::io::Io::try_write16`] on the returned handle reject + /// odd offsets because the [`Region`]-based bounds check requires + /// `offset % 2 == 0`. This model does not cover every SMBus register layout, + /// including layouts where auto-increment or auto-decrement results in command + /// bytes that appear unaligned. Use [`Self::smbus_read_word`] or + /// [`Self::smbus_read_word_swapped`] for word access at an odd command byte. + #[inline] + pub fn smbus_io(&self) -> I2cView<'_, Region<256>> { + // INVARIANT: The view borrows this bound client and covers the 256-byte + // SMBus command region. + // + // The provenance-free pointer encodes a command offset rather than a + // memory address. Its initial address is zero, and the region metadata + // supplies the length used for bounds checks. Projections select command + // offsets; SMBus accessors extract those offsets without dereferencing + // the pointer. + I2cView { + client: self, + ptr: Region::<256>::ptr_from_raw_parts_mut(core::ptr::without_provenance_mut(0), 256), + } + } + + #[inline] + fn smbus_read_byte(&self, reg: u8) -> Result { + // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_read_byte_data` accepts any u8 command byte. + let ret = unsafe { bindings::i2c_smbus_read_byte_data(self.as_raw(), reg) }; + to_result(ret)?; + Ok(ret as u8) + } + + #[inline] + fn smbus_write_byte(&self, reg: u8, value: u8) -> Result { + // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_write_byte_data` accepts any u8 command byte and value. + let ret = unsafe { bindings::i2c_smbus_write_byte_data(self.as_raw(), reg, value) }; + to_result(ret) + } + + /// Reads the 16-bit SMBus word value returned for a command. + /// + /// Wraps `i2c_smbus_read_word_data`. The `reg` parameter is the SMBus + /// command byte (`0x00..=0xFF`), a data byte which often selects a register on + /// the device. SMBus transmits the low byte first. + /// + /// Use [`Self::smbus_read_word_swapped`] for devices that transmit the + /// high byte of a multi-byte value first. + /// + /// Returns `Err` if the bus transaction fails, for example because of a + /// NACK, arbitration loss, or timeout. + #[inline] + pub fn smbus_read_word(&self, reg: u8) -> Result { + // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_read_word_data` is safe to call with any valid client + // pointer and any u8 command byte. + let ret = unsafe { bindings::i2c_smbus_read_word_data(self.as_raw(), reg) }; + to_result(ret)?; + Ok(ret as u16) + } + + #[inline] + fn smbus_write_word(&self, reg: u8, value: u16) -> Result { + // SAFETY: `self.as_raw()` returns a valid `*mut struct i2c_client` + // pointer as guaranteed by the type invariant of `I2cClient`. + // `i2c_smbus_write_word_data` accepts any u8 command byte and u16 value. + let ret = unsafe { bindings::i2c_smbus_write_word_data(self.as_raw(), reg, value) }; + to_result(ret) + } + + /// Reads a 16-bit word from an SMBus command and swaps its two bytes. + /// + /// Wraps `i2c_smbus_read_word_data` and applies [`u16::swap_bytes`] to the + /// result. The `reg` parameter is the SMBus command byte (`0x00..=0xFF`), a data + /// byte which often selects a register on the device. + /// + /// SMBus transmits the low byte first. This method swaps the returned bytes + /// for devices that transmit the high byte of a multi-byte value first. + /// + /// Returns `Err` if the bus transaction fails, for example because of a + /// NACK, arbitration loss, or timeout. + /// + /// # Examples + /// + /// ```no_run + /// use kernel::{device::Bound, i2c::I2cClient, prelude::*}; + /// + /// # fn test(client: &I2cClient) -> Result { + /// // Read a word from a device that transmits its high byte first. + /// client.smbus_read_word_swapped(0x0c) + /// # } + /// ``` + #[inline] + pub fn smbus_read_word_swapped(&self, reg: u8) -> Result { + self.smbus_read_word(reg).map(u16::swap_bytes) + } +} -- 2.50.0