public inbox for linuxppc-dev@ozlabs.org
 help / color / mirror / Atom feed
From: Link Mauve <linkmauve@linkmauve.fr>
To: rust-for-linux@vger.kernel.org
Cc: "Link Mauve" <linkmauve@linkmauve.fr>,
	"Madhavan Srinivasan" <maddy@linux.ibm.com>,
	"Michael Ellerman" <mpe@ellerman.id.au>,
	"Nicholas Piggin" <npiggin@gmail.com>,
	"Christophe Leroy (CS GROUP)" <chleroy@kernel.org>,
	"Srinivas Kandagatla" <srini@kernel.org>,
	"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>,
	"Danilo Krummrich" <dakr@kernel.org>,
	"Daniel Almeida" <daniel.almeida@collabora.com>,
	"Ard Biesheuvel" <ardb@kernel.org>,
	"Martin K. Petersen" <martin.petersen@oracle.com>,
	"Eric Biggers" <ebiggers@google.com>,
	"Greg Kroah-Hartman" <gregkh@linuxfoundation.org>,
	"Lyude Paul" <lyude@redhat.com>,
	"Asahi Lina" <lina+kernel@asahilina.net>,
	"Viresh Kumar" <viresh.kumar@linaro.org>,
	"Lorenzo Stoakes" <lorenzo.stoakes@oracle.com>,
	"Tamir Duberstein" <tamird@kernel.org>,
	"FUJITA Tomonori" <fujita.tomonori@gmail.com>,
	linuxppc-dev@lists.ozlabs.org, linux-kernel@vger.kernel.org,
	officialTechflashYT@gmail.com, "Ash Logan" <ash@heyquark.com>,
	"Roberto Van Eeden" <rw-r-r-0644@protonmail.com>,
	"Jonathan Neuschäfer" <j.neuschaefer@gmx.net>
Subject: [PATCH v2 2/4] rust: nvmem: Add an abstraction for nvmem providers
Date: Wed,  4 Feb 2026 05:04:59 +0100	[thread overview]
Message-ID: <20260204040505.8447-3-linkmauve@linkmauve.fr> (raw)
In-Reply-To: <20260204040505.8447-1-linkmauve@linkmauve.fr>

This is my very first Rust abstraction in the kernel, I took inspiration
from various other abstractions that had already been written.

I only implemented enough to rewrite a very simple driver I wrote in the
past, in order to test the API and make sure it’s at least as ergonomic
as the C version, without any unsafe at all.

Signed-off-by: Link Mauve <linkmauve@linkmauve.fr>
---
 rust/bindings/bindings_helper.h |   1 +
 rust/kernel/lib.rs              |   2 +
 rust/kernel/nvmem.rs            | 163 ++++++++++++++++++++++++++++++++
 3 files changed, 166 insertions(+)
 create mode 100644 rust/kernel/nvmem.rs

diff --git a/rust/bindings/bindings_helper.h b/rust/bindings/bindings_helper.h
index a067038b4b42..522a76b2e294 100644
--- a/rust/bindings/bindings_helper.h
+++ b/rust/bindings/bindings_helper.h
@@ -65,6 +65,7 @@
 #include <linux/mdio.h>
 #include <linux/mm.h>
 #include <linux/miscdevice.h>
+#include <linux/nvmem-provider.h>
 #include <linux/of_device.h>
 #include <linux/pci.h>
 #include <linux/phy.h>
diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 696f62f85eb5..97f3fc1e8e12 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -118,6 +118,8 @@
 #[cfg(CONFIG_NET)]
 pub mod net;
 pub mod num;
+#[cfg(CONFIG_NVMEM)]
+pub mod nvmem;
 pub mod of;
 #[cfg(CONFIG_PM_OPP)]
 pub mod opp;
diff --git a/rust/kernel/nvmem.rs b/rust/kernel/nvmem.rs
new file mode 100644
index 000000000000..4b81fd65c9a7
--- /dev/null
+++ b/rust/kernel/nvmem.rs
@@ -0,0 +1,163 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! nvmem framework provider.
+//!
+//! Copyright (C) 2026 Link Mauve <linkmauve@linkmauve.fr>
+
+use crate::build_error;
+use crate::device::Device;
+use crate::error::{from_result, VTABLE_DEFAULT_ERROR};
+use crate::prelude::*;
+use core::marker::PhantomData;
+use macros::vtable;
+
+/// The possible types for a nvmem provider.
+#[derive(Default)]
+#[repr(u32)]
+pub enum Type {
+    /// The type of memory is unknown.
+    #[default]
+    Unknown = bindings::nvmem_type_NVMEM_TYPE_UNKNOWN,
+
+    /// Electrically erasable programmable ROM.
+    Eeprom = bindings::nvmem_type_NVMEM_TYPE_EEPROM,
+
+    /// One-time programmable memory.
+    Otp = bindings::nvmem_type_NVMEM_TYPE_OTP,
+
+    /// This memory is backed by a battery.
+    BatteryBacked = bindings::nvmem_type_NVMEM_TYPE_BATTERY_BACKED,
+
+    /// Ferroelectric RAM.
+    Fram = bindings::nvmem_type_NVMEM_TYPE_FRAM,
+}
+
+/// nvmem configuration.
+///
+/// Rust abstraction for the C `struct nvmem_config`.
+#[derive(Default)]
+#[repr(transparent)]
+pub struct NvmemConfig<T: NvmemProvider + Default> {
+    inner: bindings::nvmem_config,
+    _p: PhantomData<T>,
+}
+
+impl<T: NvmemProvider + Default> NvmemConfig<T> {
+    /// NvmemConfig's read callback.
+    ///
+    /// SAFETY: Called from C. Inputs must be valid pointers.
+    extern "C" fn reg_read(
+        context: *mut c_void,
+        offset: u32,
+        val: *mut c_void,
+        bytes: usize,
+    ) -> i32 {
+        from_result(|| {
+            let context = context.cast::<T::Priv>();
+            // SAFETY: context is a valid T::Priv as set in Device::nvmem_register().
+            let context = unsafe { &*context };
+            let val = val.cast::<u8>();
+            // SAFETY: val should be non-null, and allocated for bytes bytes.
+            let data = unsafe { core::slice::from_raw_parts_mut(val, bytes) };
+            T::read(context, offset, data).map(|()| 0)
+        })
+    }
+
+    /// NvmemConfig's write callback.
+    ///
+    /// SAFETY: Called from C. Inputs must be valid pointers.
+    extern "C" fn reg_write(
+        context: *mut c_void,
+        offset: u32,
+        // TODO: Change val from void* to const void* in the C API!
+        val: *mut c_void,
+        bytes: usize,
+    ) -> i32 {
+        from_result(|| {
+            let context = context.cast::<T::Priv>();
+            // SAFETY: context is a valid T::Priv as set in Device::nvmem_register().
+            let context = unsafe { &*context };
+            let val = val.cast::<u8>().cast_const();
+            // SAFETY: val should be non-null, and allocated for bytes bytes.
+            let data = unsafe { core::slice::from_raw_parts(val, bytes) };
+            T::write(context, offset, data).map(|()| 0)
+        })
+    }
+
+    /// Optional name.
+    pub fn with_name(mut self, name: &CStr) -> Self {
+        self.inner.name = name.as_char_ptr();
+        self
+    }
+
+    /// Type of the nvmem storage
+    pub fn with_type(mut self, type_: Type) -> Self {
+        self.inner.type_ = type_ as u32;
+        self
+    }
+
+    /// Device is read-only.
+    pub fn with_read_only(mut self, read_only: bool) -> Self {
+        self.inner.read_only = read_only;
+        self
+    }
+
+    /// Device is accessibly to root only.
+    pub fn with_root_only(mut self, root_only: bool) -> Self {
+        self.inner.root_only = root_only;
+        self
+    }
+
+    /// Device size.
+    pub fn with_size(mut self, size: i32) -> Self {
+        self.inner.size = size;
+        self
+    }
+
+    /// Minimum read/write access granularity.
+    pub fn with_word_size(mut self, word_size: i32) -> Self {
+        self.inner.word_size = word_size;
+        self
+    }
+
+    /// Minimum read/write access stride.
+    pub fn with_stride(mut self, stride: i32) -> Self {
+        self.inner.stride = stride;
+        self
+    }
+}
+
+impl Device {
+    /// Register a managed nvmem provider on the given device.
+    pub fn nvmem_register<T>(&self, mut config: NvmemConfig<T>, priv_: &T::Priv)
+    where
+        T: NvmemProvider + Default,
+    {
+        // FIXME: The last cast to mut indicates some unsoundness here.
+        config.inner.priv_ = core::ptr::from_ref(priv_).cast::<c_void>().cast_mut();
+        config.inner.dev = self.as_raw();
+        config.inner.reg_read = Some(NvmemConfig::<T>::reg_read);
+        config.inner.reg_write = Some(NvmemConfig::<T>::reg_write);
+        // SAFETY: Both self and config can’t be null here, and should have the correct type.
+        unsafe { bindings::devm_nvmem_register(self.as_raw(), &config.inner) };
+    }
+}
+
+/// Helper trait to define the callbacks of a nvmem provider.
+#[vtable]
+pub trait NvmemProvider {
+    /// The type passed into the context for read and write functions.
+    type Priv;
+
+    /// Callback to read data.
+    #[inline]
+    fn read(_context: &Self::Priv, _offset: u32, _data: &mut [u8]) -> Result {
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+
+    /// Callback to write data.
+    #[inline]
+    fn write(_context: &Self::Priv, _offset: u32, _data: &[u8]) -> Result {
+        build_error!(VTABLE_DEFAULT_ERROR)
+    }
+}
-- 
2.52.0



  parent reply	other threads:[~2026-02-04  4:05 UTC|newest]

Thread overview: 23+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-02-04  4:04 [PATCH v2 0/4] Add Rust abstractions for nvmem-provider Link Mauve
2026-02-04  4:04 ` [PATCH v2 1/4] rust: io: Add big-endian read and write functions Link Mauve
2026-02-04 15:18   ` Danilo Krummrich
2026-02-04 15:20     ` Danilo Krummrich
2026-02-05 14:28     ` Daniel Almeida
2026-02-05 14:56       ` Danilo Krummrich
2026-02-05 15:16       ` Gary Guo
2026-02-05 17:28         ` Daniel Almeida
2026-02-05 19:05           ` Danilo Krummrich
2026-02-05 21:20             ` Link Mauve
2026-02-05 22:11               ` Danilo Krummrich
2026-02-05 22:31             ` Gary Guo
2026-02-05 22:43               ` Danilo Krummrich
2026-02-08 17:17                 ` Daniel Almeida
2026-02-08 17:52                   ` Danilo Krummrich
2026-02-05 22:46               ` Danilo Krummrich
2026-02-04  4:04 ` Link Mauve [this message]
2026-02-04 15:22   ` [PATCH v2 2/4] rust: nvmem: Add an abstraction for nvmem providers Danilo Krummrich
2026-02-05 12:48     ` Link Mauve
2026-02-05 12:57       ` Danilo Krummrich
2026-02-04  4:05 ` [PATCH v2 3/4] nvmem: Replace the Wii and Wii U OTP driver with a Rust one Link Mauve
2026-03-04 18:46   ` Link Mauve
2026-02-04  4:05 ` [PATCH v2 4/4] powerpc: wii_defconfig: Enable Rust Link Mauve

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=20260204040505.8447-3-linkmauve@linkmauve.fr \
    --to=linkmauve@linkmauve.fr \
    --cc=a.hindborg@kernel.org \
    --cc=aliceryhl@google.com \
    --cc=ardb@kernel.org \
    --cc=ash@heyquark.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun@kernel.org \
    --cc=chleroy@kernel.org \
    --cc=dakr@kernel.org \
    --cc=daniel.almeida@collabora.com \
    --cc=ebiggers@google.com \
    --cc=fujita.tomonori@gmail.com \
    --cc=gary@garyguo.net \
    --cc=gregkh@linuxfoundation.org \
    --cc=j.neuschaefer@gmx.net \
    --cc=lina+kernel@asahilina.net \
    --cc=linux-kernel@vger.kernel.org \
    --cc=linuxppc-dev@lists.ozlabs.org \
    --cc=lorenzo.stoakes@oracle.com \
    --cc=lossin@kernel.org \
    --cc=lyude@redhat.com \
    --cc=maddy@linux.ibm.com \
    --cc=martin.petersen@oracle.com \
    --cc=mpe@ellerman.id.au \
    --cc=npiggin@gmail.com \
    --cc=officialTechflashYT@gmail.com \
    --cc=ojeda@kernel.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=rw-r-r-0644@protonmail.com \
    --cc=srini@kernel.org \
    --cc=tamird@kernel.org \
    --cc=tmgross@umich.edu \
    --cc=viresh.kumar@linaro.org \
    /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