Skip to contentSkip to conversation

rust: replace kernel::str::CStr w/ core::ffi::CStr

PATCH Superseded Tamir Duberstein 5 participants 26 messages Oct 15, 2025 – Oct 20, 2025

Subsystems (17)
DRM drivers VFS Block layer PCI +13 more subsystems

v17 of 18 Superseded Latest is v18 →

lore
Share & tools
lore
#0 lore raw

v17 cover rust: replace kernel::str::CStr w/ core::ffi::CStr

This picks up from Michal Rostecki's work[0]. Per Michal's guidance I have omitted Co-authored tags, as the end result is quite different.

This series is intended to be taken through rust-next. The final patch in the series requires some other subsystems' Acked-bys:
- drivers/android/binder/stats.rs: rust_binder. Alice, could you take a look?
- rust/kernel/device.rs: driver-core. Already acked by gregkh.
- rust/kernel/firmware.rs: driver-core. Danilo, could you take a look?
- rust/kernel/seq_file.rs: vfs. Christian, could you take a look?
- rust/kernel/sync/*: locking-core. Boqun, could you take a look?

---
Changes in v17:
- Rebase on rust-next and fix backsliding relative to series 2a and 2b.
- Link to v16: https://lore.kernel.org/r/[email protected]

Changes in v16:
- Rebase on rust-next.
- Link to v15: https://lore.kernel.org/r/[email protected]

Changes in v15:
- Seal CStrExt. (Benno Lossin)
- Add patch to remove trailing commas from samples/rust/rust_driver_platform.rs.
- Link to v14: https://lore.kernel.org/r/[email protected]

Changes in v14:
- Break the change into multiple series.
- Move CStr reexport to kernel::ffi. (Alice Ryhl)
- pub use core::fmt::{....} in kernel/fmt.rs. (Benno Lossin)
- Avoid unnecessary binding to first_lit in fmt!. (Benno Lossin)
- Add comment to identifier-extracting loop. (Benno Lossin)
- Change quote_spanned! formatting. (Benno Lossin)
- Link to v13: https://lore.kernel.org/r/[email protected]

Changes in v13:
- Rebase on v6.16-rc4.
- Link to v12: https://lore.kernel.org/r/[email protected]

Changes in v12:
- Introduce kernel::fmt::Display to allow implementations on foreign types.
- Tidy up doc comment on str_to_cstr. (Alice Ryhl).
- Link to v11: https://lore.kernel.org/r/[email protected]

Changes in v11:
- Use quote_spanned! to avoid use<'a, T> and generally reduce manual token construction.
- Add a commit to simplify quote_spanned!.
- Drop first commit in favor of
https://lore.kernel.org/rust-for-linux/[email protected]/.
(Miguel Ojeda)
- Correctly handle expressions such as pr_info!("{a}", a = a = a). (Benno Lossin)
- Avoid dealing with }} escapes, which is not needed. (Benno Lossin)
- Revert some unnecessary changes. (Benno Lossin)
- Rename c_str_avoid_literals! to str_to_cstr!. (Benno Lossin &
Alice Ryhl).
- Link to v10: https://lore.kernel.org/r/[email protected]

Changes in v10:
- Rebase on cbeaa41dfe26b72639141e87183cb23e00d4b0dd.
- Implement Alice's suggestion to use a proc macro to work around orphan rules otherwise preventing core::ffi::CStr to be directly printed with {}.
- Link to v9: https://lore.kernel.org/r/[email protected]

Changes in v9:
- Rebase on rust-next.
- Restore impl Display for BStr which exists upstream[1].
- Link: https://doc.rust-lang.org/nightly/std/bstr/struct.ByteStr.html#impl-Display-for-ByteStr [1]
- Link to v8: https://lore.kernel.org/r/[email protected]

Changes in v8:
- Move {from,as}_char_ptr back to CStrExt. This reduces the diff some.
- Restore from_bytes_with_nul_unchecked_mut, to_cstring.
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- Rebased on mainline.
- Restore functionality added in commit a321f3ad0a5d ("rust: str: add {make,to}_{upper,lower}case() to CString").
- Used diff.algorithm patience to improve diff readability.
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Split the work into several commits for ease of review.
- Restore {from,as}_char_ptr to allow building on ARM (see commit message).
- Add CStrExt to kernel::prelude. (Alice Ryhl)
- Remove CStrExt::from_bytes_with_nul_unchecked_mut and restore DerefMut for CString. (Alice Ryhl)
- Rename and hide kernel::c_str! to encourage use of C-String literals.
- Drop implementation and invocation changes in kunit.rs. (Trevor Gross)
- Drop docs on Display impl. (Trevor Gross)
- Rewrite docs in the style of the standard library.
- Restore the test_cstr_debug unit tests to demonstrate that the implementation has changed.

Changes in v5:
- Keep the test_cstr_display* unit tests.

Changes in v4:
- Provide the CStrExt trait with display() method, which returns a CStrDisplay wrapper with Display implementation. This addresses the lack of Display implementation for core::ffi::CStr.
- Provide from_bytes_with_nul_unchecked_mut() method in CStrExt, which might be useful and is going to prevent manual, unsafe casts.
- Fix a typo (s/preffered/prefered/).

Changes in v3:
- Fix the commit message.
- Remove redundant braces in use, when only one item is imported.

Changes in v2:
- Do not remove c_str macro. While it's preferred to use C-string literals, there are two cases where c_str is helpful:
- When working with macros, which already return a Rust string literal

     (e.g. `stringify!`).

- When building macros, where we want to take a Rust string literal as an argument (for caller's convenience), but still use it as a C-string internally.
- Use Rust literals as arguments in macros (new_mutex, new_condvar, new_mutex). Use the c_str macro to convert these literals to C-string literals.
- Use c_str in kunit.rs for converting the output of stringify! to a CStr.
- Remove DerefMut implementation for CString.

---
Tamir Duberstein (11):
samples: rust: platform: remove trailing commas
rust_binder: remove trailing comma
rust_binder: use kernel::fmt
rust_binder: use core::ffi::CStr method names
rnull: use kernel::fmt
rust: alloc: use kernel::fmt
rust: debugfs: use kernel::fmt
rust: pci: use kernel::fmt
rust: remove spurious use core::fmt::Debug
rust: support formatting of foreign types
rust: replace CStr with core::ffi::CStr

 drivers/android/binder/error.rs          |   5 +-
 drivers/android/binder/process.rs        |   2 +-
 drivers/android/binder/stats.rs          |   6 +-
 drivers/block/rnull/configfs.rs          |   9 +-
 rust/ffi.rs                              |   2 +
 rust/kernel/alloc/kvec/errors.rs         |  14 +-
 rust/kernel/debugfs.rs                   |   2 +-
 rust/kernel/debugfs/callback_adapters.rs |   7 +-
 rust/kernel/debugfs/file_ops.rs          |   6 +-
 rust/kernel/debugfs/traits.rs            |  10 +-
 rust/kernel/device.rs                    |   1 +
 rust/kernel/error.rs                     |   2 +
 rust/kernel/firmware.rs                  |   9 +-
 rust/kernel/fmt.rs                       |  87 ++++++-
 rust/kernel/pci/id.rs                    |   3 +-
 rust/kernel/prelude.rs                   |   7 +-
 rust/kernel/ptr.rs                       |   1 -
 rust/kernel/seq_file.rs                  |   2 +-
 rust/kernel/str.rs                       | 395 +++++++------------------------
 rust/kernel/sync/condvar.rs              |   2 +-
 rust/kernel/sync/lock.rs                 |   2 +-
 rust/kernel/sync/lock/global.rs          |   2 +-
 rust/macros/fmt.rs                       |  94 ++++++++
 rust/macros/lib.rs                       |  19 ++
 rust/macros/quote.rs                     |   7 +
 samples/rust/rust_driver_platform.rs     |   4 +-
 26 files changed, 350 insertions(+), 350 deletions(-)

---
base-commit: 9b332cece987ee1790b2ed4c989e28162fa47860
change-id: 20250201-cstr-core-d4b9b69120cf

Best regards,

Signature · 1 line
Tamir Duberstein <[email protected]>
#1 lore raw

PATCH v17 1/11 samples: rust: platform: remove trailing commas

This prepares for a later commit in which we introduce a custom formatting macro; that macro doesn't handle trailing commas so just remove them.

---
 samples/rust/rust_driver_platform.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
samples/rust/rust_driver_platform.rs +2 -2
index 6473baf4f120..8a82e251820f 100644
@@ -146,7 +146,7 @@ fn properties_parse(dev: &device::Device) -> Result {
 
         let name = c_str!("test,u32-optional-prop");
         let prop = fwnode.property_read::<u32>(name).or(0x12);
-        dev_info!(dev, "'{name}'='{prop:#x}' (default = 0x12)\n",);
+        dev_info!(dev, "'{name}'='{prop:#x}' (default = 0x12)\n");
 
         // A missing required property will print an error. Discard the error to
         // prevent properties_parse from failing in that case.
@@ -161,7 +161,7 @@ fn properties_parse(dev: &device::Device) -> Result {
         let prop: [i16; 4] = fwnode.property_read(name).required_by(dev)?;
         dev_info!(dev, "'{name}'='{prop:?}'\n");
         let len = fwnode.property_count_elem::<u16>(name)?;
-        dev_info!(dev, "'{name}' length is {len}\n",);
+        dev_info!(dev, "'{name}' length is {len}\n");
 
         let name = c_str!("test,i16-array");
         let prop: KVec<i16> = fwnode.property_read_array_vec(name, 4)?.required_by(dev)?;
Signature · 1 line
2.51.0
#2 lore raw

PATCH v17 2/11 rust_binder: remove trailing comma

In reply to Tamir Duberstein

This prepares for a later commit in which we introduce a custom formatting macro; that macro doesn't handle trailing commas so just remove this one.

---
 drivers/android/binder/process.rs | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/android/binder/process.rs +1 -1
index f13a747e784c..d8111c990f21 100644
@@ -596,7 +596,7 @@ pub(crate) fn debug_print(&self, m: &SeqFile, ctx: &Context, print_all: bool) ->
                     "  ref {}: desc {} {}node {debug_id} s {strong} w {weak}",
                     r.debug_id,
                     r.handle,
-                    if dead { "dead " } else { "" },
+                    if dead { "dead " } else { "" }
                 );
             }
         }
Signature · 1 line
2.51.0
#4 lore raw

PATCH v17 3/11 rust_binder: use `kernel::fmt`

In reply to Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit eafedbc7c050 ("rust_binder: add Rust Binder driver").

---
 drivers/android/binder/error.rs | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/android/binder/error.rs +3 -2
index 9921827267d0..b24497cfa292 100644
@@ -2,6 +2,7 @@
 
 // Copyright (C) 2025 Google LLC.
 
+use kernel::fmt;
 use kernel::prelude::*;
 
 use crate::defs::*;
@@ -76,8 +77,8 @@ fn from(_: kernel::alloc::AllocError) -> Self {
     }
 }
 
-impl core::fmt::Debug for BinderError {
-    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+impl fmt::Debug for BinderError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self.reply {
             BR_FAILED_REPLY => match self.source.as_ref() {
                 Some(source) => f
Signature · 1 line
2.51.0
maintainer Reviewed-by on v17 3/11
#5 lore raw

Re: [PATCH v17 03/11] rust_binder: use `kernel::fmt`

Quoted 7 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit eafedbc7c050 ("rust_binder: add Rust Binder driver").

#6 lore raw

PATCH v17 4/11 rust_binder: use `core::ffi::CStr` method names

In reply to Tamir Duberstein

Prepare for core::ffi::CStr taking the place of kernel::str::CStr by avoiding methods that only exist on the latter.

This backslid in commit eafedbc7c050 ("rust_binder: add Rust Binder driver").

---
 drivers/android/binder/stats.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/android/binder/stats.rs +2 -2
index a83ec111d2cb..10c43679d5c3 100644
@@ -72,7 +72,7 @@ pub(super) fn command_string(i: usize) -> &'static str {
         // SAFETY: Accessing `binder_command_strings` is always safe.
         let c_str_ptr = unsafe { binder_command_strings[i] };
         // SAFETY: The `binder_command_strings` array only contains nul-terminated strings.
-        let bytes = unsafe { CStr::from_char_ptr(c_str_ptr) }.as_bytes();
+        let bytes = unsafe { CStr::from_char_ptr(c_str_ptr) }.to_bytes();
         // SAFETY: The `binder_command_strings` array only contains strings with ascii-chars.
         unsafe { from_utf8_unchecked(bytes) }
     }
@@ -81,7 +81,7 @@ pub(super) fn return_string(i: usize) -> &'static str {
         // SAFETY: Accessing `binder_return_strings` is always safe.
         let c_str_ptr = unsafe { binder_return_strings[i] };
         // SAFETY: The `binder_command_strings` array only contains nul-terminated strings.
-        let bytes = unsafe { CStr::from_char_ptr(c_str_ptr) }.as_bytes();
+        let bytes = unsafe { CStr::from_char_ptr(c_str_ptr) }.to_bytes();
         // SAFETY: The `binder_command_strings` array only contains strings with ascii-chars.
         unsafe { from_utf8_unchecked(bytes) }
     }
Signature · 1 line
2.51.0
maintainer Reviewed-by on v17 4/11
#7 lore raw

Re: [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names

Quoted 7 lines · Tamir Duberstein

Prepare for core::ffi::CStr taking the place of kernel::str::CStr by avoiding methods that only exist on the latter.

This backslid in commit eafedbc7c050 ("rust_binder: add Rust Binder driver").

#8 lore raw

PATCH v17 5/11 rnull: use `kernel::fmt`

In reply to Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit d969d504bc13 ("rnull: enable configuration via configfs") and commit 34585dc649fb ("rnull: add soft-irq completion support").

---
 drivers/block/rnull/configfs.rs | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
drivers/block/rnull/configfs.rs +5 -4
index 8498e9bae6fd..6713a6d92391 100644
@@ -1,12 +1,13 @@
 // SPDX-License-Identifier: GPL-2.0
 
 use super::{NullBlkDevice, THIS_MODULE};
-use core::fmt::{Display, Write};
 use kernel::{
     block::mq::gen_disk::{GenDisk, GenDiskBuilder},
     c_str,
     configfs::{self, AttributeOperations},
-    configfs_attrs, new_mutex,
+    configfs_attrs,
+    fmt::{self, Write as _},
+    new_mutex,
     page::PAGE_SIZE,
     prelude::*,
     str::{kstrtobool_bytes, CString},
@@ -99,8 +100,8 @@ fn try_from(value: u8) -> Result<Self> {
     }
 }
 
-impl Display for IRQMode {
-    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+impl fmt::Display for IRQMode {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
             Self::None => f.write_str("0")?,
             Self::Soft => f.write_str("1")?,
Signature · 1 line
2.51.0
maintainer Acked-by on v17 5/11
#9 lore raw

Re: [PATCH v17 05/11] rnull: use `kernel::fmt`

Quoted 8 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit d969d504bc13 ("rnull: enable configuration via configfs") and commit 34585dc649fb ("rnull: add soft-irq completion support").

Best regards,
Andreas Hindborg

#10 lore raw

PATCH v17 6/11 rust: alloc: use `kernel::fmt`

In reply to Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 9def0d0a2a1c ("rust: alloc: add Vec::push_within_capacity").

---
 rust/kernel/alloc/kvec/errors.rs | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
rust/kernel/alloc/kvec/errors.rs +7 -7
index 21a920a4b09b..e7de5049ee47 100644
@@ -2,14 +2,14 @@
 
 //! Errors for the [`Vec`] type.
 
-use kernel::fmt::{self, Debug, Formatter};
+use kernel::fmt;
 use kernel::prelude::*;
 
 /// Error type for [`Vec::push_within_capacity`].
 pub struct PushError<T>(pub T);
 
-impl<T> Debug for PushError<T> {
-    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+impl<T> fmt::Debug for PushError<T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "Not enough capacity")
     }
 }
@@ -25,8 +25,8 @@ fn from(_: PushError<T>) -> Error {
 /// Error type for [`Vec::remove`].
 pub struct RemoveError;
 
-impl Debug for RemoveError {
-    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+impl fmt::Debug for RemoveError {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         write!(f, "Index out of bounds")
     }
 }
@@ -45,8 +45,8 @@ pub enum InsertError<T> {
     OutOfCapacity(T),
 }
 
-impl<T> Debug for InsertError<T> {
-    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
+impl<T> fmt::Debug for InsertError<T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         match self {
             InsertError::IndexOutOfBounds(_) => write!(f, "Index out of bounds"),
             InsertError::OutOfCapacity(_) => write!(f, "Not enough capacity"),
Signature · 1 line
2.51.0
#11 lore raw

Re: [PATCH v17 06/11] rust: alloc: use `kernel::fmt`

Quoted 17 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 9def0d0a2a1c ("rust: alloc: add Vec::push_within_capacity").

---
 rust/kernel/alloc/kvec/errors.rs | 14 +++++++-------
 1 file changed, 7 insertions(+), 7 deletions(-)
rust/kernel/alloc/kvec/errors.rs +0 -0
index 21a920a4b09b..e7de5049ee47 100644

rust/kernel/alloc/kvec/errors.rs line 6

Quoted 6 lines
rust/kernel/alloc/kvec/errors.rs +1 -1
@@ -2,14 +2,14 @@
 
 //! Errors for the [`Vec`] type.
 
-use kernel::fmt::{self, Debug, Formatter};
+use kernel::fmt;
 use kernel::prelude::*;

Oops, this one is not necessary. Just a style change here.

maintainer Reviewed-by on v17 6/11
#12 lore raw

Re: [PATCH v17 06/11] rust: alloc: use `kernel::fmt`

In reply to Tamir Duberstein
Quoted 7 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 9def0d0a2a1c ("rust: alloc: add Vec::push_within_capacity").

maintainer Acked-by on v17 6/11
#13 lore raw

Re: [PATCH v17 06/11] rust: alloc: use `kernel::fmt`

In reply to Tamir Duberstein
Quoted 7 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 9def0d0a2a1c ("rust: alloc: add Vec::push_within_capacity").

#14 lore raw

PATCH v17 7/11 rust: debugfs: use `kernel::fmt`

In reply to Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 40ecc49466c8 ("rust: debugfs: Add support for callback-based files") and commit 5e40b591cb46 ("rust: debugfs: Add support for read-only files").

---
 rust/kernel/debugfs.rs                   |  2 +-
 rust/kernel/debugfs/callback_adapters.rs |  7 +++----
 rust/kernel/debugfs/file_ops.rs          |  6 +++---
 rust/kernel/debugfs/traits.rs            | 10 +++++-----
 4 files changed, 12 insertions(+), 13 deletions(-)
rust/kernel/debugfs.rs +1 -1
index 381c23b3dd83..8c35d032acfe 100644
@@ -8,12 +8,12 @@
 // When DebugFS is disabled, many parameters are dead. Linting for this isn't helpful.
 #![cfg_attr(not(CONFIG_DEBUG_FS), allow(unused_variables))]
 
+use crate::fmt;
 use crate::prelude::*;
 use crate::str::CStr;
 #[cfg(CONFIG_DEBUG_FS)]
 use crate::sync::Arc;
 use crate::uaccess::UserSliceReader;
-use core::fmt;
 use core::marker::PhantomData;
 use core::marker::PhantomPinned;
 #[cfg(CONFIG_DEBUG_FS)]
rust/kernel/debugfs/callback_adapters.rs +3 -4
index 6c024230f676..a260d8dee051 100644
@@ -5,10 +5,9 @@
 //! than a trait implementation. If provided, it will override the trait implementation.
 
 use super::{Reader, Writer};
+use crate::fmt;
 use crate::prelude::*;
 use crate::uaccess::UserSliceReader;
-use core::fmt;
-use core::fmt::Formatter;
 use core::marker::PhantomData;
 use core::ops::Deref;
 
@@ -76,9 +75,9 @@ fn deref(&self) -> &D {
 
 impl<D, F> Writer for FormatAdapter<D, F>
 where
-    F: Fn(&D, &mut Formatter<'_>) -> fmt::Result + 'static,
+    F: Fn(&D, &mut fmt::Formatter<'_>) -> fmt::Result + 'static,
 {
-    fn write(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
+    fn write(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         // SAFETY: FormatAdapter<_, F> can only be constructed if F is inhabited
         let f: &F = unsafe { materialize_zst() };
         f(&self.inner, fmt)
rust/kernel/debugfs/file_ops.rs +3 -3
index 50fead17b6f3..9ad5e3fa6f69 100644
@@ -3,11 +3,11 @@
 
 use super::{Reader, Writer};
 use crate::debugfs::callback_adapters::Adapter;
+use crate::fmt;
 use crate::prelude::*;
 use crate::seq_file::SeqFile;
 use crate::seq_print;
 use crate::uaccess::UserSlice;
-use core::fmt::{Display, Formatter, Result};
 use core::marker::PhantomData;
 
 #[cfg(CONFIG_DEBUG_FS)]
@@ -65,8 +65,8 @@ fn deref(&self) -> &Self::Target {
 
 struct WriterAdapter<T>(T);
 
-impl<'a, T: Writer> Display for WriterAdapter<&'a T> {
-    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+impl<'a, T: Writer> fmt::Display for WriterAdapter<&'a T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         self.0.write(f)
     }
 }
rust/kernel/debugfs/traits.rs +5 -5
index ab009eb254b3..ad33bfbc7669 100644
@@ -3,10 +3,10 @@
 
 //! Traits for rendering or updating values exported to DebugFS.
 
+use crate::fmt;
 use crate::prelude::*;
 use crate::sync::Mutex;
 use crate::uaccess::UserSliceReader;
-use core::fmt::{self, Debug, Formatter};
 use core::str::FromStr;
 use core::sync::atomic::{
     AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64,
@@ -24,17 +24,17 @@
 /// explicitly instead.
 pub trait Writer {
     /// Formats the value using the given formatter.
-    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
+    fn write(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
 }
 
 impl<T: Writer> Writer for Mutex<T> {
-    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+    fn write(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         self.lock().write(f)
     }
 }
 
-impl<T: Debug> Writer for T {
-    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+impl<T: fmt::Debug> Writer for T {
+    fn write(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         writeln!(f, "{self:?}")
     }
 }
Signature · 1 line
2.51.0
Reviewed-by on v17 7/11
#15 lore raw

Re: [PATCH v17 07/11] rust: debugfs: use `kernel::fmt`

Quoted 8 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 40ecc49466c8 ("rust: debugfs: Add support for callback-based files") and commit 5e40b591cb46 ("rust: debugfs: Add support for read-only files").

Quoted 8 lines
---
 rust/kernel/debugfs.rs                   |  2 +-
 rust/kernel/debugfs/callback_adapters.rs |  7 +++----
 rust/kernel/debugfs/file_ops.rs          |  6 +++---
 rust/kernel/debugfs/traits.rs            | 10 +++++-----
 4 files changed, 12 insertions(+), 13 deletions(-)
Quoted 133 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 40ecc49466c8 ("rust: debugfs: Add support for callback-based files") and commit 5e40b591cb46 ("rust: debugfs: Add support for read-only files").

---
 rust/kernel/debugfs.rs                   |  2 +-
 rust/kernel/debugfs/callback_adapters.rs |  7 +++----
 rust/kernel/debugfs/file_ops.rs          |  6 +++---
 rust/kernel/debugfs/traits.rs            | 10 +++++-----
 4 files changed, 12 insertions(+), 13 deletions(-)
rust/kernel/debugfs.rs +1 -1
index 381c23b3dd83..8c35d032acfe 100644
@@ -8,12 +8,12 @@
 // When DebugFS is disabled, many parameters are dead. Linting for this isn't helpful.
 #![cfg_attr(not(CONFIG_DEBUG_FS), allow(unused_variables))]
 
+use crate::fmt;
 use crate::prelude::*;
 use crate::str::CStr;
 #[cfg(CONFIG_DEBUG_FS)]
 use crate::sync::Arc;
 use crate::uaccess::UserSliceReader;
-use core::fmt;
 use core::marker::PhantomData;
 use core::marker::PhantomPinned;
 #[cfg(CONFIG_DEBUG_FS)]
rust/kernel/debugfs/callback_adapters.rs +3 -4
index 6c024230f676..a260d8dee051 100644
@@ -5,10 +5,9 @@
 //! than a trait implementation. If provided, it will override the trait implementation.
 
 use super::{Reader, Writer};
+use crate::fmt;
 use crate::prelude::*;
 use crate::uaccess::UserSliceReader;
-use core::fmt;
-use core::fmt::Formatter;
 use core::marker::PhantomData;
 use core::ops::Deref;
 
@@ -76,9 +75,9 @@ fn deref(&self) -> &D {
 
 impl<D, F> Writer for FormatAdapter<D, F>
 where
-    F: Fn(&D, &mut Formatter<'_>) -> fmt::Result + 'static,
+    F: Fn(&D, &mut fmt::Formatter<'_>) -> fmt::Result + 'static,
 {
-    fn write(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
+    fn write(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
         // SAFETY: FormatAdapter<_, F> can only be constructed if F is inhabited
         let f: &F = unsafe { materialize_zst() };
         f(&self.inner, fmt)
rust/kernel/debugfs/file_ops.rs +3 -3
index 50fead17b6f3..9ad5e3fa6f69 100644
@@ -3,11 +3,11 @@
 
 use super::{Reader, Writer};
 use crate::debugfs::callback_adapters::Adapter;
+use crate::fmt;
 use crate::prelude::*;
 use crate::seq_file::SeqFile;
 use crate::seq_print;
 use crate::uaccess::UserSlice;
-use core::fmt::{Display, Formatter, Result};
 use core::marker::PhantomData;
 
 #[cfg(CONFIG_DEBUG_FS)]
@@ -65,8 +65,8 @@ fn deref(&self) -> &Self::Target {
 
 struct WriterAdapter<T>(T);
 
-impl<'a, T: Writer> Display for WriterAdapter<&'a T> {
-    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+impl<'a, T: Writer> fmt::Display for WriterAdapter<&'a T> {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         self.0.write(f)
     }
 }
rust/kernel/debugfs/traits.rs +5 -6
index ab009eb254b3..ad33bfbc7669 100644
@@ -3,10 +3,10 @@
 
 //! Traits for rendering or updating values exported to DebugFS.
 
+use crate::fmt;
 use crate::prelude::*;
 use crate::sync::Mutex;
 use crate::uaccess::UserSliceReader;
-use core::fmt::{self, Debug, Formatter};
 use core::str::FromStr;
 use core::sync::atomic::{
     AtomicI16, AtomicI32, AtomicI64, AtomicI8, AtomicIsize, AtomicU16, AtomicU32, AtomicU64,
@@ -24,17 +24,17 @@
 /// explicitly instead.
 pub trait Writer {
     /// Formats the value using the given formatter.
-    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result;
+    fn write(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
 }
 
 impl<T: Writer> Writer for Mutex<T> {
-    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+    fn write(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         self.lock().write(f)
     }
 }
 
-impl<T: Debug> Writer for T {
-    fn write(&self, f: &mut Formatter<'_>) -> fmt::Result {
+impl<T: fmt::Debug> Writer for T {
+    fn write(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
         writeln!(f, "{self:?}")
     }
 }
 
--

2.51.0

maintainer Acked-by on v17 7/11
#16 lore raw

Re: [PATCH v17 07/11] rust: debugfs: use `kernel::fmt`

In reply to Tamir Duberstein
Quoted 8 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit 40ecc49466c8 ("rust: debugfs: Add support for callback-based files") and commit 5e40b591cb46 ("rust: debugfs: Add support for read-only files").

#17 lore raw

PATCH v17 8/11 rust: pci: use `kernel::fmt`

In reply to Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit ed78a01887e2 ("rust: pci: provide access to PCI Class and Class-related items").

---
 rust/kernel/pci/id.rs | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
rust/kernel/pci/id.rs +1 -2
index 7f2a7f57507f..5f5d59ff49fc 100644
@@ -4,8 +4,7 @@
 //!
 //! This module contains PCI class codes, Vendor IDs, and supporting types.
 
-use crate::{bindings, error::code::EINVAL, error::Error, prelude::*};
-use core::fmt;
+use crate::{bindings, error::code::EINVAL, error::Error, fmt, prelude::*};
 
 /// PCI device class codes.
 ///
Signature · 1 line
2.51.0
maintainer Acked-by on v17 8/11
#18 lore raw

Re: [PATCH v17 08/11] rust: pci: use `kernel::fmt`

Quoted 7 lines · Tamir Duberstein

Reduce coupling to implementation details of the formatting machinery by avoiding direct use for core's formatting traits and macros.

This backslid in commit ed78a01887e2 ("rust: pci: provide access to PCI Class and Class-related items").

#19 lore raw

PATCH v17 9/11 rust: remove spurious `use core::fmt::Debug`

In reply to Tamir Duberstein

We want folks to use kernel::fmt but this is only used for derive so can be removed entirely.

This backslid in commit ea60cea07d8c ("rust: add Alignment type").

---
 rust/kernel/ptr.rs | 1 -
 1 file changed, 1 deletion(-)
rust/kernel/ptr.rs +0 -1
index 2e5e2a090480..e3893ed04049 100644
@@ -2,7 +2,6 @@
 
 //! Types and functions to work with pointers and addresses.
 
-use core::fmt::Debug;
 use core::mem::align_of;
 use core::num::NonZero;
 
Signature · 1 line
2.51.0
#21 lore raw

PATCH v17 10/11 rust: support formatting of foreign types

In reply to Tamir Duberstein

Introduce a fmt! macro which wraps all arguments in kernel::fmt::Adapter and a kernel::fmt::Display trait. This enables formatting of foreign types (like core::ffi::CStr) that do not implement core::fmt::Display due to concerns around lossy conversions which do not apply in the kernel.

---
 rust/kernel/fmt.rs     | 87 +++++++++++++++++++++++++++++++++++++++++++++-
 rust/kernel/prelude.rs |  3 +-
 rust/macros/fmt.rs     | 94 ++++++++++++++++++++++++++++++++++++++++++++++++++
 rust/macros/lib.rs     | 19 ++++++++++
 rust/macros/quote.rs   |  7 ++++
 5 files changed, 207 insertions(+), 3 deletions(-)
rust/kernel/fmt.rs +86 -1
index 0306e8388968..84d634201d90 100644
@@ -4,4 +4,89 @@
 //!
 //! This module is intended to be used in place of `core::fmt` in kernel code.
 
-pub use core::fmt::{Arguments, Debug, Display, Error, Formatter, Result, Write};
+pub use core::fmt::{Arguments, Debug, Error, Formatter, Result, Write};
+
+/// Internal adapter used to route allow implementations of formatting traits for foreign types.
+///
+/// It is inserted automatically by the [`fmt!`] macro and is not meant to be used directly.
+///
+/// [`fmt!`]: crate::prelude::fmt!
+#[doc(hidden)]
+pub struct Adapter<T>(pub T);
+
+macro_rules! impl_fmt_adapter_forward {
+    ($($trait:ident),* $(,)?) => {
+        $(
+            impl<T: $trait> $trait for Adapter<T> {
+                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+                    let Self(t) = self;
+                    $trait::fmt(t, f)
+                }
+            }
+        )*
+    };
+}
+
+use core::fmt::{Binary, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex};
+impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, Pointer, LowerExp, UpperExp);
+
+/// A copy of [`core::fmt::Display`] that allows us to implement it for foreign types.
+///
+/// Types should implement this trait rather than [`core::fmt::Display`]. Together with the
+/// [`Adapter`] type and [`fmt!`] macro, it allows for formatting foreign types (e.g. types from
+/// core) which do not implement [`core::fmt::Display`] directly.
+///
+/// [`fmt!`]: crate::prelude::fmt!
+pub trait Display {
+    /// Same as [`core::fmt::Display::fmt`].
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result;
+}
+
+impl<T: ?Sized + Display> Display for &T {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        Display::fmt(*self, f)
+    }
+}
+
+impl<T: ?Sized + Display> core::fmt::Display for Adapter<&T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        let Self(t) = self;
+        Display::fmt(t, f)
+    }
+}
+
+macro_rules! impl_display_forward {
+    ($(
+        $( { $($generics:tt)* } )? $ty:ty $( { where $($where:tt)* } )?
+    ),* $(,)?) => {
+        $(
+            impl$($($generics)*)? Display for $ty $(where $($where)*)? {
+                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+                    core::fmt::Display::fmt(self, f)
+                }
+            }
+        )*
+    };
+}
+
+impl_display_forward!(
+    bool,
+    char,
+    core::panic::PanicInfo<'_>,
+    Arguments<'_>,
+    i128,
+    i16,
+    i32,
+    i64,
+    i8,
+    isize,
+    str,
+    u128,
+    u16,
+    u32,
+    u64,
+    u8,
+    usize,
+    {<T: ?Sized>} crate::sync::Arc<T> {where crate::sync::Arc<T>: core::fmt::Display},
+    {<T: ?Sized>} crate::sync::UniqueArc<T> {where crate::sync::UniqueArc<T>: core::fmt::Display},
+);
rust/kernel/prelude.rs +1 -2
index 198d09a31449..26424ad7e989 100644
@@ -25,7 +25,7 @@
 pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec};
 
 #[doc(no_inline)]
-pub use macros::{export, kunit_tests, module, vtable};
+pub use macros::{export, fmt, kunit_tests, module, vtable};
 
 pub use pin_init::{init, pin_data, pin_init, pinned_drop, InPlaceWrite, Init, PinInit, Zeroable};
 
@@ -36,7 +36,6 @@
 pub use super::dbg;
 pub use super::{dev_alert, dev_crit, dev_dbg, dev_emerg, dev_err, dev_info, dev_notice, dev_warn};
 pub use super::{pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn};
-pub use core::format_args as fmt;
 
 pub use super::{try_init, try_pin_init};
 
rust/macros/fmt.rs new file +94 -0

94 lines not on this page · raw message

rust/macros/lib.rs +19 -0
index fa847cf3a9b5..793f712dbf7c 100644
@@ -15,6 +15,7 @@
 mod quote;
 mod concat_idents;
 mod export;
+mod fmt;
 mod helpers;
 mod kunit;
 mod module;
@@ -201,6 +202,24 @@ pub fn export(attr: TokenStream, ts: TokenStream) -> TokenStream {
     export::export(attr, ts)
 }
 
+/// Like [`core::format_args!`], but automatically wraps arguments in [`kernel::fmt::Adapter`].
+///
+/// This macro allows generating `fmt::Arguments` while ensuring that each argument is wrapped with
+/// `::kernel::fmt::Adapter`, which customizes formatting behavior for kernel logging.
+///
+/// Named arguments used in the format string (e.g. `{foo}`) are detected and resolved from local
+/// bindings. All positional and named arguments are automatically wrapped.
+///
+/// This macro is an implementation detail of other kernel logging macros like [`pr_info!`] and
+/// should not typically be used directly.
+///
+/// [`kernel::fmt::Adapter`]: ../kernel/fmt/struct.Adapter.html
+/// [`pr_info!`]: ../kernel/macro.pr_info.html
+#[proc_macro]
+pub fn fmt(input: TokenStream) -> TokenStream {
+    fmt::fmt(input)
+}
+
 /// Concatenate two identifiers.
 ///
 /// This is useful in macros that need to declare or reference items with names
rust/macros/quote.rs +7 -0
index acc140c18653..ddfc21577539 100644
@@ -48,6 +48,7 @@ macro_rules! quote_spanned {
     ($span:expr => $($tt:tt)*) => {{
         let mut tokens = ::proc_macro::TokenStream::new();
         {
+            #[allow(unused_variables)]
             let span = $span;
             quote_spanned!(@proc tokens span $($tt)*);
         }
@@ -146,6 +147,12 @@ macro_rules! quote_spanned {
         )]);
         quote_spanned!(@proc $v $span $($tt)*);
     };
+    (@proc $v:ident $span:ident & $($tt:tt)*) => {
+        $v.extend([::proc_macro::TokenTree::Punct(
+            ::proc_macro::Punct::new('&', ::proc_macro::Spacing::Alone),
+        )]);
+        quote_spanned!(@proc $v $span $($tt)*);
+    };
     (@proc $v:ident $span:ident _ $($tt:tt)*) => {
         $v.extend([::proc_macro::TokenTree::Ident(
             ::proc_macro::Ident::new("_", $span),
Signature · 1 line
2.51.0
#22 lore raw

PATCH v17 11/11 rust: replace `CStr` with `core::ffi::CStr`

In reply to Tamir Duberstein

kernel::ffi::CStr was introduced in commit d126d2380131 ("rust: str:
add CStr type") in November 2022 as an upstreaming of earlier work that was done in May 2021[0]. That earlier work, having predated the inclusion of CStr in core, largely duplicated the implementation of std::ffi::CStr.

std::ffi::CStr was moved to core::ffi::CStr in Rust 1.64 in September 2022. Hence replace kernel::str::CStr with core::ffi::CStr to reduce our custom code footprint, and retain needed custom functionality through an extension trait.

Add CStr to ffi and the kernel prelude.

---
 drivers/android/binder/stats.rs |   2 +-
 rust/ffi.rs                     |   2 +
 rust/kernel/device.rs           |   1 +
 rust/kernel/error.rs            |   2 +
 rust/kernel/firmware.rs         |   9 +-
 rust/kernel/prelude.rs          |   4 +-
 rust/kernel/seq_file.rs         |   2 +-
 rust/kernel/str.rs              | 395 +++++++++-------------------------------
 rust/kernel/sync/condvar.rs     |   2 +-
 rust/kernel/sync/lock.rs        |   2 +-
 rust/kernel/sync/lock/global.rs |   2 +-
 11 files changed, 110 insertions(+), 313 deletions(-)
drivers/android/binder/stats.rs +1 -1
index 10c43679d5c3..037002651941 100644
@@ -61,7 +61,7 @@ pub(crate) fn debug_print(&self, prefix: &str, m: &SeqFile) {
 
 mod strings {
     use core::str::from_utf8_unchecked;
-    use kernel::str::CStr;
+    use kernel::str::{CStr, CStrExt as _};
 
     extern "C" {
         static binder_command_strings: [*const u8; super::BC_COUNT];
rust/ffi.rs +2 -0
index d60aad792af4..f961e9728f59 100644
@@ -46,3 +46,5 @@ macro_rules! alias {
 }
 
 pub use core::ffi::c_void;
+
+pub use core::ffi::CStr;
rust/kernel/device.rs +1 -0
index 1321e6f0b53c..0b13aa60b685 100644
@@ -13,6 +13,7 @@
 
 #[cfg(CONFIG_PRINTK)]
 use crate::c_str;
+use crate::str::CStrExt as _;
 
 pub mod property;
 
rust/kernel/error.rs +2 -0
index 1c0e0e241daa..258b12afdcba 100644
@@ -182,6 +182,8 @@ pub fn name(&self) -> Option<&'static CStr> {
         if ptr.is_null() {
             None
         } else {
+            use crate::str::CStrExt as _;
+
             // SAFETY: The string returned by `errname` is static and `NUL`-terminated.
             Some(unsafe { CStr::from_char_ptr(ptr) })
         }
rust/kernel/firmware.rs +8 -1
index 94e6bb88b903..376e7e77453f 100644
@@ -4,7 +4,14 @@
 //!
 //! C header: [`include/linux/firmware.h`](srctree/include/linux/firmware.h)
 
-use crate::{bindings, device::Device, error::Error, error::Result, ffi, str::CStr};
+use crate::{
+    bindings,
+    device::Device,
+    error::Error,
+    error::Result,
+    ffi,
+    str::{CStr, CStrExt as _},
+};
 use core::ptr::NonNull;
 
 /// # Invariants
rust/kernel/prelude.rs +2 -2
index 26424ad7e989..33fa8404c5c6 100644
@@ -19,7 +19,7 @@
 
 pub use ::ffi::{
     c_char, c_int, c_long, c_longlong, c_schar, c_short, c_uchar, c_uint, c_ulong, c_ulonglong,
-    c_ushort, c_void,
+    c_ushort, c_void, CStr,
 };
 
 pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec};
@@ -43,7 +43,7 @@
 
 pub use super::error::{code::*, Error, Result};
 
-pub use super::{str::CStr, ThisModule};
+pub use super::{str::CStrExt as _, ThisModule};
 
 pub use super::init::InPlaceInit;
 
rust/kernel/seq_file.rs +1 -1
index 59fbfc2473f8..855e533813a6 100644
@@ -4,7 +4,7 @@
 //!
 //! C header: [`include/linux/seq_file.h`](srctree/include/linux/seq_file.h)
 
-use crate::{bindings, c_str, fmt, types::NotThreadSafe, types::Opaque};
+use crate::{bindings, c_str, fmt, str::CStrExt as _, types::NotThreadSafe, types::Opaque};
 
 /// A utility for generating the contents of a seq file.
 #[repr(transparent)]
rust/kernel/str.rs +90 -305

515 lines not on this page · raw message

rust/kernel/sync/condvar.rs +1 -1
index c6ec64295c9f..a24e25a690ee 100644
@@ -8,7 +8,7 @@
 use super::{lock::Backend, lock::Guard, LockClassKey};
 use crate::{
     ffi::{c_int, c_long},
-    str::CStr,
+    str::{CStr, CStrExt as _},
     task::{
         MAX_SCHEDULE_TIMEOUT, TASK_FREEZABLE, TASK_INTERRUPTIBLE, TASK_NORMAL, TASK_UNINTERRUPTIBLE,
     },
rust/kernel/sync/lock.rs +1 -1
index 27202beef90c..5d7991e6d373 100644
@@ -7,7 +7,7 @@
 
 use super::LockClassKey;
 use crate::{
-    str::CStr,
+    str::{CStr, CStrExt as _},
     types::{NotThreadSafe, Opaque, ScopeGuard},
 };
 use core::{cell::UnsafeCell, marker::PhantomPinned, pin::Pin};
rust/kernel/sync/lock/global.rs +1 -1
index d65f94b5caf2..79d0ef7fda86 100644
@@ -5,7 +5,7 @@
 //! Support for defining statics containing locks.
 
 use crate::{
-    str::CStr,
+    str::{CStr, CStrExt as _},
     sync::lock::{Backend, Guard, Lock},
     sync::{LockClassKey, LockedBy},
     types::Opaque,
Signature · 1 line
2.51.0
maintainer
#23 lore raw
In reply to Tamir Duberstein
Quoted 12 lines · Tamir Duberstein

This picks up from Michal Rostecki's work[0]. Per Michal's guidance I have omitted Co-authored tags, as the end result is quite different.

This series is intended to be taken through rust-next. The final patch in the series requires some other subsystems' Acked-bys:
- drivers/android/binder/stats.rs: rust_binder. Alice, could you take a look?
- rust/kernel/device.rs: driver-core. Already acked by gregkh.
- rust/kernel/firmware.rs: driver-core. Danilo, could you take a look?
- rust/kernel/seq_file.rs: vfs. Christian, could you take a look?
- rust/kernel/sync/*: locking-core. Boqun, could you take a look?

Quoted 4 lines

You need a few more changes:

rust/kernel/clk.rs +2 -2
index 1e6c8c42fb3a..c1cfaeaa36a2 100644
@@ -136,7 +136,7 @@ impl Clk {
         ///
         /// [`clk_get`]: https://docs.kernel.org/core-api/kernel-api.html#c.clk_get
         pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
-            let con_id = name.map_or(ptr::null(), |n| n.as_ptr());
+            let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
 
             // SAFETY: It is safe to call [`clk_get`] for a valid device pointer.
             //
@@ -304,7 +304,7 @@ impl OptionalClk {
         /// [`clk_get_optional`]:
         /// https://docs.kernel.org/core-api/kernel-api.html#c.clk_get_optional
         pub fn get(dev: &Device, name: Option<&CStr>) -> Result<Self> {
-            let con_id = name.map_or(ptr::null(), |n| n.as_ptr());
+            let con_id = name.map_or(ptr::null(), |n| n.as_char_ptr());
 
             // SAFETY: It is safe to call [`clk_get_optional`] for a valid device pointer.
             //
rust/kernel/configfs.rs +1 -1
index 10f1547ca9f1..466fb7f40762 100644
@@ -157,7 +157,7 @@ pub fn new(
                     unsafe {
                         bindings::config_group_init_type_name(
                             &mut (*place.get()).su_group,
-                            name.as_ptr(),
+                            name.as_char_ptr(),
                             item_type.as_ptr(),
                         )
                     };
rust/kernel/debugfs/entry.rs +1 -2
index f99402cd3ba0..5de0ebc27198 100644
@@ -2,8 +2,7 @@
 // Copyright (C) 2025 Google LLC.
 
 use crate::debugfs::file_ops::FileOps;
-use crate::ffi::c_void;
-use crate::str::CStr;
+use crate::prelude::*;
 use crate::sync::Arc;
 use core::marker::PhantomData;
 
rust/kernel/regulator.rs +6 -3
index b55a201e5029..65a4eb096cae 100644
@@ -84,7 +84,7 @@ pub struct Error<State: RegulatorState> {
 pub fn devm_enable(dev: &Device<Bound>, name: &CStr) -> Result {
     // SAFETY: `dev` is a valid and bound device, while `name` is a valid C
     // string.
-    to_result(unsafe { bindings::devm_regulator_get_enable(dev.as_raw(), name.as_ptr()) })
+    to_result(unsafe { bindings::devm_regulator_get_enable(dev.as_raw(), name.as_char_ptr()) })
 }
 
 /// Same as [`devm_enable`], but calls `devm_regulator_get_enable_optional`
@@ -102,7 +102,9 @@ pub fn devm_enable(dev: &Device<Bound>, name: &CStr) -> Result {
 pub fn devm_enable_optional(dev: &Device<Bound>, name: &CStr) -> Result {
     // SAFETY: `dev` is a valid and bound device, while `name` is a valid C
     // string.
-    to_result(unsafe { bindings::devm_regulator_get_enable_optional(dev.as_raw(), name.as_ptr()) })
+    to_result(unsafe {
+        bindings::devm_regulator_get_enable_optional(dev.as_raw(), name.as_char_ptr())
+    })
 }
 
 /// A `struct regulator` abstraction.
@@ -268,7 +270,8 @@ pub fn get_voltage(&self) -> Result<Voltage> {
     fn get_internal(dev: &Device, name: &CStr) -> Result<Regulator<T>> {
         // SAFETY: It is safe to call `regulator_get()`, on a device pointer
         // received from the C code.
-        let inner = from_err_ptr(unsafe { bindings::regulator_get(dev.as_raw(), name.as_ptr()) })?;
+        let inner =
+            from_err_ptr(unsafe { bindings::regulator_get(dev.as_raw(), name.as_char_ptr()) })?;
 
         // SAFETY: We can safely trust `inner` to be a pointer to a valid
         // regulator if `ERR_PTR` was not returned.
maintainer
#24 lore raw
Quoted 13 lines · Alice Ryhl
Quoted 12 lines · Tamir Duberstein

This picks up from Michal Rostecki's work[0]. Per Michal's guidance I have omitted Co-authored tags, as the end result is quite different.

This series is intended to be taken through rust-next. The final patch in the series requires some other subsystems' Acked-bys:
- drivers/android/binder/stats.rs: rust_binder. Alice, could you take a look?
- rust/kernel/device.rs: driver-core. Already acked by gregkh.
- rust/kernel/firmware.rs: driver-core. Danilo, could you take a look?
- rust/kernel/seq_file.rs: vfs. Christian, could you take a look?
- rust/kernel/sync/*: locking-core. Boqun, could you take a look?

Quoted 6 lines
Quoted 4 lines

You need a few more changes:

One more:

rust/kernel/drm/ioctl.rs +1 -1
index 69efbdb4c85a..5489961a62ca 100644
@@ -156,7 +156,7 @@ macro_rules! declare_drm_ioctls {
                         Some($cmd)
                     },
                     flags: $flags,
-                    name: $crate::c_str!(::core::stringify!($cmd)).as_char_ptr(),
+                    name: $crate::str::as_char_ptr_in_const_context($crate::c_str!(::core::stringify!($cmd))),
                 }
             ),*];
             ioctls
#25 lore raw
Quoted 29 lines · Alice Ryhl
Quoted 13 lines · Alice Ryhl
Quoted 12 lines · Tamir Duberstein

This picks up from Michal Rostecki's work[0]. Per Michal's guidance I have omitted Co-authored tags, as the end result is quite different.

This series is intended to be taken through rust-next. The final patch in the series requires some other subsystems' Acked-bys:
- drivers/android/binder/stats.rs: rust_binder. Alice, could you take a look?
- rust/kernel/device.rs: driver-core. Already acked by gregkh.
- rust/kernel/firmware.rs: driver-core. Danilo, could you take a look?
- rust/kernel/seq_file.rs: vfs. Christian, could you take a look?
- rust/kernel/sync/*: locking-core. Boqun, could you take a look?

Quoted 6 lines
Quoted 4 lines

You need a few more changes:

One more:

rust/kernel/drm/ioctl.rs +0 -0
index 69efbdb4c85a..5489961a62ca 100644

rust/kernel/drm/ioctl.rs macro_rules! declare_drm_ioctls { · line 162

Quoted 8 lines
rust/kernel/drm/ioctl.rs +1 -1
@@ -156,7 +156,7 @@ macro_rules! declare_drm_ioctls {
                         Some($cmd)
                     },
                     flags: $flags,
-                    name: $crate::c_str!(::core::stringify!($cmd)).as_char_ptr(),
+                    name: $crate::str::as_char_ptr_in_const_context($crate::c_str!(::core::stringify!($cmd))),
                 }
             ),*];
             ioctls

Thanks! Sent v18 on Saturday. Those as_ptr() -> as_char_ptr() were tricky because they relied on deref to &[u8].