Rust for Linux List
 help / color / mirror / Atom feed
From: Mike Lothian <mike@fireburn.co.uk>
To: rust-for-linux@vger.kernel.org
Cc: dri-devel@lists.freedesktop.org,
	"David Airlie" <airlied@gmail.com>,
	"Simona Vetter" <simona@ffwll.ch>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Lyude Paul" <lyude@redhat.com>,
	"Miguel Ojeda" <ojeda@kernel.org>,
	"Boqun Feng" <boqun@kernel.org>, "Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Benno Lossin" <lossin@kernel.org>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Alice Ryhl" <aliceryhl@google.com>,
	"Trevor Gross" <tmgross@umich.edu>,
	linux-kernel@vger.kernel.org,
	"Mike Lothian" <mike@fireburn.co.uk>
Subject: [RFC PATCH v2 13/18] rust: i2c: add adapter-provider (bus controller) registration
Date: Fri,  3 Jul 2026 04:01:00 +0100	[thread overview]
Message-ID: <20260703030123.2814-14-mike@fireburn.co.uk> (raw)
In-Reply-To: <20260703030123.2814-1-mike@fireburn.co.uk>

The I2C abstraction can register an I2C *client* driver (i2c::Driver), but not
provide a bus. A driver that presents a virtual I2C bus and services the
transfers itself -- e.g. DisplayLink's evdi, which exposes a DDC/CI channel so
userspace monitor-control tools can reach the display -- needs the controller
side.

Add i2c::BusController (a trait with master_xfer/functionality over a
driver-supplied Context) and i2c::BusAdapter, which fills a struct i2c_adapter
whose i2c_algorithm dispatches to the trait via trampolines, calls
i2c_add_adapter() on creation and i2c_del_adapter() on drop. i2c::Msg is a
#[repr(transparent)] view over struct i2c_msg exposing addr/flags/is_read and
the payload as a (mutable) byte slice, so a transfer routine needs no unsafe.
FUNC_I2C is exported for the common functionality() return.

Signed-off-by: Mike Lothian <mike@fireburn.co.uk>
Assisted-by: Claude:claude-opus-4-8 [Claude-Code]
---
 rust/kernel/i2c.rs | 192 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 192 insertions(+)

diff --git a/rust/kernel/i2c.rs b/rust/kernel/i2c.rs
index 624b971ca8b0..5cde59a3ce46 100644
--- a/rust/kernel/i2c.rs
+++ b/rust/kernel/i2c.rs
@@ -601,3 +601,195 @@ 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 {}
+
+// ===========================================================================
+// I2C adapter (bus controller / provider) side
+// ===========================================================================
+
+/// A single I2C message presented to a [`BusController`]'s transfer routine.
+///
+/// Wraps a `struct i2c_msg`; `#[repr(transparent)]` so a C `i2c_msg` array can be viewed directly
+/// as a `[Msg]`.
+#[repr(transparent)]
+pub struct Msg(Opaque<bindings::i2c_msg>);
+
+impl Msg {
+    /// The 7-bit (or 10-bit) target address.
+    #[inline]
+    pub fn addr(&self) -> u16 {
+        // SAFETY: `self.0` is a valid `i2c_msg` for the callback's duration.
+        unsafe { (*self.0.get()).addr }
+    }
+
+    /// The message flags (`I2C_M_*`).
+    #[inline]
+    pub fn flags(&self) -> u16 {
+        // SAFETY: as above.
+        unsafe { (*self.0.get()).flags }
+    }
+
+    /// Whether this is a read (`I2C_M_RD`) rather than a write.
+    #[inline]
+    pub fn is_read(&self) -> bool {
+        self.flags() & (bindings::I2C_M_RD as u16) != 0
+    }
+
+    /// The message length in bytes.
+    #[inline]
+    pub fn len(&self) -> usize {
+        // SAFETY: as above.
+        unsafe { (*self.0.get()).len as usize }
+    }
+
+    /// Whether the message is empty.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.len() == 0
+    }
+
+    /// The message payload of a write, as a read-only slice.
+    #[inline]
+    pub fn buf(&self) -> &[u8] {
+        // SAFETY: `buf` points to `len` bytes valid for the callback's duration.
+        unsafe { core::slice::from_raw_parts((*self.0.get()).buf, self.len()) }
+    }
+
+    /// The message buffer of a read, as a mutable slice to fill with the reply.
+    #[inline]
+    pub fn buf_mut(&mut self) -> &mut [u8] {
+        // SAFETY: `buf` points to `len` writable bytes valid for the callback's duration.
+        unsafe { core::slice::from_raw_parts_mut((*self.0.get()).buf, self.len()) }
+    }
+}
+
+/// `I2C_FUNC_I2C`: the adapter supports plain I2C (not just SMBus) transfers.
+pub const FUNC_I2C: u32 = bindings::I2C_FUNC_I2C;
+
+/// A Rust-implemented I2C bus adapter (the controller/provider side).
+///
+/// This is the counterpart to the [`Driver`] trait above: rather than binding to an I2C client on
+/// an existing bus, an implementer *is* a bus and services transfers. Virtual buses -- e.g. the
+/// DDC/CI channel DisplayLink's evdi exposes so userspace monitor-control tools can reach the
+/// display -- use this.
+pub trait BusController: 'static {
+    /// Per-adapter driver context, made available to the transfer callbacks.
+    type Context: Send + Sync;
+
+    /// Transfer `msgs` on the bus, returning the number of messages successfully transferred
+    /// (as the C `master_xfer` does), or an error.
+    fn master_xfer(ctx: &Self::Context, msgs: &mut [Msg]) -> Result<usize>;
+
+    /// Report the bus functionality bitmask (`I2C_FUNC_*`).
+    fn functionality(ctx: &Self::Context) -> u32;
+}
+
+/// An owned, registered I2C adapter driven by a [`BusController`].
+///
+/// [`BusAdapter::new`] fills a `struct i2c_adapter` (pointing its algorithm at trampolines that
+/// dispatch to `T`) and calls `i2c_add_adapter()`; dropping it calls `i2c_del_adapter()`.
+#[pin_data(PinnedDrop)]
+pub struct BusAdapter<T: BusController> {
+    #[pin]
+    adapter: Opaque<bindings::i2c_adapter>,
+    #[pin]
+    algo: Opaque<bindings::i2c_algorithm>,
+    ctx: T::Context,
+    registered: core::sync::atomic::AtomicBool,
+}
+
+// SAFETY: the adapter is internally synchronized by the I2C core; `ctx` is `Send + Sync`.
+unsafe impl<T: BusController> Send for BusAdapter<T> {}
+// SAFETY: see `Send`.
+unsafe impl<T: BusController> Sync for BusAdapter<T> {}
+
+impl<T: BusController> BusAdapter<T> {
+    /// # Safety
+    /// `adap` is a valid adapter whose `algo_data` points to a live `T::Context`.
+    unsafe extern "C" fn xfer_trampoline(
+        adap: *mut bindings::i2c_adapter,
+        msgs: *mut bindings::i2c_msg,
+        num: crate::ffi::c_int,
+    ) -> crate::ffi::c_int {
+        // SAFETY: by the invariant established in `new`, `algo_data` points to the `T::Context`.
+        let ctx = unsafe { &*((*adap).algo_data as *const T::Context) };
+        // SAFETY: the I2C core passes `num` valid `i2c_msg`s; `Msg` is `#[repr(transparent)]`.
+        let slice = unsafe { core::slice::from_raw_parts_mut(msgs.cast::<Msg>(), num as usize) };
+        match T::master_xfer(ctx, slice) {
+            Ok(n) => n as crate::ffi::c_int,
+            Err(e) => e.to_errno(),
+        }
+    }
+
+    /// # Safety
+    /// `adap` is a valid adapter whose `algo_data` points to a live `T::Context`.
+    unsafe extern "C" fn func_trampoline(adap: *mut bindings::i2c_adapter) -> u32 {
+        // SAFETY: by the invariant established in `new`, `algo_data` points to the `T::Context`.
+        let ctx = unsafe { &*((*adap).algo_data as *const T::Context) };
+        T::functionality(ctx)
+    }
+
+    /// Create and register a new I2C adapter named `name`, parented to `parent`, with driver
+    /// context `ctx`.
+    pub fn new(
+        name: &CStr,
+        parent: &device::Device,
+        ctx: T::Context,
+    ) -> Result<Pin<KBox<Self>>> {
+        let this = KBox::try_pin_init(
+            try_pin_init!(Self {
+                adapter <- Opaque::ffi_init(|slot: *mut bindings::i2c_adapter| {
+                    // SAFETY: `slot` is valid, uninitialized storage; a zeroed adapter is a valid
+                    // starting point (self-referential fields are set below, after pinning).
+                    unsafe { *slot = bindings::i2c_adapter::default() };
+                }),
+                algo <- Opaque::ffi_init(|slot: *mut bindings::i2c_algorithm| {
+                    // SAFETY: `slot` is valid, uninitialized storage.
+                    unsafe {
+                        *slot = bindings::i2c_algorithm::default();
+                        (*slot).__bindgen_anon_1.master_xfer = Some(Self::xfer_trampoline);
+                        (*slot).functionality = Some(Self::func_trampoline);
+                    }
+                }),
+                ctx: ctx,
+                registered: core::sync::atomic::AtomicBool::new(false),
+            }),
+            GFP_KERNEL,
+        )?;
+
+        // `this` now has a stable address; wire the self-referential adapter fields and register.
+        let adap = this.adapter.get();
+        // Copy the name without its NUL into the fixed 48-byte array (capped at 47 so the
+        // already-zeroed array stays NUL-terminated even if the name is over-long).
+        let name_bytes = name.to_bytes();
+        let n = core::cmp::min(name_bytes.len(), 47);
+        // SAFETY: `adap`/`algo`/`ctx` live for `this`'s (pinned) lifetime; `name_bytes` is valid
+        // for `n <= 47` bytes; `parent` is a valid device.
+        unsafe {
+            (*adap).algo = this.algo.get();
+            (*adap).algo_data = (&this.ctx as *const T::Context).cast_mut().cast();
+            core::ptr::copy_nonoverlapping(
+                name_bytes.as_ptr(),
+                (*adap).name.as_mut_ptr().cast::<u8>(),
+                n,
+            );
+            (*adap).dev.parent = parent.as_raw();
+        }
+
+        // SAFETY: `adap` is a fully-initialized adapter.
+        to_result(unsafe { bindings::i2c_add_adapter(adap) })?;
+        this.registered
+            .store(true, core::sync::atomic::Ordering::Release);
+        Ok(this)
+    }
+}
+
+#[pinned_drop]
+impl<T: BusController> PinnedDrop for BusAdapter<T> {
+    fn drop(self: Pin<&mut Self>) {
+        if self.registered.load(core::sync::atomic::Ordering::Acquire) {
+            // SAFETY: the adapter was successfully registered with `i2c_add_adapter` and has not
+            // been deleted yet.
+            unsafe { bindings::i2c_del_adapter(self.adapter.get()) };
+        }
+    }
+}
-- 
2.55.0


  parent reply	other threads:[~2026-07-03  3:02 UTC|newest]

Thread overview: 29+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-06-17 15:02 [RFC PATCH 0/5] rust: drm: minimal KMS bindings, EDID read, rotation, HDCP defs Mike Lothian
2026-06-17 15:02 ` [RFC PATCH 1/4] rust: drm: add minimal KMS bindings for simple-display-pipe drivers Mike Lothian
2026-06-17 15:02 ` [RFC PATCH 2/4] rust: drm: expose drm_edid.h for reading connector EDID Mike Lothian
2026-06-17 15:02 ` [RFC PATCH 3/4] rust: drm: expose drm::Device::as_raw() Mike Lothian
2026-06-17 15:02 ` [RFC PATCH 4/4] rust: drm: expose drm_blend.h and the atomic new-CRTC-state accessor Mike Lothian
2026-06-17 15:11 ` [RFC PATCH 0/5] rust: drm: minimal KMS bindings, EDID read, rotation, HDCP defs Miguel Ojeda
2026-06-17 15:29   ` Mike Lothian
2026-07-03  3:00 ` [RFC PATCH v2 00/18] rust: drm: safe KMS mode-object layer + evdi bindings Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 01/18] rust: drm: kms: forward-port the safe mode-object layer onto the typestate device Mike Lothian
2026-07-07 21:46     ` lyude
2026-07-07 22:21     ` lyude
2026-07-03  3:00   ` [RFC PATCH v2 02/18] rust: drm: kms: adapt the port to current drm-next Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 03/18] rust: drm: kms: break the Driver* trait well-formedness cycle Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 04/18] rust: drm: kms: build the kernel crate clean under -Znext-solver Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 05/18] rust: drm: expose <drm/display/drm_hdcp.h> HDCP 2.2 message definitions Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 06/18] rust: drm: kms: add a Framebuffer::vmap() guard Mike Lothian
2026-07-07 21:51     ` lyude
2026-07-03  3:00   ` [RFC PATCH v2 07/18] rust: drm: kms: add safe accessors for common state and connector modes Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 08/18] rust: drm: tyr: add the Kms associated type Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 09/18] rust: drm: add drm_event delivery Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 10/18] rust: drm: allow drivers to declare ioctls from their own uAPI module Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 11/18] rust: platform: add runtime platform device creation Mike Lothian
2026-07-03  3:00   ` [RFC PATCH v2 12/18] rust: drm: framebuffer: add geometry accessors, refcounting and a byte-slice vmap Mike Lothian
2026-07-03  3:01   ` Mike Lothian [this message]
2026-07-03  3:01   ` [RFC PATCH v2 14/18] rust: add sysfs device attribute groups Mike Lothian
2026-07-03  3:01   ` [RFC PATCH v2 15/18] rust: drm: support hardware cursor planes with sleepable event delivery Mike Lothian
2026-07-03  3:01   ` [RFC PATCH v2 16/18] rust: drm: add CRTC gamma LUT and plane rotation property bindings Mike Lothian
2026-07-03  3:01   ` [RFC PATCH v2 17/18] rust: drm: kms: add connector detect() and mode_valid() hooks Mike Lothian
2026-07-03  3:01   ` [RFC PATCH v2 18/18] rust: drm: kms: add plane damage-clip accessors Mike Lothian

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=20260703030123.2814-14-mike@fireburn.co.uk \
    --to=mike@fireburn.co.uk \
    --cc=a.hindborg@kernel.org \
    --cc=airlied@gmail.com \
    --cc=aliceryhl@google.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=dakr@kernel.org \
    --cc=dri-devel@lists.freedesktop.org \
    --cc=gary@garyguo.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=lossin@kernel.org \
    --cc=lyude@redhat.com \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=simona@ffwll.ch \
    --cc=tmgross@umich.edu \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox