* [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr
@ 2025-10-15 19:24 Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 01/11] samples: rust: platform: remove trailing commas Tamir Duberstein
` (11 more replies)
0 siblings, 12 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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-by`s:
- 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?
Link: https://lore.kernel.org/rust-for-linux/20240819153656.28807-2-vadorovsky@protonmail.com/t/#u [0]
Closes: https://github.com/Rust-for-Linux/linux/issues/1075
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
Changes in v17:
- Rebase on rust-next and fix backsliding relative to series 2a and 2b.
- Link to v16: https://lore.kernel.org/r/20250925-cstr-core-v16-0-5cdcb3470ec2@gmail.com
Changes in v16:
- Rebase on rust-next.
- Link to v15: https://lore.kernel.org/r/20250813-cstr-core-v15-0-c732d9223f4e@gmail.com
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/20250710-cstr-core-v14-0-ca7e0ca82c82@gmail.com
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/20250701-cstr-core-v13-0-29f7d3eb97a6@gmail.com
Changes in v13:
- Rebase on v6.16-rc4.
- Link to v12: https://lore.kernel.org/r/20250619-cstr-core-v12-0-80c9c7b45900@gmail.com
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/20250530-cstr-core-v11-0-cd9c0cbcb902@gmail.com
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/20240906164448.2268368-1-paddymills@proton.me/.
(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/20250524-cstr-core-v10-0-6412a94d9d75@gmail.com
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/20250317-cstr-core-v9-0-51d6cc522f62@gmail.com
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/20250203-cstr-core-v8-0-cb3f26e78686@gmail.com
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/20250202-cstr-core-v7-0-da1802520438@gmail.com
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/20250202-cstr-core-v6-0-8469cd6d29fd@gmail.com
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,
--
Tamir Duberstein <tamird@gmail.com>
^ permalink raw reply [flat|nested] 26+ messages in thread
* [PATCH v17 01/11] samples: rust: platform: remove trailing commas
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 02/11] rust_binder: remove trailing comma Tamir Duberstein
` (10 subsequent siblings)
11 siblings, 0 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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 them.
Acked-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
samples/rust/rust_driver_platform.rs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/samples/rust/rust_driver_platform.rs b/samples/rust/rust_driver_platform.rs
index 6473baf4f120..8a82e251820f 100644
--- a/samples/rust/rust_driver_platform.rs
+++ b/samples/rust/rust_driver_platform.rs
@@ -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)?;
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 02/11] rust_binder: remove trailing comma
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 01/11] samples: rust: platform: remove trailing commas Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:30 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 03/11] rust_binder: use `kernel::fmt` Tamir Duberstein
` (9 subsequent siblings)
11 siblings, 1 reply; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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.
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
drivers/android/binder/process.rs | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/drivers/android/binder/process.rs b/drivers/android/binder/process.rs
index f13a747e784c..d8111c990f21 100644
--- a/drivers/android/binder/process.rs
+++ b/drivers/android/binder/process.rs
@@ -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 { "" }
);
}
}
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 03/11] rust_binder: use `kernel::fmt`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 01/11] samples: rust: platform: remove trailing commas Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 02/11] rust_binder: remove trailing comma Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names Tamir Duberstein
` (8 subsequent siblings)
11 siblings, 1 reply; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
drivers/android/binder/error.rs | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/drivers/android/binder/error.rs b/drivers/android/binder/error.rs
index 9921827267d0..b24497cfa292 100644
--- a/drivers/android/binder/error.rs
+++ b/drivers/android/binder/error.rs
@@ -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
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (2 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 03/11] rust_binder: use `kernel::fmt` Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 05/11] rnull: use `kernel::fmt` Tamir Duberstein
` (7 subsequent siblings)
11 siblings, 1 reply; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
drivers/android/binder/stats.rs | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/drivers/android/binder/stats.rs b/drivers/android/binder/stats.rs
index a83ec111d2cb..10c43679d5c3 100644
--- a/drivers/android/binder/stats.rs
+++ b/drivers/android/binder/stats.rs
@@ -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) }
}
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 05/11] rnull: use `kernel::fmt`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (3 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-16 8:42 ` Andreas Hindborg
2025-10-15 19:24 ` [PATCH v17 06/11] rust: alloc: " Tamir Duberstein
` (6 subsequent siblings)
11 siblings, 1 reply; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
drivers/block/rnull/configfs.rs | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)
diff --git a/drivers/block/rnull/configfs.rs b/drivers/block/rnull/configfs.rs
index 8498e9bae6fd..6713a6d92391 100644
--- a/drivers/block/rnull/configfs.rs
+++ b/drivers/block/rnull/configfs.rs
@@ -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")?,
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 06/11] rust: alloc: use `kernel::fmt`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (4 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 05/11] rnull: use `kernel::fmt` Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:29 ` Tamir Duberstein
` (2 more replies)
2025-10-15 19:24 ` [PATCH v17 07/11] rust: debugfs: " Tamir Duberstein
` (5 subsequent siblings)
11 siblings, 3 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
rust/kernel/alloc/kvec/errors.rs | 14 +++++++-------
1 file changed, 7 insertions(+), 7 deletions(-)
diff --git a/rust/kernel/alloc/kvec/errors.rs b/rust/kernel/alloc/kvec/errors.rs
index 21a920a4b09b..e7de5049ee47 100644
--- a/rust/kernel/alloc/kvec/errors.rs
+++ b/rust/kernel/alloc/kvec/errors.rs
@@ -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"),
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 07/11] rust: debugfs: use `kernel::fmt`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (5 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 06/11] rust: alloc: " Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:39 ` Matthew Maurer
2025-10-15 19:45 ` Danilo Krummrich
2025-10-15 19:24 ` [PATCH v17 08/11] rust: pci: " Tamir Duberstein
` (4 subsequent siblings)
11 siblings, 2 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
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(-)
diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs
index 381c23b3dd83..8c35d032acfe 100644
--- a/rust/kernel/debugfs.rs
+++ b/rust/kernel/debugfs.rs
@@ -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)]
diff --git a/rust/kernel/debugfs/callback_adapters.rs b/rust/kernel/debugfs/callback_adapters.rs
index 6c024230f676..a260d8dee051 100644
--- a/rust/kernel/debugfs/callback_adapters.rs
+++ b/rust/kernel/debugfs/callback_adapters.rs
@@ -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)
diff --git a/rust/kernel/debugfs/file_ops.rs b/rust/kernel/debugfs/file_ops.rs
index 50fead17b6f3..9ad5e3fa6f69 100644
--- a/rust/kernel/debugfs/file_ops.rs
+++ b/rust/kernel/debugfs/file_ops.rs
@@ -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)
}
}
diff --git a/rust/kernel/debugfs/traits.rs b/rust/kernel/debugfs/traits.rs
index ab009eb254b3..ad33bfbc7669 100644
--- a/rust/kernel/debugfs/traits.rs
+++ b/rust/kernel/debugfs/traits.rs
@@ -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
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 08/11] rust: pci: use `kernel::fmt`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (6 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 07/11] rust: debugfs: " Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:46 ` Danilo Krummrich
2025-10-15 19:24 ` [PATCH v17 09/11] rust: remove spurious `use core::fmt::Debug` Tamir Duberstein
` (3 subsequent siblings)
11 siblings, 1 reply; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
rust/kernel/pci/id.rs | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/rust/kernel/pci/id.rs b/rust/kernel/pci/id.rs
index 7f2a7f57507f..5f5d59ff49fc 100644
--- a/rust/kernel/pci/id.rs
+++ b/rust/kernel/pci/id.rs
@@ -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.
///
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 09/11] rust: remove spurious `use core::fmt::Debug`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (7 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 08/11] rust: pci: " Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:33 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 10/11] rust: support formatting of foreign types Tamir Duberstein
` (2 subsequent siblings)
11 siblings, 1 reply; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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").
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
rust/kernel/ptr.rs | 1 -
1 file changed, 1 deletion(-)
diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs
index 2e5e2a090480..e3893ed04049 100644
--- a/rust/kernel/ptr.rs
+++ b/rust/kernel/ptr.rs
@@ -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;
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 10/11] rust: support formatting of foreign types
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (8 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 09/11] rust: remove spurious `use core::fmt::Debug` Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 11/11] rust: replace `CStr` with `core::ffi::CStr` Tamir Duberstein
2025-10-18 17:02 ` [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Alice Ryhl
11 siblings, 0 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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.
Suggested-by: Alice Ryhl <aliceryhl@google.com>
Link: https://rust-for-linux.zulipchat.com/#narrow/channel/288089-General/topic/Custom.20formatting/with/516476467
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
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(-)
diff --git a/rust/kernel/fmt.rs b/rust/kernel/fmt.rs
index 0306e8388968..84d634201d90 100644
--- a/rust/kernel/fmt.rs
+++ b/rust/kernel/fmt.rs
@@ -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},
+);
diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs
index 198d09a31449..26424ad7e989 100644
--- a/rust/kernel/prelude.rs
+++ b/rust/kernel/prelude.rs
@@ -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};
diff --git a/rust/macros/fmt.rs b/rust/macros/fmt.rs
new file mode 100644
index 000000000000..2f4b9f6e2211
--- /dev/null
+++ b/rust/macros/fmt.rs
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: GPL-2.0
+
+use proc_macro::{Ident, TokenStream, TokenTree};
+use std::collections::BTreeSet;
+
+/// Please see [`crate::fmt`] for documentation.
+pub(crate) fn fmt(input: TokenStream) -> TokenStream {
+ let mut input = input.into_iter();
+
+ let first_opt = input.next();
+ let first_owned_str;
+ let mut names = BTreeSet::new();
+ let first_span = {
+ let Some((mut first_str, first_span)) = (match first_opt.as_ref() {
+ Some(TokenTree::Literal(first_lit)) => {
+ first_owned_str = first_lit.to_string();
+ Some(first_owned_str.as_str()).and_then(|first| {
+ let first = first.strip_prefix('"')?;
+ let first = first.strip_suffix('"')?;
+ Some((first, first_lit.span()))
+ })
+ }
+ _ => None,
+ }) else {
+ return first_opt.into_iter().chain(input).collect();
+ };
+
+ // Parse `identifier`s from the format string.
+ //
+ // See https://doc.rust-lang.org/std/fmt/index.html#syntax.
+ while let Some((_, rest)) = first_str.split_once('{') {
+ first_str = rest;
+ if let Some(rest) = first_str.strip_prefix('{') {
+ first_str = rest;
+ continue;
+ }
+ if let Some((name, rest)) = first_str.split_once('}') {
+ first_str = rest;
+ let name = name.split_once(':').map_or(name, |(name, _)| name);
+ if !name.is_empty() && !name.chars().all(|c| c.is_ascii_digit()) {
+ names.insert(name);
+ }
+ }
+ }
+ first_span
+ };
+
+ let adapter = quote_spanned!(first_span => ::kernel::fmt::Adapter);
+
+ let mut args = TokenStream::from_iter(first_opt);
+ {
+ let mut flush = |args: &mut TokenStream, current: &mut TokenStream| {
+ let current = std::mem::take(current);
+ if !current.is_empty() {
+ let (lhs, rhs) = (|| {
+ let mut current = current.into_iter();
+ let mut acc = TokenStream::new();
+ while let Some(tt) = current.next() {
+ // Split on `=` only once to handle cases like `a = b = c`.
+ if matches!(&tt, TokenTree::Punct(p) if p.as_char() == '=') {
+ names.remove(acc.to_string().as_str());
+ // Include the `=` itself to keep the handling below uniform.
+ acc.extend([tt]);
+ return (Some(acc), current.collect::<TokenStream>());
+ }
+ acc.extend([tt]);
+ }
+ (None, acc)
+ })();
+ args.extend(quote_spanned!(first_span => #lhs #adapter(&#rhs)));
+ }
+ };
+
+ let mut current = TokenStream::new();
+ for tt in input {
+ match &tt {
+ TokenTree::Punct(p) if p.as_char() == ',' => {
+ flush(&mut args, &mut current);
+ &mut args
+ }
+ _ => &mut current,
+ }
+ .extend([tt]);
+ }
+ flush(&mut args, &mut current);
+ }
+
+ for name in names {
+ let name = Ident::new(name, first_span);
+ args.extend(quote_spanned!(first_span => , #name = #adapter(&#name)));
+ }
+
+ quote_spanned!(first_span => ::core::format_args!(#args))
+}
diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs
index fa847cf3a9b5..793f712dbf7c 100644
--- a/rust/macros/lib.rs
+++ b/rust/macros/lib.rs
@@ -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
diff --git a/rust/macros/quote.rs b/rust/macros/quote.rs
index acc140c18653..ddfc21577539 100644
--- a/rust/macros/quote.rs
+++ b/rust/macros/quote.rs
@@ -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),
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* [PATCH v17 11/11] rust: replace `CStr` with `core::ffi::CStr`
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (9 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 10/11] rust: support formatting of foreign types Tamir Duberstein
@ 2025-10-15 19:24 ` Tamir Duberstein
2025-10-18 17:02 ` [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Alice Ryhl
11 siblings, 0 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:24 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, 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.
Link: https://github.com/Rust-for-Linux/linux/commit/faa3cbcca03d0dec8f8e43f1d8d5c0860d98a23f [0]
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
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(-)
diff --git a/drivers/android/binder/stats.rs b/drivers/android/binder/stats.rs
index 10c43679d5c3..037002651941 100644
--- a/drivers/android/binder/stats.rs
+++ b/drivers/android/binder/stats.rs
@@ -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];
diff --git a/rust/ffi.rs b/rust/ffi.rs
index d60aad792af4..f961e9728f59 100644
--- a/rust/ffi.rs
+++ b/rust/ffi.rs
@@ -46,3 +46,5 @@ macro_rules! alias {
}
pub use core::ffi::c_void;
+
+pub use core::ffi::CStr;
diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs
index 1321e6f0b53c..0b13aa60b685 100644
--- a/rust/kernel/device.rs
+++ b/rust/kernel/device.rs
@@ -13,6 +13,7 @@
#[cfg(CONFIG_PRINTK)]
use crate::c_str;
+use crate::str::CStrExt as _;
pub mod property;
diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs
index 1c0e0e241daa..258b12afdcba 100644
--- a/rust/kernel/error.rs
+++ b/rust/kernel/error.rs
@@ -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) })
}
diff --git a/rust/kernel/firmware.rs b/rust/kernel/firmware.rs
index 94e6bb88b903..376e7e77453f 100644
--- a/rust/kernel/firmware.rs
+++ b/rust/kernel/firmware.rs
@@ -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
diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs
index 26424ad7e989..33fa8404c5c6 100644
--- a/rust/kernel/prelude.rs
+++ b/rust/kernel/prelude.rs
@@ -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;
diff --git a/rust/kernel/seq_file.rs b/rust/kernel/seq_file.rs
index 59fbfc2473f8..855e533813a6 100644
--- a/rust/kernel/seq_file.rs
+++ b/rust/kernel/seq_file.rs
@@ -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)]
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 5c74e5f77601..da539e1f29d4 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -10,9 +10,11 @@
};
use core::{
marker::PhantomData,
- ops::{self, Deref, DerefMut, Index},
+ ops::{Deref, DerefMut, Index},
};
+pub use crate::prelude::CStr;
+
/// Byte string without UTF-8 validity guarantee.
#[repr(transparent)]
pub struct BStr([u8]);
@@ -186,58 +188,17 @@ macro_rules! b_str {
// - error[E0379]: functions in trait impls cannot be declared const
#[inline]
pub const fn as_char_ptr_in_const_context(c_str: &CStr) -> *const c_char {
- c_str.0.as_ptr()
+ c_str.as_ptr().cast()
}
-/// Possible errors when using conversion functions in [`CStr`].
-#[derive(Debug, Clone, Copy)]
-pub enum CStrConvertError {
- /// Supplied bytes contain an interior `NUL`.
- InteriorNul,
-
- /// Supplied bytes are not terminated by `NUL`.
- NotNulTerminated,
-}
+mod private {
+ pub trait Sealed {}
-impl From<CStrConvertError> for Error {
- #[inline]
- fn from(_: CStrConvertError) -> Error {
- EINVAL
- }
+ impl Sealed for super::CStr {}
}
-/// A string that is guaranteed to have exactly one `NUL` byte, which is at the
-/// end.
-///
-/// Used for interoperability with kernel APIs that take C strings.
-#[repr(transparent)]
-pub struct CStr([u8]);
-
-impl CStr {
- /// Returns the length of this string excluding `NUL`.
- #[inline]
- pub const fn len(&self) -> usize {
- self.len_with_nul() - 1
- }
-
- /// Returns the length of this string with `NUL`.
- #[inline]
- pub const fn len_with_nul(&self) -> usize {
- if self.0.is_empty() {
- // SAFETY: This is one of the invariant of `CStr`.
- // We add a `unreachable_unchecked` here to hint the optimizer that
- // the value returned from this function is non-zero.
- unsafe { core::hint::unreachable_unchecked() };
- }
- self.0.len()
- }
-
- /// Returns `true` if the string only includes `NUL`.
- #[inline]
- pub const fn is_empty(&self) -> bool {
- self.len() == 0
- }
-
+/// Extensions to [`CStr`].
+pub trait CStrExt: private::Sealed {
/// Wraps a raw C string pointer.
///
/// # Safety
@@ -245,54 +206,9 @@ pub const fn is_empty(&self) -> bool {
/// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must
/// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr`
/// must not be mutated.
- #[inline]
- pub unsafe fn from_char_ptr<'a>(ptr: *const c_char) -> &'a Self {
- // SAFETY: The safety precondition guarantees `ptr` is a valid pointer
- // to a `NUL`-terminated C string.
- let len = unsafe { bindings::strlen(ptr) } + 1;
- // SAFETY: Lifetime guaranteed by the safety precondition.
- let bytes = unsafe { core::slice::from_raw_parts(ptr.cast(), len) };
- // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`.
- // As we have added 1 to `len`, the last byte is known to be `NUL`.
- unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
- }
-
- /// Creates a [`CStr`] from a `[u8]`.
- ///
- /// The provided slice must be `NUL`-terminated, does not contain any
- /// interior `NUL` bytes.
- pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
- if bytes.is_empty() {
- return Err(CStrConvertError::NotNulTerminated);
- }
- if bytes[bytes.len() - 1] != 0 {
- return Err(CStrConvertError::NotNulTerminated);
- }
- let mut i = 0;
- // `i + 1 < bytes.len()` allows LLVM to optimize away bounds checking,
- // while it couldn't optimize away bounds checks for `i < bytes.len() - 1`.
- while i + 1 < bytes.len() {
- if bytes[i] == 0 {
- return Err(CStrConvertError::InteriorNul);
- }
- i += 1;
- }
- // SAFETY: We just checked that all properties hold.
- Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
- }
-
- /// Creates a [`CStr`] from a `[u8]` without performing any additional
- /// checks.
- ///
- /// # Safety
- ///
- /// `bytes` *must* end with a `NUL` byte, and should only have a single
- /// `NUL` byte (or the string will be truncated).
- #[inline]
- pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
- // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
- unsafe { core::mem::transmute(bytes) }
- }
+ // This function exists to paper over the fact that `CStr::from_ptr` takes a `*const
+ // core::ffi::c_char` rather than a `*const crate::ffi::c_char`.
+ unsafe fn from_char_ptr<'a>(ptr: *const c_char) -> &'a Self;
/// Creates a mutable [`CStr`] from a `[u8]` without performing any
/// additional checks.
@@ -301,99 +217,16 @@ pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError
///
/// `bytes` *must* end with a `NUL` byte, and should only have a single
/// `NUL` byte (or the string will be truncated).
- #[inline]
- pub unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut CStr {
- // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
- unsafe { &mut *(core::ptr::from_mut(bytes) as *mut CStr) }
- }
+ unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut Self;
/// Returns a C pointer to the string.
- ///
- /// Using this function in a const context is deprecated in favor of
- /// [`as_char_ptr_in_const_context`] in preparation for replacing `CStr` with `core::ffi::CStr`
- /// which does not have this method.
- #[inline]
- pub const fn as_char_ptr(&self) -> *const c_char {
- as_char_ptr_in_const_context(self)
- }
-
- /// Convert the string to a byte slice without the trailing `NUL` byte.
- #[inline]
- pub fn to_bytes(&self) -> &[u8] {
- &self.0[..self.len()]
- }
-
- /// Convert the string to a byte slice without the trailing `NUL` byte.
- ///
- /// This function is deprecated in favor of [`Self::to_bytes`] in preparation for replacing
- /// `CStr` with `core::ffi::CStr` which does not have this method.
- #[inline]
- pub fn as_bytes(&self) -> &[u8] {
- self.to_bytes()
- }
-
- /// Convert the string to a byte slice containing the trailing `NUL` byte.
- #[inline]
- pub const fn to_bytes_with_nul(&self) -> &[u8] {
- &self.0
- }
-
- /// Convert the string to a byte slice containing the trailing `NUL` byte.
- ///
- /// This function is deprecated in favor of [`Self::to_bytes_with_nul`] in preparation for
- /// replacing `CStr` with `core::ffi::CStr` which does not have this method.
- #[inline]
- pub const fn as_bytes_with_nul(&self) -> &[u8] {
- self.to_bytes_with_nul()
- }
-
- /// Yields a [`&str`] slice if the [`CStr`] contains valid UTF-8.
- ///
- /// If the contents of the [`CStr`] are valid UTF-8 data, this
- /// function will return the corresponding [`&str`] slice. Otherwise,
- /// it will return an error with details of where UTF-8 validation failed.
- ///
- /// # Examples
- ///
- /// ```
- /// # use kernel::str::CStr;
- /// let cstr = CStr::from_bytes_with_nul(b"foo\0")?;
- /// assert_eq!(cstr.to_str(), Ok("foo"));
- /// # Ok::<(), kernel::error::Error>(())
- /// ```
- #[inline]
- pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
- core::str::from_utf8(self.as_bytes())
- }
-
- /// Unsafely convert this [`CStr`] into a [`&str`], without checking for
- /// valid UTF-8.
- ///
- /// # Safety
- ///
- /// The contents must be valid UTF-8.
- ///
- /// # Examples
- ///
- /// ```
- /// # use kernel::c_str;
- /// # use kernel::str::CStr;
- /// let bar = c_str!("ツ");
- /// // SAFETY: String literals are guaranteed to be valid UTF-8
- /// // by the Rust compiler.
- /// assert_eq!(unsafe { bar.as_str_unchecked() }, "ツ");
- /// ```
- #[inline]
- pub unsafe fn as_str_unchecked(&self) -> &str {
- // SAFETY: TODO.
- unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
- }
+ // This function exists to paper over the fact that `CStr::as_ptr` returns a `*const
+ // core::ffi::c_char` rather than a `*const crate::ffi::c_char`.
+ fn as_char_ptr(&self) -> *const c_char;
/// Convert this [`CStr`] into a [`CString`] by allocating memory and
/// copying over the string data.
- pub fn to_cstring(&self) -> Result<CString, AllocError> {
- CString::try_from(self)
- }
+ fn to_cstring(&self) -> Result<CString, AllocError>;
/// Converts this [`CStr`] to its ASCII lower case equivalent in-place.
///
@@ -404,11 +237,7 @@ pub fn to_cstring(&self) -> Result<CString, AllocError> {
/// [`to_ascii_lowercase()`].
///
/// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase
- pub fn make_ascii_lowercase(&mut self) {
- // INVARIANT: This doesn't introduce or remove NUL bytes in the C
- // string.
- self.0.make_ascii_lowercase();
- }
+ fn make_ascii_lowercase(&mut self);
/// Converts this [`CStr`] to its ASCII upper case equivalent in-place.
///
@@ -419,11 +248,7 @@ pub fn make_ascii_lowercase(&mut self) {
/// [`to_ascii_uppercase()`].
///
/// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase
- pub fn make_ascii_uppercase(&mut self) {
- // INVARIANT: This doesn't introduce or remove NUL bytes in the C
- // string.
- self.0.make_ascii_uppercase();
- }
+ fn make_ascii_uppercase(&mut self);
/// Returns a copy of this [`CString`] where each character is mapped to its
/// ASCII lower case equivalent.
@@ -434,13 +259,7 @@ pub fn make_ascii_uppercase(&mut self) {
/// To lowercase the value in-place, use [`make_ascii_lowercase`].
///
/// [`make_ascii_lowercase`]: str::make_ascii_lowercase
- pub fn to_ascii_lowercase(&self) -> Result<CString, AllocError> {
- let mut s = self.to_cstring()?;
-
- s.make_ascii_lowercase();
-
- Ok(s)
- }
+ fn to_ascii_lowercase(&self) -> Result<CString, AllocError>;
/// Returns a copy of this [`CString`] where each character is mapped to its
/// ASCII upper case equivalent.
@@ -451,13 +270,7 @@ pub fn to_ascii_lowercase(&self) -> Result<CString, AllocError> {
/// To uppercase the value in-place, use [`make_ascii_uppercase`].
///
/// [`make_ascii_uppercase`]: str::make_ascii_uppercase
- pub fn to_ascii_uppercase(&self) -> Result<CString, AllocError> {
- let mut s = self.to_cstring()?;
-
- s.make_ascii_uppercase();
-
- Ok(s)
- }
+ fn to_ascii_uppercase(&self) -> Result<CString, AllocError>;
}
impl fmt::Display for CStr {
@@ -490,98 +303,75 @@ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
}
}
-impl fmt::Debug for CStr {
- /// Formats printable ASCII characters with a double quote on either end, escaping the rest.
- ///
- /// ```
- /// # use kernel::c_str;
- /// # use kernel::prelude::fmt;
- /// # use kernel::str::CStr;
- /// # use kernel::str::CString;
- /// let penguin = c_str!("🐧");
- /// let s = CString::try_from_fmt(fmt!("{penguin:?}"))?;
- /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes());
- ///
- /// // Embedded double quotes are escaped.
- /// let ascii = c_str!("so \"cool\"");
- /// let s = CString::try_from_fmt(fmt!("{ascii:?}"))?;
- /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes());
- /// # Ok::<(), kernel::error::Error>(())
- /// ```
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- f.write_str("\"")?;
- for &c in self.as_bytes() {
- match c {
- // Printable characters.
- b'\"' => f.write_str("\\\"")?,
- 0x20..=0x7e => f.write_char(c as char)?,
- _ => write!(f, "\\x{c:02x}")?,
- }
- }
- f.write_str("\"")
- }
+/// Converts a mutable C string to a mutable byte slice.
+///
+/// # Safety
+///
+/// The caller must ensure that the slice ends in a NUL byte and contains no other NUL bytes before
+/// the borrow ends and the underlying [`CStr`] is used.
+unsafe fn to_bytes_mut(s: &mut CStr) -> &mut [u8] {
+ // SAFETY: the cast from `&CStr` to `&[u8]` is safe since `CStr` has the same layout as `&[u8]`
+ // (this is technically not guaranteed, but we rely on it here). The pointer dereference is
+ // safe since it comes from a mutable reference which is guaranteed to be valid for writes.
+ unsafe { &mut *(core::ptr::from_mut(s) as *mut [u8]) }
}
-impl AsRef<BStr> for CStr {
+impl CStrExt for CStr {
#[inline]
- fn as_ref(&self) -> &BStr {
- BStr::from_bytes(self.as_bytes())
+ unsafe fn from_char_ptr<'a>(ptr: *const c_char) -> &'a Self {
+ // SAFETY: The safety preconditions are the same as for `CStr::from_ptr`.
+ unsafe { CStr::from_ptr(ptr.cast()) }
}
-}
-impl Deref for CStr {
- type Target = BStr;
+ #[inline]
+ unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut Self {
+ // SAFETY: the cast from `&[u8]` to `&CStr` is safe since the properties of `bytes` are
+ // guaranteed by the safety precondition and `CStr` has the same layout as `&[u8]` (this is
+ // technically not guaranteed, but we rely on it here). The pointer dereference is safe
+ // since it comes from a mutable reference which is guaranteed to be valid for writes.
+ unsafe { &mut *(core::ptr::from_mut(bytes) as *mut CStr) }
+ }
#[inline]
- fn deref(&self) -> &Self::Target {
- self.as_ref()
+ fn as_char_ptr(&self) -> *const c_char {
+ self.as_ptr().cast()
+ }
+
+ fn to_cstring(&self) -> Result<CString, AllocError> {
+ CString::try_from(self)
}
-}
-impl Index<ops::RangeFrom<usize>> for CStr {
- type Output = CStr;
+ fn make_ascii_lowercase(&mut self) {
+ // SAFETY: This doesn't introduce or remove NUL bytes in the C string.
+ unsafe { to_bytes_mut(self) }.make_ascii_lowercase();
+ }
- #[inline]
- fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
- // Delegate bounds checking to slice.
- // Assign to _ to mute clippy's unnecessary operation warning.
- let _ = &self.as_bytes()[index.start..];
- // SAFETY: We just checked the bounds.
- unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
+ fn make_ascii_uppercase(&mut self) {
+ // SAFETY: This doesn't introduce or remove NUL bytes in the C string.
+ unsafe { to_bytes_mut(self) }.make_ascii_uppercase();
}
-}
-impl Index<ops::RangeFull> for CStr {
- type Output = CStr;
+ fn to_ascii_lowercase(&self) -> Result<CString, AllocError> {
+ let mut s = self.to_cstring()?;
- #[inline]
- fn index(&self, _index: ops::RangeFull) -> &Self::Output {
- self
+ s.make_ascii_lowercase();
+
+ Ok(s)
}
-}
-mod private {
- use core::ops;
+ fn to_ascii_uppercase(&self) -> Result<CString, AllocError> {
+ let mut s = self.to_cstring()?;
- // Marker trait for index types that can be forward to `BStr`.
- pub trait CStrIndex {}
+ s.make_ascii_uppercase();
- impl CStrIndex for usize {}
- impl CStrIndex for ops::Range<usize> {}
- impl CStrIndex for ops::RangeInclusive<usize> {}
- impl CStrIndex for ops::RangeToInclusive<usize> {}
+ Ok(s)
+ }
}
-impl<Idx> Index<Idx> for CStr
-where
- Idx: private::CStrIndex,
- BStr: Index<Idx>,
-{
- type Output = <BStr as Index<Idx>>::Output;
-
+impl AsRef<BStr> for CStr {
#[inline]
- fn index(&self, index: Idx) -> &Self::Output {
- &self.as_ref()[index]
+ fn as_ref(&self) -> &BStr {
+ BStr::from_bytes(self.to_bytes())
}
}
@@ -612,6 +402,13 @@ macro_rules! c_str {
mod tests {
use super::*;
+ impl From<core::ffi::FromBytesWithNulError> for Error {
+ #[inline]
+ fn from(_: core::ffi::FromBytesWithNulError) -> Error {
+ EINVAL
+ }
+ }
+
macro_rules! format {
($($f:tt)*) => ({
CString::try_from_fmt(fmt!($($f)*))?.to_str()?
@@ -634,40 +431,28 @@ macro_rules! format {
#[test]
fn test_cstr_to_str() -> Result {
- let good_bytes = b"\xf0\x9f\xa6\x80\0";
- let checked_cstr = CStr::from_bytes_with_nul(good_bytes)?;
- let checked_str = checked_cstr.to_str()?;
+ let cstr = c"\xf0\x9f\xa6\x80";
+ let checked_str = cstr.to_str()?;
assert_eq!(checked_str, "🦀");
Ok(())
}
#[test]
fn test_cstr_to_str_invalid_utf8() -> Result {
- let bad_bytes = b"\xc3\x28\0";
- let checked_cstr = CStr::from_bytes_with_nul(bad_bytes)?;
- assert!(checked_cstr.to_str().is_err());
- Ok(())
- }
-
- #[test]
- fn test_cstr_as_str_unchecked() -> Result {
- let good_bytes = b"\xf0\x9f\x90\xA7\0";
- let checked_cstr = CStr::from_bytes_with_nul(good_bytes)?;
- // SAFETY: The contents come from a string literal which contains valid UTF-8.
- let unchecked_str = unsafe { checked_cstr.as_str_unchecked() };
- assert_eq!(unchecked_str, "🐧");
+ let cstr = c"\xc3\x28";
+ assert!(cstr.to_str().is_err());
Ok(())
}
#[test]
fn test_cstr_display() -> Result {
- let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0")?;
+ let hello_world = c"hello, world!";
assert_eq!(format!("{hello_world}"), "hello, world!");
- let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0")?;
+ let non_printables = c"\x01\x09\x0a";
assert_eq!(format!("{non_printables}"), "\\x01\\x09\\x0a");
- let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0")?;
+ let non_ascii = c"d\xe9j\xe0 vu";
assert_eq!(format!("{non_ascii}"), "d\\xe9j\\xe0 vu");
- let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0")?;
+ let good_bytes = c"\xf0\x9f\xa6\x80";
assert_eq!(format!("{good_bytes}"), "\\xf0\\x9f\\xa6\\x80");
Ok(())
}
@@ -686,13 +471,13 @@ fn test_cstr_display_all_bytes() -> Result {
#[test]
fn test_cstr_debug() -> Result {
- let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0")?;
+ let hello_world = c"hello, world!";
assert_eq!(format!("{hello_world:?}"), "\"hello, world!\"");
- let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0")?;
- assert_eq!(format!("{non_printables:?}"), "\"\\x01\\x09\\x0a\"");
- let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0")?;
+ let non_printables = c"\x01\x09\x0a";
+ assert_eq!(format!("{non_printables:?}"), "\"\\x01\\t\\n\"");
+ let non_ascii = c"d\xe9j\xe0 vu";
assert_eq!(format!("{non_ascii:?}"), "\"d\\xe9j\\xe0 vu\"");
- let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0")?;
+ let good_bytes = c"\xf0\x9f\xa6\x80";
assert_eq!(format!("{good_bytes:?}"), "\"\\xf0\\x9f\\xa6\\x80\"");
Ok(())
}
diff --git a/rust/kernel/sync/condvar.rs b/rust/kernel/sync/condvar.rs
index c6ec64295c9f..a24e25a690ee 100644
--- a/rust/kernel/sync/condvar.rs
+++ b/rust/kernel/sync/condvar.rs
@@ -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,
},
diff --git a/rust/kernel/sync/lock.rs b/rust/kernel/sync/lock.rs
index 27202beef90c..5d7991e6d373 100644
--- a/rust/kernel/sync/lock.rs
+++ b/rust/kernel/sync/lock.rs
@@ -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};
diff --git a/rust/kernel/sync/lock/global.rs b/rust/kernel/sync/lock/global.rs
index d65f94b5caf2..79d0ef7fda86 100644
--- a/rust/kernel/sync/lock/global.rs
+++ b/rust/kernel/sync/lock/global.rs
@@ -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,
--
2.51.0
^ permalink raw reply related [flat|nested] 26+ messages in thread
* Re: [PATCH v17 06/11] rust: alloc: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 06/11] rust: alloc: " Tamir Duberstein
@ 2025-10-15 19:29 ` Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:47 ` Danilo Krummrich
2 siblings, 0 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-15 19:29 UTC (permalink / raw)
To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 3:25 PM Tamir Duberstein <tamird@gmail.com> wrote:
>
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> ---
> rust/kernel/alloc/kvec/errors.rs | 14 +++++++-------
> 1 file changed, 7 insertions(+), 7 deletions(-)
>
> diff --git a/rust/kernel/alloc/kvec/errors.rs b/rust/kernel/alloc/kvec/errors.rs
> index 21a920a4b09b..e7de5049ee47 100644
> --- a/rust/kernel/alloc/kvec/errors.rs
> +++ b/rust/kernel/alloc/kvec/errors.rs
> @@ -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.
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 02/11] rust_binder: remove trailing comma
2025-10-15 19:24 ` [PATCH v17 02/11] rust_binder: remove trailing comma Tamir Duberstein
@ 2025-10-15 19:30 ` Alice Ryhl
0 siblings, 0 replies; 26+ messages in thread
From: Alice Ryhl @ 2025-10-15 19:30 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 03:24:32PM -0400, Tamir Duberstein wrote:
> 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.
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 03/11] rust_binder: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 03/11] rust_binder: use `kernel::fmt` Tamir Duberstein
@ 2025-10-15 19:31 ` Alice Ryhl
0 siblings, 0 replies; 26+ messages in thread
From: Alice Ryhl @ 2025-10-15 19:31 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 03:24:33PM -0400, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names
2025-10-15 19:24 ` [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names Tamir Duberstein
@ 2025-10-15 19:31 ` Alice Ryhl
0 siblings, 0 replies; 26+ messages in thread
From: Alice Ryhl @ 2025-10-15 19:31 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 03:24:34PM -0400, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 06/11] rust: alloc: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 06/11] rust: alloc: " Tamir Duberstein
2025-10-15 19:29 ` Tamir Duberstein
@ 2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:47 ` Danilo Krummrich
2 siblings, 0 replies; 26+ messages in thread
From: Alice Ryhl @ 2025-10-15 19:31 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 03:24:36PM -0400, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 09/11] rust: remove spurious `use core::fmt::Debug`
2025-10-15 19:24 ` [PATCH v17 09/11] rust: remove spurious `use core::fmt::Debug` Tamir Duberstein
@ 2025-10-15 19:33 ` Alice Ryhl
0 siblings, 0 replies; 26+ messages in thread
From: Alice Ryhl @ 2025-10-15 19:33 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 03:24:39PM -0400, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 07/11] rust: debugfs: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 07/11] rust: debugfs: " Tamir Duberstein
@ 2025-10-15 19:39 ` Matthew Maurer
2025-10-15 19:45 ` Danilo Krummrich
1 sibling, 0 replies; 26+ messages in thread
From: Matthew Maurer @ 2025-10-15 19:39 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 12:27 PM Tamir Duberstein <tamird@gmail.com> wrote:
>
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> ---
> 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(-)
>
Reviewed-by: Matthew Maurer <mmaurer@google.com>
On Wed, Oct 15, 2025 at 12:27 PM Tamir Duberstein <tamird@gmail.com> wrote:
>
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> ---
> 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(-)
>
> diff --git a/rust/kernel/debugfs.rs b/rust/kernel/debugfs.rs
> index 381c23b3dd83..8c35d032acfe 100644
> --- a/rust/kernel/debugfs.rs
> +++ b/rust/kernel/debugfs.rs
> @@ -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)]
> diff --git a/rust/kernel/debugfs/callback_adapters.rs b/rust/kernel/debugfs/callback_adapters.rs
> index 6c024230f676..a260d8dee051 100644
> --- a/rust/kernel/debugfs/callback_adapters.rs
> +++ b/rust/kernel/debugfs/callback_adapters.rs
> @@ -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)
> diff --git a/rust/kernel/debugfs/file_ops.rs b/rust/kernel/debugfs/file_ops.rs
> index 50fead17b6f3..9ad5e3fa6f69 100644
> --- a/rust/kernel/debugfs/file_ops.rs
> +++ b/rust/kernel/debugfs/file_ops.rs
> @@ -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)
> }
> }
> diff --git a/rust/kernel/debugfs/traits.rs b/rust/kernel/debugfs/traits.rs
> index ab009eb254b3..ad33bfbc7669 100644
> --- a/rust/kernel/debugfs/traits.rs
> +++ b/rust/kernel/debugfs/traits.rs
> @@ -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
>
>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 07/11] rust: debugfs: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 07/11] rust: debugfs: " Tamir Duberstein
2025-10-15 19:39 ` Matthew Maurer
@ 2025-10-15 19:45 ` Danilo Krummrich
1 sibling, 0 replies; 26+ messages in thread
From: Danilo Krummrich @ 2025-10-15 19:45 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Greg Kroah-Hartman, Rafael J. Wysocki,
Luis Chamberlain, Russ Weight, Peter Zijlstra, Ingo Molnar,
Will Deacon, Waiman Long, Nathan Chancellor, Nick Desaulniers,
Bill Wendling, Justin Stitt, Christian Brauner, Alexander Viro,
Jan Kara, Arve Hjønnevåg, Todd Kjos, Martijn Coenen,
Joel Fernandes, Carlos Llamas, Suren Baghdasaryan, Jens Axboe,
Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On 10/15/25 9:24 PM, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 08/11] rust: pci: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 08/11] rust: pci: " Tamir Duberstein
@ 2025-10-15 19:46 ` Danilo Krummrich
0 siblings, 0 replies; 26+ messages in thread
From: Danilo Krummrich @ 2025-10-15 19:46 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Greg Kroah-Hartman, Rafael J. Wysocki,
Luis Chamberlain, Russ Weight, Peter Zijlstra, Ingo Molnar,
Will Deacon, Waiman Long, Nathan Chancellor, Nick Desaulniers,
Bill Wendling, Justin Stitt, Christian Brauner, Alexander Viro,
Jan Kara, Arve Hjønnevåg, Todd Kjos, Martijn Coenen,
Joel Fernandes, Carlos Llamas, Suren Baghdasaryan, Jens Axboe,
Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On 10/15/25 9:24 PM, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 06/11] rust: alloc: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 06/11] rust: alloc: " Tamir Duberstein
2025-10-15 19:29 ` Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
@ 2025-10-15 19:47 ` Danilo Krummrich
2 siblings, 0 replies; 26+ messages in thread
From: Danilo Krummrich @ 2025-10-15 19:47 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
Trevor Gross, Greg Kroah-Hartman, Rafael J. Wysocki,
Luis Chamberlain, Russ Weight, Peter Zijlstra, Ingo Molnar,
Will Deacon, Waiman Long, Nathan Chancellor, Nick Desaulniers,
Bill Wendling, Justin Stitt, Christian Brauner, Alexander Viro,
Jan Kara, Arve Hjønnevåg, Todd Kjos, Martijn Coenen,
Joel Fernandes, Carlos Llamas, Suren Baghdasaryan, Jens Axboe,
Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On 10/15/25 9:24 PM, Tamir Duberstein wrote:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 05/11] rnull: use `kernel::fmt`
2025-10-15 19:24 ` [PATCH v17 05/11] rnull: use `kernel::fmt` Tamir Duberstein
@ 2025-10-16 8:42 ` Andreas Hindborg
0 siblings, 0 replies; 26+ messages in thread
From: Andreas Hindborg @ 2025-10-16 8:42 UTC (permalink / raw)
To: Tamir Duberstein, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Alice Ryhl, Trevor Gross,
Danilo Krummrich, Greg Kroah-Hartman, Rafael J. Wysocki,
Luis Chamberlain, Russ Weight, Peter Zijlstra, Ingo Molnar,
Will Deacon, Waiman Long, Nathan Chancellor, Nick Desaulniers,
Bill Wendling, Justin Stitt, Christian Brauner, Alexander Viro,
Jan Kara, Arve Hjønnevåg, Todd Kjos, Martijn Coenen,
Joel Fernandes, Carlos Llamas, Suren Baghdasaryan, Jens Axboe,
Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński
Cc: rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci, Tamir Duberstein
"Tamir Duberstein" <tamird@gmail.com> writes:
> 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").
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Acked-by: Andreas Hindborg <a.hindborg@kernel.org>
Best regards,
Andreas Hindborg
^ permalink raw reply [flat|nested] 26+ messages in thread
* Re: [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
` (10 preceding siblings ...)
2025-10-15 19:24 ` [PATCH v17 11/11] rust: replace `CStr` with `core::ffi::CStr` Tamir Duberstein
@ 2025-10-18 17:02 ` Alice Ryhl
2025-10-18 17:09 ` Alice Ryhl
11 siblings, 1 reply; 26+ messages in thread
From: Alice Ryhl @ 2025-10-18 17:02 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Wed, Oct 15, 2025 at 03:24:30PM -0400, Tamir Duberstein wrote:
> 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-by`s:
> - 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?
>
> Link: https://lore.kernel.org/rust-for-linux/20240819153656.28807-2-vadorovsky@protonmail.com/t/#u [0]
> Closes: https://github.com/Rust-for-Linux/linux/issues/1075
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
You need a few more changes:
diff --git a/rust/kernel/clk.rs b/rust/kernel/clk.rs
index 1e6c8c42fb3a..c1cfaeaa36a2 100644
--- a/rust/kernel/clk.rs
+++ b/rust/kernel/clk.rs
@@ -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.
//
diff --git a/rust/kernel/configfs.rs b/rust/kernel/configfs.rs
index 10f1547ca9f1..466fb7f40762 100644
--- a/rust/kernel/configfs.rs
+++ b/rust/kernel/configfs.rs
@@ -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(),
)
};
diff --git a/rust/kernel/debugfs/entry.rs b/rust/kernel/debugfs/entry.rs
index f99402cd3ba0..5de0ebc27198 100644
--- a/rust/kernel/debugfs/entry.rs
+++ b/rust/kernel/debugfs/entry.rs
@@ -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;
diff --git a/rust/kernel/regulator.rs b/rust/kernel/regulator.rs
index b55a201e5029..65a4eb096cae 100644
--- a/rust/kernel/regulator.rs
+++ b/rust/kernel/regulator.rs
@@ -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.
--
^ permalink raw reply related [flat|nested] 26+ messages in thread
* Re: [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr
2025-10-18 17:02 ` [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Alice Ryhl
@ 2025-10-18 17:09 ` Alice Ryhl
2025-10-20 12:00 ` Tamir Duberstein
0 siblings, 1 reply; 26+ messages in thread
From: Alice Ryhl @ 2025-10-18 17:09 UTC (permalink / raw)
To: Tamir Duberstein
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Sat, Oct 18, 2025 at 05:02:39PM +0000, Alice Ryhl wrote:
> On Wed, Oct 15, 2025 at 03:24:30PM -0400, Tamir Duberstein wrote:
> > 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-by`s:
> > - 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?
> >
> > Link: https://lore.kernel.org/rust-for-linux/20240819153656.28807-2-vadorovsky@protonmail.com/t/#u [0]
> > Closes: https://github.com/Rust-for-Linux/linux/issues/1075
> >
> > Signed-off-by: Tamir Duberstein <tamird@gmail.com>
>
> You need a few more changes:
One more:
diff --git a/rust/kernel/drm/ioctl.rs b/rust/kernel/drm/ioctl.rs
index 69efbdb4c85a..5489961a62ca 100644
--- a/rust/kernel/drm/ioctl.rs
+++ b/rust/kernel/drm/ioctl.rs
@@ -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
^ permalink raw reply related [flat|nested] 26+ messages in thread
* Re: [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr
2025-10-18 17:09 ` Alice Ryhl
@ 2025-10-20 12:00 ` Tamir Duberstein
0 siblings, 0 replies; 26+ messages in thread
From: Tamir Duberstein @ 2025-10-20 12:00 UTC (permalink / raw)
To: Alice Ryhl
Cc: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
Björn Roy Baron, Benno Lossin, Andreas Hindborg,
Trevor Gross, Danilo Krummrich, Greg Kroah-Hartman,
Rafael J. Wysocki, Luis Chamberlain, Russ Weight, Peter Zijlstra,
Ingo Molnar, Will Deacon, Waiman Long, Nathan Chancellor,
Nick Desaulniers, Bill Wendling, Justin Stitt, Christian Brauner,
Alexander Viro, Jan Kara, Arve Hjønnevåg, Todd Kjos,
Martijn Coenen, Joel Fernandes, Carlos Llamas, Suren Baghdasaryan,
Jens Axboe, Lorenzo Stoakes, Vlastimil Babka, Liam R. Howlett,
Uladzislau Rezki, Bjorn Helgaas, Krzysztof Wilczyński,
rust-for-linux, linux-kernel, llvm, linux-fsdevel, linux-block,
linux-pci
On Sat, Oct 18, 2025 at 1:09 PM Alice Ryhl <aliceryhl@google.com> wrote:
>
> On Sat, Oct 18, 2025 at 05:02:39PM +0000, Alice Ryhl wrote:
> > On Wed, Oct 15, 2025 at 03:24:30PM -0400, Tamir Duberstein wrote:
> > > 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-by`s:
> > > - 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?
> > >
> > > Link: https://lore.kernel.org/rust-for-linux/20240819153656.28807-2-vadorovsky@protonmail.com/t/#u [0]
> > > Closes: https://github.com/Rust-for-Linux/linux/issues/1075
> > >
> > > Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> >
> > You need a few more changes:
>
> One more:
>
> diff --git a/rust/kernel/drm/ioctl.rs b/rust/kernel/drm/ioctl.rs
> index 69efbdb4c85a..5489961a62ca 100644
> --- a/rust/kernel/drm/ioctl.rs
> +++ b/rust/kernel/drm/ioctl.rs
> @@ -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]`.
^ permalink raw reply [flat|nested] 26+ messages in thread
end of thread, other threads:[~2025-10-20 12:01 UTC | newest]
Thread overview: 26+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-10-15 19:24 [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 01/11] samples: rust: platform: remove trailing commas Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 02/11] rust_binder: remove trailing comma Tamir Duberstein
2025-10-15 19:30 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 03/11] rust_binder: use `kernel::fmt` Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 04/11] rust_binder: use `core::ffi::CStr` method names Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 05/11] rnull: use `kernel::fmt` Tamir Duberstein
2025-10-16 8:42 ` Andreas Hindborg
2025-10-15 19:24 ` [PATCH v17 06/11] rust: alloc: " Tamir Duberstein
2025-10-15 19:29 ` Tamir Duberstein
2025-10-15 19:31 ` Alice Ryhl
2025-10-15 19:47 ` Danilo Krummrich
2025-10-15 19:24 ` [PATCH v17 07/11] rust: debugfs: " Tamir Duberstein
2025-10-15 19:39 ` Matthew Maurer
2025-10-15 19:45 ` Danilo Krummrich
2025-10-15 19:24 ` [PATCH v17 08/11] rust: pci: " Tamir Duberstein
2025-10-15 19:46 ` Danilo Krummrich
2025-10-15 19:24 ` [PATCH v17 09/11] rust: remove spurious `use core::fmt::Debug` Tamir Duberstein
2025-10-15 19:33 ` Alice Ryhl
2025-10-15 19:24 ` [PATCH v17 10/11] rust: support formatting of foreign types Tamir Duberstein
2025-10-15 19:24 ` [PATCH v17 11/11] rust: replace `CStr` with `core::ffi::CStr` Tamir Duberstein
2025-10-18 17:02 ` [PATCH v17 00/11] rust: replace kernel::str::CStr w/ core::ffi::CStr Alice Ryhl
2025-10-18 17:09 ` Alice Ryhl
2025-10-20 12:00 ` Tamir Duberstein
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).