From 27c7518e7f1ccaaa43eb5f25dc362779d2dc2ccb Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sun, 15 Dec 2024 22:43:53 +0100 Subject: [PATCH 01/31] rust: finish using custom FFI integer types In the last kernel cycle we migrated most of the `core::ffi` cases in commit d072acda4862 ("rust: use custom FFI integer types"): Currently FFI integer types are defined in libcore. This commit creates the `ffi` crate and asks bindgen to use that crate for FFI integer types instead of `core::ffi`. This commit is preparatory and no type changes are made in this commit yet. Finish now the few remaining/new cases so that we perform the actual remapping in the next commit as planned. Acked-by: Jocelyn Falempe # drm Link: https://lore.kernel.org/rust-for-linux/CANiq72m_rg42SvZK=bF2f0yEoBLVA33UBhiAsv8THhVu=G2dPA@mail.gmail.com/ Link: https://lore.kernel.org/all/cc9253fa-9d5f-460b-9841-94948fb6580c@redhat.com/ Signed-off-by: Miguel Ojeda --- drivers/gpu/drm/drm_panic_qr.rs | 2 +- rust/kernel/device.rs | 4 ++-- rust/kernel/miscdevice.rs | 8 ++------ rust/kernel/security.rs | 2 +- rust/kernel/seq_file.rs | 2 +- samples/rust/rust_print_main.rs | 2 +- 6 files changed, 8 insertions(+), 12 deletions(-) diff --git a/drivers/gpu/drm/drm_panic_qr.rs b/drivers/gpu/drm/drm_panic_qr.rs index ef2d490965ba..bcf248f69252 100644 --- a/drivers/gpu/drm/drm_panic_qr.rs +++ b/drivers/gpu/drm/drm_panic_qr.rs @@ -931,7 +931,7 @@ impl QrImage<'_> { /// They must remain valid for the duration of the function call. #[no_mangle] pub unsafe extern "C" fn drm_panic_qr_generate( - url: *const i8, + url: *const kernel::ffi::c_char, data: *mut u8, data_len: usize, data_size: usize, diff --git a/rust/kernel/device.rs b/rust/kernel/device.rs index c926e0c2b852..d5e6a19ff6b7 100644 --- a/rust/kernel/device.rs +++ b/rust/kernel/device.rs @@ -173,10 +173,10 @@ impl Device { #[cfg(CONFIG_PRINTK)] unsafe { bindings::_dev_printk( - klevel as *const _ as *const core::ffi::c_char, + klevel as *const _ as *const crate::ffi::c_char, self.as_raw(), c_str!("%pA").as_char_ptr(), - &msg as *const _ as *const core::ffi::c_void, + &msg as *const _ as *const crate::ffi::c_void, ) }; } diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index 7e2a79b3ae26..fbd761380384 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -11,16 +11,12 @@ use crate::{ bindings, error::{to_result, Error, Result, VTABLE_DEFAULT_ERROR}, + ffi::{c_int, c_long, c_uint, c_ulong}, prelude::*, str::CStr, types::{ForeignOwnable, Opaque}, }; -use core::{ - ffi::{c_int, c_long, c_uint, c_ulong}, - marker::PhantomData, - mem::MaybeUninit, - pin::Pin, -}; +use core::{marker::PhantomData, mem::MaybeUninit, pin::Pin}; /// Options for creating a misc device. #[derive(Copy, Clone)] diff --git a/rust/kernel/security.rs b/rust/kernel/security.rs index 2522868862a1..ea4c58c81703 100644 --- a/rust/kernel/security.rs +++ b/rust/kernel/security.rs @@ -19,7 +19,7 @@ use crate::{ /// successful call to `security_secid_to_secctx`, that has not yet been destroyed by calling /// `security_release_secctx`. pub struct SecurityCtx { - secdata: *mut core::ffi::c_char, + secdata: *mut crate::ffi::c_char, seclen: usize, } diff --git a/rust/kernel/seq_file.rs b/rust/kernel/seq_file.rs index 6ca29d576d02..04947c672979 100644 --- a/rust/kernel/seq_file.rs +++ b/rust/kernel/seq_file.rs @@ -36,7 +36,7 @@ impl SeqFile { bindings::seq_printf( self.inner.get(), c_str!("%pA").as_char_ptr(), - &args as *const _ as *const core::ffi::c_void, + &args as *const _ as *const crate::ffi::c_void, ); } } diff --git a/samples/rust/rust_print_main.rs b/samples/rust/rust_print_main.rs index aed90a6feecf..7935b4772ec6 100644 --- a/samples/rust/rust_print_main.rs +++ b/samples/rust/rust_print_main.rs @@ -83,7 +83,7 @@ impl Drop for RustPrint { } mod trace { - use core::ffi::c_int; + use kernel::ffi::c_int; kernel::declare_trace! { /// # Safety From 1bae8729e50a900f41e9a1c17ae81113e4cf62b8 Mon Sep 17 00:00:00 2001 From: Gary Guo Date: Fri, 13 Sep 2024 22:29:24 +0100 Subject: [PATCH 02/31] rust: map `long` to `isize` and `char` to `u8` The following FFI types are replaced compared to `core::ffi`: 1. `char` type is now always mapped to `u8`, since kernel uses `-funsigned-char` on the C code. `core::ffi` maps it to platform default ABI, which can be either signed or unsigned. 2. `long` is now always mapped to `isize`. It's very common in the kernel to use `long` to represent a pointer-sized integer, and in fact `intptr_t` is a typedef of `long` in the kernel. Enforce this mapping rather than mapping to `i32/i64` depending on platform can save us a lot of unnecessary casts. Signed-off-by: Gary Guo Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20240913213041.395655-5-gary@garyguo.net [ Moved `uaccess` changes from the next commit, since they were irrefutable patterns that Rust >= 1.82.0 warns about. Reworded slightly and reformatted a few documentation comments. Rebased on top of `rust-next`. Added the removal of two casts to avoid Clippy warnings. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/ffi.rs | 37 ++++++++++++++++++++++++++++++++++++- rust/kernel/error.rs | 5 +---- rust/kernel/firmware.rs | 2 +- rust/kernel/miscdevice.rs | 4 ++-- rust/kernel/uaccess.rs | 27 +++++++-------------------- 5 files changed, 47 insertions(+), 28 deletions(-) diff --git a/rust/ffi.rs b/rust/ffi.rs index be153c4d551b..584f75b49862 100644 --- a/rust/ffi.rs +++ b/rust/ffi.rs @@ -10,4 +10,39 @@ #![no_std] -pub use core::ffi::*; +macro_rules! alias { + ($($name:ident = $ty:ty;)*) => {$( + #[allow(non_camel_case_types, missing_docs)] + pub type $name = $ty; + + // Check size compatibility with `core`. + const _: () = assert!( + core::mem::size_of::<$name>() == core::mem::size_of::() + ); + )*} +} + +alias! { + // `core::ffi::c_char` is either `i8` or `u8` depending on architecture. In the kernel, we use + // `-funsigned-char` so it's always mapped to `u8`. + c_char = u8; + + c_schar = i8; + c_uchar = u8; + + c_short = i16; + c_ushort = u16; + + c_int = i32; + c_uint = u32; + + // In the kernel, `intptr_t` is defined to be `long` in all platforms, so we can map the type to + // `isize`. + c_long = isize; + c_ulong = usize; + + c_longlong = i64; + c_ulonglong = u64; +} + +pub use core::ffi::c_void; diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 52c502432447..5fece574ec02 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -153,11 +153,8 @@ impl Error { /// Returns the error encoded as a pointer. pub fn to_ptr(self) -> *mut T { - #[cfg_attr(target_pointer_width = "32", allow(clippy::useless_conversion))] // SAFETY: `self.0` is a valid error due to its invariant. - unsafe { - bindings::ERR_PTR(self.0.get().into()) as *mut _ - } + unsafe { bindings::ERR_PTR(self.0.get() as _) as *mut _ } } /// Returns a string representing the error, if one exists. diff --git a/rust/kernel/firmware.rs b/rust/kernel/firmware.rs index 13a374a5cdb7..c5162fdc95ff 100644 --- a/rust/kernel/firmware.rs +++ b/rust/kernel/firmware.rs @@ -12,7 +12,7 @@ use core::ptr::NonNull; /// One of the following: `bindings::request_firmware`, `bindings::firmware_request_nowarn`, /// `bindings::firmware_request_platform`, `bindings::request_firmware_direct`. struct FwFunc( - unsafe extern "C" fn(*mut *const bindings::firmware, *const i8, *mut bindings::device) -> i32, + unsafe extern "C" fn(*mut *const bindings::firmware, *const u8, *mut bindings::device) -> i32, ); impl FwFunc { diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index fbd761380384..8f88891fb1d2 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -225,7 +225,7 @@ unsafe extern "C" fn fops_ioctl( // SAFETY: Ioctl calls can borrow the private data of the file. let device = unsafe { ::borrow(private) }; - match T::ioctl(device, cmd, arg as usize) { + match T::ioctl(device, cmd, arg) { Ok(ret) => ret as c_long, Err(err) => err.to_errno() as c_long, } @@ -245,7 +245,7 @@ unsafe extern "C" fn fops_compat_ioctl( // SAFETY: Ioctl calls can borrow the private data of the file. let device = unsafe { ::borrow(private) }; - match T::compat_ioctl(device, cmd, arg as usize) { + match T::compat_ioctl(device, cmd, arg) { Ok(ret) => ret as c_long, Err(err) => err.to_errno() as c_long, } diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index 05b0b8d13b10..cc044924867b 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -8,7 +8,7 @@ use crate::{ alloc::Flags, bindings, error::Result, - ffi::{c_ulong, c_void}, + ffi::c_void, prelude::*, transmute::{AsBytes, FromBytes}, }; @@ -224,13 +224,9 @@ impl UserSliceReader { if len > self.length { return Err(EFAULT); } - let Ok(len_ulong) = c_ulong::try_from(len) else { - return Err(EFAULT); - }; - // SAFETY: `out_ptr` points into a mutable slice of length `len_ulong`, so we may write + // SAFETY: `out_ptr` points into a mutable slice of length `len`, so we may write // that many bytes to it. - let res = - unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len_ulong) }; + let res = unsafe { bindings::copy_from_user(out_ptr, self.ptr as *const c_void, len) }; if res != 0 { return Err(EFAULT); } @@ -259,9 +255,6 @@ impl UserSliceReader { if len > self.length { return Err(EFAULT); } - let Ok(len_ulong) = c_ulong::try_from(len) else { - return Err(EFAULT); - }; let mut out: MaybeUninit = MaybeUninit::uninit(); // SAFETY: The local variable `out` is valid for writing `size_of::()` bytes. // @@ -272,7 +265,7 @@ impl UserSliceReader { bindings::_copy_from_user( out.as_mut_ptr().cast::(), self.ptr as *const c_void, - len_ulong, + len, ) }; if res != 0 { @@ -335,12 +328,9 @@ impl UserSliceWriter { if len > self.length { return Err(EFAULT); } - let Ok(len_ulong) = c_ulong::try_from(len) else { - return Err(EFAULT); - }; - // SAFETY: `data_ptr` points into an immutable slice of length `len_ulong`, so we may read + // SAFETY: `data_ptr` points into an immutable slice of length `len`, so we may read // that many bytes from it. - let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len_ulong) }; + let res = unsafe { bindings::copy_to_user(self.ptr as *mut c_void, data_ptr, len) }; if res != 0 { return Err(EFAULT); } @@ -359,9 +349,6 @@ impl UserSliceWriter { if len > self.length { return Err(EFAULT); } - let Ok(len_ulong) = c_ulong::try_from(len) else { - return Err(EFAULT); - }; // SAFETY: The reference points to a value of type `T`, so it is valid for reading // `size_of::()` bytes. // @@ -372,7 +359,7 @@ impl UserSliceWriter { bindings::_copy_to_user( self.ptr as *mut c_void, (value as *const T).cast::(), - len_ulong, + len, ) }; if res != 0 { From 9b98be76855f14bd5180b59c1ac646b5add98f33 Mon Sep 17 00:00:00 2001 From: Gary Guo Date: Fri, 13 Sep 2024 22:29:25 +0100 Subject: [PATCH 03/31] rust: cleanup unnecessary casts With `long` mapped to `isize`, `size_t`/`__kernel_size_t` mapped to `usize` and `char` mapped to `u8`, many of the existing casts are no longer necessary. Signed-off-by: Gary Guo Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20240913213041.395655-6-gary@garyguo.net [ Moved `uaccess` changes to the previous commit, since they were irrefutable patterns that Rust >= 1.82.0 warns about. Removed a couple casts that now use `c""` literals. Rebased on top of `rust-next`. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/print.rs | 4 ++-- rust/kernel/str.rs | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/rust/kernel/print.rs b/rust/kernel/print.rs index a28077a7cb30..b19ee490be58 100644 --- a/rust/kernel/print.rs +++ b/rust/kernel/print.rs @@ -107,7 +107,7 @@ pub unsafe fn call_printk( // SAFETY: TODO. unsafe { bindings::_printk( - format_string.as_ptr() as _, + format_string.as_ptr(), module_name.as_ptr(), &args as *const _ as *const c_void, ); @@ -128,7 +128,7 @@ pub fn call_printk_cont(args: fmt::Arguments<'_>) { #[cfg(CONFIG_PRINTK)] unsafe { bindings::_printk( - format_strings::CONT.as_ptr() as _, + format_strings::CONT.as_ptr(), &args as *const _ as *const c_void, ); } diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index d04c12a1426d..0f2765463dc8 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -189,7 +189,7 @@ impl CStr { // 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 as _, len as _) }; + let bytes = unsafe { core::slice::from_raw_parts(ptr as _, 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) } @@ -248,7 +248,7 @@ impl CStr { /// Returns a C pointer to the string. #[inline] pub const fn as_char_ptr(&self) -> *const crate::ffi::c_char { - self.0.as_ptr() as _ + self.0.as_ptr() } /// Convert the string to a byte slice without the trailing `NUL` byte. @@ -838,7 +838,7 @@ impl CString { // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size` // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator) // so `f.bytes_written() - 1` doesn't underflow. - let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) }; + let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, f.bytes_written() - 1) }; if !ptr.is_null() { return Err(EINVAL); } From 9a02cbc5139e668f8b74e75a611d3a04b5241228 Mon Sep 17 00:00:00 2001 From: Daniel Sedlak Date: Sat, 7 Dec 2024 12:24:45 +0100 Subject: [PATCH 04/31] rust: error: modify `from_errno` to use `try_from_errno` Modify the from_errno function to use try_from_errno to reduce code duplication while still maintaining all existing behavior and error handling and also reduces unsafe code. Link: https://github.com/Rust-for-Linux/linux/issues/1125 Suggested-by: Miguel Ojeda Co-developed-by: Guilherme Augusto Martins da Silva Signed-off-by: Guilherme Augusto Martins da Silva Signed-off-by: Daniel Sedlak Reviewed-by: Fiona Behrens Link: https://lore.kernel.org/r/20241207112445.55502-1-daniel@sedlak.dev Signed-off-by: Miguel Ojeda --- rust/kernel/error.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 5fece574ec02..914e8dec1abd 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -101,19 +101,16 @@ impl Error { /// It is a bug to pass an out-of-range `errno`. `EINVAL` would /// be returned in such a case. pub fn from_errno(errno: crate::ffi::c_int) -> Error { - if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 { + if let Some(error) = Self::try_from_errno(errno) { + error + } else { // TODO: Make it a `WARN_ONCE` once available. crate::pr_warn!( "attempted to create `Error` with out of range `errno`: {}", errno ); - return code::EINVAL; + code::EINVAL } - - // INVARIANT: The check above ensures the type invariant - // will hold. - // SAFETY: `errno` is checked above to be in a valid range. - unsafe { Error::from_errno_unchecked(errno) } } /// Creates an [`Error`] from a kernel error code. From 3f4223c007b25327c49aabe3af8ecc72bb33dbf6 Mon Sep 17 00:00:00 2001 From: Dirk Behme Date: Wed, 16 Oct 2024 15:35:07 +0200 Subject: [PATCH 05/31] rust: workqueue: Enable execution of doctests Having the Rust doctests enabled these workqueue tests are built but not executed as the final callers of the print_*() functions are missing. Add them. The result is # rust_doctest_kernel_workqueue_rs_0.location: rust/kernel/workqueue.rs:35 rust_doctests_kernel: The value is: 42 ok 94 rust_doctest_kernel_workqueue_rs_0 # rust_doctest_kernel_workqueue_rs_3.location: rust/kernel/workqueue.rs:78 rust_doctests_kernel: The value is: 24 rust_doctests_kernel: The second value is: 42 ok 97 rust_doctest_kernel_workqueue_rs_3 Without this change the "The value ..." outputs are not there meaning that this test code is not run. Reviewed-by: Alice Ryhl Signed-off-by: Dirk Behme Reviewed-by: Boqun Feng Acked-by: Tejun Heo Link: https://lore.kernel.org/r/cb953202-0dbe-4127-8a8e-6a75258c2116@gmail.com [ Reworded slightly. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/workqueue.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/rust/kernel/workqueue.rs b/rust/kernel/workqueue.rs index 4d1d2062f6eb..1dcd53478edd 100644 --- a/rust/kernel/workqueue.rs +++ b/rust/kernel/workqueue.rs @@ -69,6 +69,7 @@ //! fn print_later(val: Arc) { //! let _ = workqueue::system().enqueue(val); //! } +//! # print_later(MyStruct::new(42).unwrap()); //! ``` //! //! The following example shows how multiple `work_struct` fields can be used: @@ -126,6 +127,8 @@ //! fn print_2_later(val: Arc) { //! let _ = workqueue::system().enqueue::, 2>(val); //! } +//! # print_1_later(MyStruct::new(24, 25).unwrap()); +//! # print_2_later(MyStruct::new(41, 42).unwrap()); //! ``` //! //! C header: [`include/linux/workqueue.h`](srctree/include/linux/workqueue.h) From 2dde1c8b04a5c415912bc3ffa8b677eb364dbcb7 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Thu, 7 Nov 2024 05:36:46 -0500 Subject: [PATCH 06/31] rust: sync: document `PhantomData` in `Arc` Add a comment explaining the relevant semantics of `PhantomData`. This should help future readers who may, as I did, assume that this field is redundant at first glance. Signed-off-by: Tamir Duberstein Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241107-simplify-arc-v2-1-7256e638aac1@gmail.com Signed-off-by: Miguel Ojeda --- rust/kernel/sync/arc.rs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index fa4509406ee9..9f0b04400e8e 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -127,6 +127,14 @@ mod std_vendor; /// ``` pub struct Arc { ptr: NonNull>, + // NB: this informs dropck that objects of type `ArcInner` may be used in ` as + // Drop>::drop`. Note that dropck already assumes that objects of type `T` may be used in + // ` as Drop>::drop` and the distinction between `T` and `ArcInner` is not presently + // meaningful with respect to dropck - but this may change in the future so this is left here + // out of an abundance of caution. + // + // See https://doc.rust-lang.org/nomicon/phantom-data.html#generic-parameters-and-drop-checking + // for more detail on the semantics of dropck in the presence of `PhantomData`. _p: PhantomData>, } From 21e08aa59a9a0b665b051a8919ec80a872807cfb Mon Sep 17 00:00:00 2001 From: Guangbo Cui <2407018371@qq.com> Date: Mon, 11 Nov 2024 21:40:41 +0800 Subject: [PATCH 07/31] rust: alloc: implement Display for Box Currently `impl Display` is missing for `Box`, as a result, things like using `Box<..>` directly as an operand in `pr_info!()` are impossible, which is less ergonomic compared to `Box` in Rust std. Therefore add `impl Display` for `Box`. Acked-by: Danilo Krummrich Suggested-by: Boqun Feng Link: https://github.com/Rust-for-Linux/linux/issues/1126 Signed-off-by: Guangbo Cui <2407018371@qq.com> Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/tencent_2AD25C6A6898D3A598CBA54BB6AF59BB900A@qq.com [ Reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/kbox.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index 9ce414361c2c..6beb97658026 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -427,6 +427,16 @@ where } } +impl fmt::Display for Box +where + T: ?Sized + fmt::Display, + A: Allocator, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + ::fmt(&**self, f) + } +} + impl fmt::Debug for Box where T: ?Sized + fmt::Debug, From 517743c4e303252cd8c1a1fb1bed28e7d94d4678 Mon Sep 17 00:00:00 2001 From: Guangbo Cui <2407018371@qq.com> Date: Mon, 11 Nov 2024 21:51:27 +0800 Subject: [PATCH 08/31] rust: alloc: align Debug implementation for Box with Display Ensure consistency between `Debug` and `Display` for `Box` by updating `Debug` to match the new `Display` style. Acked-by: Danilo Krummrich Signed-off-by: Guangbo Cui <2407018371@qq.com> Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/tencent_1FC0BC283DA65DD81A8A14EEF25563934E05@qq.com [ Reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/kbox.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index 6beb97658026..19e227351918 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -443,7 +443,7 @@ where A: Allocator, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt::Debug::fmt(&**self, f) + ::fmt(&**self, f) } } From 0c5928deada15a8d075516e6e0d9ee19011bb000 Mon Sep 17 00:00:00 2001 From: Yutaro Ohno Date: Thu, 24 Oct 2024 00:54:59 +0900 Subject: [PATCH 09/31] rust: block: fix formatting in GenDisk doc Align bullet points and improve indentation in the `Invariants` section of the `GenDisk` struct documentation for better readability. [ Yutaro is also working on implementing the lint we suggested to catch this sort of issue in upstream Rust: https://github.com/rust-lang/rust-clippy/issues/13601 https://github.com/rust-lang/rust-clippy/pull/13711 Thanks a lot! - Miguel ] Fixes: 3253aba3408a ("rust: block: introduce `kernel::block::mq` module") Signed-off-by: Yutaro Ohno Reviewed-by: Boqun Feng Acked-by: Andreas Hindborg Link: https://lore.kernel.org/r/ZxkcU5yTFCagg_lX@ohnotp Signed-off-by: Miguel Ojeda --- rust/kernel/block/mq/gen_disk.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/block/mq/gen_disk.rs b/rust/kernel/block/mq/gen_disk.rs index 798c4ae0bded..14806e1997fd 100644 --- a/rust/kernel/block/mq/gen_disk.rs +++ b/rust/kernel/block/mq/gen_disk.rs @@ -174,9 +174,9 @@ impl GenDiskBuilder { /// /// # Invariants /// -/// - `gendisk` must always point to an initialized and valid `struct gendisk`. -/// - `gendisk` was added to the VFS through a call to -/// `bindings::device_add_disk`. +/// - `gendisk` must always point to an initialized and valid `struct gendisk`. +/// - `gendisk` was added to the VFS through a call to +/// `bindings::device_add_disk`. pub struct GenDisk { _tagset: Arc>, gendisk: *mut bindings::gendisk, From c23d1f7e15d11d6ae6c70824e04ba9ed0299de0a Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Mon, 9 Dec 2024 22:25:44 +0100 Subject: [PATCH 10/31] rust: document `bindgen` 0.71.0 regression `bindgen` 0.71.0 regressed [1] on the "`--version` requires header" issue which appeared in 0.69.0 first [2] and was fixed in 0.69.1. It has been fixed again in 0.71.1 [3]. Thus document it so that, when we upgrade the minimum past 0.69.0 in the future, we do not forget that we cannot remove the workaround until we arrive at 0.71.1 at least. Link: https://github.com/rust-lang/rust-bindgen/issues/3039 [1] Link: https://github.com/rust-lang/rust-bindgen/issues/2677 [2] Link: https://github.com/rust-lang/rust-bindgen/blob/main/CHANGELOG.md#v0711-2024-12-09 [3] Reviewed-by: Fiona Behrens Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241209212544.1977065-1-ojeda@kernel.org Signed-off-by: Miguel Ojeda --- init/Kconfig | 6 ++++-- scripts/rust_is_available.sh | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/init/Kconfig b/init/Kconfig index a20e6efd3f0f..e8d2b5128f87 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -1989,8 +1989,10 @@ config BINDGEN_VERSION_TEXT string depends on RUST # The dummy parameter `workaround-for-0.69.0` is required to support 0.69.0 - # (https://github.com/rust-lang/rust-bindgen/pull/2678). It can be removed when - # the minimum version is upgraded past that (0.69.1 already fixed the issue). + # (https://github.com/rust-lang/rust-bindgen/pull/2678) and 0.71.0 + # (https://github.com/rust-lang/rust-bindgen/pull/3040). It can be removed + # when the minimum version is upgraded past the latter (0.69.1 and 0.71.1 + # both fixed the issue). default "$(shell,$(BINDGEN) --version workaround-for-0.69.0 2>/dev/null)" # diff --git a/scripts/rust_is_available.sh b/scripts/rust_is_available.sh index 93c0ef7fb3fb..d2323de0692c 100755 --- a/scripts/rust_is_available.sh +++ b/scripts/rust_is_available.sh @@ -123,8 +123,10 @@ fi # Non-stable and distributions' versions may have a version suffix, e.g. `-dev`. # # The dummy parameter `workaround-for-0.69.0` is required to support 0.69.0 -# (https://github.com/rust-lang/rust-bindgen/pull/2678). It can be removed when -# the minimum version is upgraded past that (0.69.1 already fixed the issue). +# (https://github.com/rust-lang/rust-bindgen/pull/2678) and 0.71.0 +# (https://github.com/rust-lang/rust-bindgen/pull/3040). It can be removed when +# the minimum version is upgraded past the latter (0.69.1 and 0.71.1 both fixed +# the issue). rust_bindings_generator_output=$( \ LC_ALL=C "$BINDGEN" --version workaround-for-0.69.0 2>/dev/null ) || rust_bindings_generator_code=$? From f0915acd1fc6060a35e3f18673072671583ff0be Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Nov 2024 23:23:45 +0100 Subject: [PATCH 11/31] rust: give Clippy the minimum supported Rust version Clippy's lints may avoid emitting a suggestion to use a language or library feature that is not supported by the minimum supported version, if given by the `msrv` field in the configuration file. For instance, Clippy should not suggest using `let ... else` in a lint if the MSRV did not implement that syntax. If the MSRV is not provided, Clippy will assume all features are available. Thus enable it with the minimum Rust version the kernel supports. Note that there is currently a small disadvantage in doing so: since we still use unstable features that nevertheless work in the range of versions we support (e.g. `#[expect(...)]`), we lose suggestions for those. However, over time we will stop using unstable features (especially language and library ones) as it is our goal, thus, in the end, we will want to have the `msrv` set. Rust is also considering adding a similar feature in `rustc` too, which we should probably enable if it becomes available [2]. Link: https://github.com/rust-lang/rust-clippy/blob/8298da72e7b81fa30c515631b40fc4c0845948cb/clippy_utils/src/msrvs.rs#L20 [1] Link: https://github.com/rust-lang/compiler-team/issues/772 [2] Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123222345.346976-1-ojeda@kernel.org Signed-off-by: Miguel Ojeda --- .clippy.toml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.clippy.toml b/.clippy.toml index e4c4eef10b28..815c94732ed7 100644 --- a/.clippy.toml +++ b/.clippy.toml @@ -1,5 +1,7 @@ # SPDX-License-Identifier: GPL-2.0 +msrv = "1.78.0" + check-private-items = true disallowed-macros = [ From 2a87f8b075ea0ba33d3809aee7980c019f920bd6 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Nov 2024 19:06:38 +0100 Subject: [PATCH 12/31] rust: kbuild: run Clippy for `rusttest` code Running Clippy for `rusttest` code is useful to catch issues there too, even if the code is not as critical. In the future, this code may also run in kernelspace and could be copy-pasted. Thus it is useful to keep it under the same standards. For instance, it will now make us add `// SAFETY` comments. It also makes everything more consistent. Thus clean the few issues spotted by Clippy and start running it. Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123180639.260191-1-ojeda@kernel.org Signed-off-by: Miguel Ojeda --- rust/Makefile | 8 ++++---- rust/kernel/str.rs | 4 +++- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/rust/Makefile b/rust/Makefile index a40a3936126d..161e7cf67c97 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -116,10 +116,10 @@ rustdoc-kernel: $(src)/kernel/lib.rs rustdoc-core rustdoc-ffi rustdoc-macros \ $(obj)/bindings.o FORCE +$(call if_changed,rustdoc) -quiet_cmd_rustc_test_library = RUSTC TL $< +quiet_cmd_rustc_test_library = $(RUSTC_OR_CLIPPY_QUIET) TL $< cmd_rustc_test_library = \ OBJTREE=$(abspath $(objtree)) \ - $(RUSTC) $(rust_common_flags) \ + $(RUSTC_OR_CLIPPY) $(rust_common_flags) \ @$(objtree)/include/generated/rustc_cfg $(rustc_target_flags) \ --crate-type $(if $(rustc_test_library_proc),proc-macro,rlib) \ --out-dir $(objtree)/$(obj)/test --cfg testlib \ @@ -187,10 +187,10 @@ quiet_cmd_rustdoc_test_kernel = RUSTDOC TK $< # We cannot use `-Zpanic-abort-tests` because some tests are dynamic, # so for the moment we skip `-Cpanic=abort`. -quiet_cmd_rustc_test = RUSTC T $< +quiet_cmd_rustc_test = $(RUSTC_OR_CLIPPY_QUIET) T $< cmd_rustc_test = \ OBJTREE=$(abspath $(objtree)) \ - $(RUSTC) --test $(rust_common_flags) \ + $(RUSTC_OR_CLIPPY) --test $(rust_common_flags) \ @$(objtree)/include/generated/rustc_cfg \ $(rustc_target_flags) --out-dir $(objtree)/$(obj)/test \ -L$(objtree)/$(obj)/test \ diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 0f2765463dc8..5dfddb0d41d9 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -522,6 +522,7 @@ macro_rules! c_str { } #[cfg(test)] +#[expect(clippy::items_after_test_module)] mod tests { use super::*; @@ -547,7 +548,7 @@ mod tests { }) } - const ALL_ASCII_CHARS: &'static str = + const ALL_ASCII_CHARS: &str = "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ \\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \ !\"#$%&'()*+,-./0123456789:;<=>?@\ @@ -581,6 +582,7 @@ mod tests { fn test_cstr_as_str_unchecked() { let good_bytes = b"\xf0\x9f\x90\xA7\0"; let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); + // 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, "🐧"); } From 15f2f9313a394f97fb9443271721e9ff1c8d4be4 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Nov 2024 23:28:47 +0100 Subject: [PATCH 13/31] rust: use the `build_error!` macro, not the hidden function Code and some examples were using the function, rather than the macro. The macro is what is documented. Thus move users to the macro. Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123222849.350287-1-ojeda@kernel.org [ Applied the change to the new miscdevice cases. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/block/mq/operations.rs | 2 +- rust/kernel/miscdevice.rs | 4 ++-- rust/kernel/net/phy.rs | 18 +++++++++--------- rust/macros/lib.rs | 8 ++++---- 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/rust/kernel/block/mq/operations.rs b/rust/kernel/block/mq/operations.rs index c8646d0d9866..962f16a5a530 100644 --- a/rust/kernel/block/mq/operations.rs +++ b/rust/kernel/block/mq/operations.rs @@ -35,7 +35,7 @@ pub trait Operations: Sized { /// Called by the kernel to poll the device for completed requests. Only /// used for poll queues. fn poll() -> bool { - crate::build_error(crate::error::VTABLE_DEFAULT_ERROR) + crate::build_error!(crate::error::VTABLE_DEFAULT_ERROR) } } diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index 8f88891fb1d2..a26b3d31a97b 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -116,7 +116,7 @@ pub trait MiscDevice { _cmd: u32, _arg: usize, ) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Handler for ioctls. @@ -132,7 +132,7 @@ pub trait MiscDevice { _cmd: u32, _arg: usize, ) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } } diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs index b89c681d97c0..ea43b7571ae0 100644 --- a/rust/kernel/net/phy.rs +++ b/rust/kernel/net/phy.rs @@ -587,17 +587,17 @@ pub trait Driver { /// Issues a PHY software reset. fn soft_reset(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Sets up device-specific structures during discovery. fn probe(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Probes the hardware to determine what abilities it has. fn get_features(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Returns true if this is a suitable driver for the given phydev. @@ -609,32 +609,32 @@ pub trait Driver { /// Configures the advertisement and resets auto-negotiation /// if auto-negotiation is enabled. fn config_aneg(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Determines the negotiated speed and duplex. fn read_status(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Suspends the hardware, saving state if needed. fn suspend(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Resumes the hardware, restoring state if needed. fn resume(_dev: &mut Device) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Overrides the default MMD read function for reading a MMD register. fn read_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Overrides the default MMD write function for writing a MMD register. fn write_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16, _val: u16) -> Result { - kernel::build_error(VTABLE_DEFAULT_ERROR) + kernel::build_error!(VTABLE_DEFAULT_ERROR) } /// Callback for notification of link change. diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 4ab94e44adfe..1a30c8075ebd 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -123,12 +123,12 @@ pub fn module(ts: TokenStream) -> TokenStream { /// used on the Rust side, it should not be possible to call the default /// implementation. This is done to ensure that we call the vtable methods /// through the C vtable, and not through the Rust vtable. Therefore, the -/// default implementation should call `kernel::build_error`, which prevents +/// default implementation should call `kernel::build_error!`, which prevents /// calls to this function at compile time: /// /// ```compile_fail /// # // Intentionally missing `use`s to simplify `rusttest`. -/// kernel::build_error(VTABLE_DEFAULT_ERROR) +/// kernel::build_error!(VTABLE_DEFAULT_ERROR) /// ``` /// /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`]. @@ -145,11 +145,11 @@ pub fn module(ts: TokenStream) -> TokenStream { /// #[vtable] /// pub trait Operations: Send + Sync + Sized { /// fn foo(&self) -> Result<()> { -/// kernel::build_error(VTABLE_DEFAULT_ERROR) +/// kernel::build_error!(VTABLE_DEFAULT_ERROR) /// } /// /// fn bar(&self) -> Result<()> { -/// kernel::build_error(VTABLE_DEFAULT_ERROR) +/// kernel::build_error!(VTABLE_DEFAULT_ERROR) /// } /// } /// From 614724e780f587c8321f027ca539b39f32796406 Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Nov 2024 23:28:48 +0100 Subject: [PATCH 14/31] rust: kernel: move `build_error` hidden function to prevent mistakes Users were using the hidden exported `kernel::build_error` function instead of the intended `kernel::build_error!` macro, e.g. see the previous commit. To force to use the macro, move it into the `build_assert` module, thus making it a compilation error and avoiding a collision in the same "namespace". Using the function now would require typing the module name (which is hidden), not just a single character. Now attempting to use the function will trigger this error with the right suggestion by the compiler: error[E0423]: expected function, found macro `kernel::build_error` --> samples/rust/rust_minimal.rs:29:9 | 29 | kernel::build_error(); | ^^^^^^^^^^^^^^^^^^^ not a function | help: use `!` to invoke the macro | 29 | kernel::build_error!(); | + An alternative would be using an alias, but it would be more complex and moving it into the module seems right since it belongs there and reduces the amount of code at the crate root. Keep the `#[doc(hidden)]` inside `build_assert` in case the module is not hidden in the future. Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123222849.350287-2-ojeda@kernel.org Signed-off-by: Miguel Ojeda --- rust/kernel/build_assert.rs | 11 +++++++---- rust/kernel/lib.rs | 6 ++---- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/rust/kernel/build_assert.rs b/rust/kernel/build_assert.rs index 9e37120bc69c..347ba5ce50f4 100644 --- a/rust/kernel/build_assert.rs +++ b/rust/kernel/build_assert.rs @@ -2,6 +2,9 @@ //! Build-time assert. +#[doc(hidden)] +pub use build_error::build_error; + /// Fails the build if the code path calling `build_error!` can possibly be executed. /// /// If the macro is executed in const context, `build_error!` will panic. @@ -23,10 +26,10 @@ #[macro_export] macro_rules! build_error { () => {{ - $crate::build_error("") + $crate::build_assert::build_error("") }}; ($msg:expr) => {{ - $crate::build_error($msg) + $crate::build_assert::build_error($msg) }}; } @@ -73,12 +76,12 @@ macro_rules! build_error { macro_rules! build_assert { ($cond:expr $(,)?) => {{ if !$cond { - $crate::build_error(concat!("assertion failed: ", stringify!($cond))); + $crate::build_assert::build_error(concat!("assertion failed: ", stringify!($cond))); } }}; ($cond:expr, $msg:expr) => {{ if !$cond { - $crate::build_error($msg); + $crate::build_assert::build_error($msg); } }}; } diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index e1065a7551a3..6063f4a3d9c0 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -32,7 +32,8 @@ pub use ffi; pub mod alloc; #[cfg(CONFIG_BLOCK)] pub mod block; -mod build_assert; +#[doc(hidden)] +pub mod build_assert; pub mod cred; pub mod device; pub mod error; @@ -74,9 +75,6 @@ pub use bindings; pub use macros; pub use uapi; -#[doc(hidden)] -pub use build_error::build_error; - /// Prefix to appear before log messages printed from within the `kernel` crate. const __LOG_PREFIX: &[u8] = b"rust_kernel\0"; From 4401565fe92be6ee54a68ea58d80a4076007d5eb Mon Sep 17 00:00:00 2001 From: Miguel Ojeda Date: Sat, 23 Nov 2024 23:28:49 +0100 Subject: [PATCH 15/31] rust: add `build_error!` to the prelude The sibling `build_assert!` is already in the prelude, it makes sense that a "core"/"language" facility like this is part of the prelude and users should not be defining their own one (thus there should be no risk of future name collisions and we would want to be aware of them anyway). Thus add `build_error!` into the prelude. Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123222849.350287-3-ojeda@kernel.org [ Applied the change to the new miscdevice cases. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/block/mq/operations.rs | 3 ++- rust/kernel/build_assert.rs | 1 - rust/kernel/miscdevice.rs | 4 ++-- rust/kernel/net/phy.rs | 18 +++++++++--------- rust/kernel/prelude.rs | 2 +- rust/macros/lib.rs | 8 ++++---- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/rust/kernel/block/mq/operations.rs b/rust/kernel/block/mq/operations.rs index 962f16a5a530..864ff379dc91 100644 --- a/rust/kernel/block/mq/operations.rs +++ b/rust/kernel/block/mq/operations.rs @@ -9,6 +9,7 @@ use crate::{ block::mq::request::RequestDataWrapper, block::mq::Request, error::{from_result, Result}, + prelude::*, types::ARef, }; use core::{marker::PhantomData, sync::atomic::AtomicU64, sync::atomic::Ordering}; @@ -35,7 +36,7 @@ pub trait Operations: Sized { /// Called by the kernel to poll the device for completed requests. Only /// used for poll queues. fn poll() -> bool { - crate::build_error!(crate::error::VTABLE_DEFAULT_ERROR) + build_error!(crate::error::VTABLE_DEFAULT_ERROR) } } diff --git a/rust/kernel/build_assert.rs b/rust/kernel/build_assert.rs index 347ba5ce50f4..6331b15d7c4d 100644 --- a/rust/kernel/build_assert.rs +++ b/rust/kernel/build_assert.rs @@ -14,7 +14,6 @@ pub use build_error::build_error; /// # Examples /// /// ``` -/// # use kernel::build_error; /// #[inline] /// fn foo(a: usize) -> usize { /// a.checked_add(1).unwrap_or_else(|| build_error!("overflow")) diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index a26b3d31a97b..9e1b9c0fae9d 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -116,7 +116,7 @@ pub trait MiscDevice { _cmd: u32, _arg: usize, ) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Handler for ioctls. @@ -132,7 +132,7 @@ pub trait MiscDevice { _cmd: u32, _arg: usize, ) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } } diff --git a/rust/kernel/net/phy.rs b/rust/kernel/net/phy.rs index ea43b7571ae0..d7da29f95e43 100644 --- a/rust/kernel/net/phy.rs +++ b/rust/kernel/net/phy.rs @@ -587,17 +587,17 @@ pub trait Driver { /// Issues a PHY software reset. fn soft_reset(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Sets up device-specific structures during discovery. fn probe(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Probes the hardware to determine what abilities it has. fn get_features(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Returns true if this is a suitable driver for the given phydev. @@ -609,32 +609,32 @@ pub trait Driver { /// Configures the advertisement and resets auto-negotiation /// if auto-negotiation is enabled. fn config_aneg(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Determines the negotiated speed and duplex. fn read_status(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Suspends the hardware, saving state if needed. fn suspend(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Resumes the hardware, restoring state if needed. fn resume(_dev: &mut Device) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Overrides the default MMD read function for reading a MMD register. fn read_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Overrides the default MMD write function for writing a MMD register. fn write_mmd(_dev: &mut Device, _devnum: u8, _regnum: u16, _val: u16) -> Result { - kernel::build_error!(VTABLE_DEFAULT_ERROR) + build_error!(VTABLE_DEFAULT_ERROR) } /// Callback for notification of link change. diff --git a/rust/kernel/prelude.rs b/rust/kernel/prelude.rs index 9ab4e0b6cbc9..dde2e0649790 100644 --- a/rust/kernel/prelude.rs +++ b/rust/kernel/prelude.rs @@ -19,7 +19,7 @@ pub use crate::alloc::{flags::*, Box, KBox, KVBox, KVVec, KVec, VBox, VVec, Vec} #[doc(no_inline)] pub use macros::{module, pin_data, pinned_drop, vtable, Zeroable}; -pub use super::build_assert; +pub use super::{build_assert, build_error}; // `super::std_vendor` is hidden, which makes the macro inline for some reason. #[doc(no_inline)] diff --git a/rust/macros/lib.rs b/rust/macros/lib.rs index 1a30c8075ebd..d61bc6a56425 100644 --- a/rust/macros/lib.rs +++ b/rust/macros/lib.rs @@ -123,12 +123,12 @@ pub fn module(ts: TokenStream) -> TokenStream { /// used on the Rust side, it should not be possible to call the default /// implementation. This is done to ensure that we call the vtable methods /// through the C vtable, and not through the Rust vtable. Therefore, the -/// default implementation should call `kernel::build_error!`, which prevents +/// default implementation should call `build_error!`, which prevents /// calls to this function at compile time: /// /// ```compile_fail /// # // Intentionally missing `use`s to simplify `rusttest`. -/// kernel::build_error!(VTABLE_DEFAULT_ERROR) +/// build_error!(VTABLE_DEFAULT_ERROR) /// ``` /// /// Note that you might need to import [`kernel::error::VTABLE_DEFAULT_ERROR`]. @@ -145,11 +145,11 @@ pub fn module(ts: TokenStream) -> TokenStream { /// #[vtable] /// pub trait Operations: Send + Sync + Sized { /// fn foo(&self) -> Result<()> { -/// kernel::build_error!(VTABLE_DEFAULT_ERROR) +/// build_error!(VTABLE_DEFAULT_ERROR) /// } /// /// fn bar(&self) -> Result<()> { -/// kernel::build_error!(VTABLE_DEFAULT_ERROR) +/// build_error!(VTABLE_DEFAULT_ERROR) /// } /// } /// From 0730422bced5e8325fb6806d9a80bb10673588e6 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Mon, 16 Dec 2024 10:54:22 -0500 Subject: [PATCH 16/31] rust: use host dylib naming convention to support macOS Because the `macros` crate exposes procedural macros, it must be compiled as a dynamic library (so it can be loaded by the compiler at compile-time). Before this change the resulting artifact was always named `libmacros.so`, which works on hosts where this matches the naming convention for dynamic libraries. However the proper name on macOS would be `libmacros.dylib`. This turns out to matter even when the dependency is passed with a path (`--extern macros=path/to/libmacros.so` rather than `--extern macros`) because rustc uses the file name to infer the type of the library (see link). This is because there's no way to specify both the path to and the type of the external library via CLI flags. The compiler could speculatively parse the file to determine its type, but it does not do so today. This means that libraries that match neither rustc's naming convention for static libraries nor the platform's naming convention for dynamic libraries are *rejected*. The only solution I've found is to follow the host platform's naming convention. This patch does that by querying the compiler to determine the appropriate name for the artifact. This allows the kernel to build with CONFIG_RUST=y on macOS. Link: https://github.com/rust-lang/rust/blob/d829780/compiler/rustc_metadata/src/locator.rs#L728-L752 Tested-by: Daniel Gomez Co-developed-by: Fiona Behrens Signed-off-by: Fiona Behrens Signed-off-by: Tamir Duberstein Tested-by: Andreas Hindborg Link: https://lore.kernel.org/r/20241216-b4-dylib-host-macos-v7-1-cfc507681447@gmail.com [ Added `MAKEFLAGS=`s to avoid jobserver warnings. Removed space. Reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- .gitignore | 1 + Makefile | 2 +- rust/Makefile | 22 ++++++++++++---------- scripts/generate_rust_analyzer.py | 15 +++++++++++---- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index 6839cf84acda..5937c74d3dc1 100644 --- a/.gitignore +++ b/.gitignore @@ -22,6 +22,7 @@ *.dtb.S *.dtbo.S *.dwo +*.dylib *.elf *.gcno *.gcda diff --git a/Makefile b/Makefile index e5b8a8832c0c..80d9943d9744 100644 --- a/Makefile +++ b/Makefile @@ -1571,7 +1571,7 @@ MRPROPER_FILES += include/config include/generated \ certs/x509.genkey \ vmlinux-gdb.py \ rpmbuild \ - rust/libmacros.so + rust/libmacros.so rust/libmacros.dylib # clean - Delete most, but leave enough to build external modules # diff --git a/rust/Makefile b/rust/Makefile index 161e7cf67c97..5c8f35f5ada2 100644 --- a/rust/Makefile +++ b/rust/Makefile @@ -11,9 +11,6 @@ always-$(CONFIG_RUST) += exports_core_generated.h obj-$(CONFIG_RUST) += helpers/helpers.o CFLAGS_REMOVE_helpers/helpers.o = -Wmissing-prototypes -Wmissing-declarations -always-$(CONFIG_RUST) += libmacros.so -no-clean-files += libmacros.so - always-$(CONFIG_RUST) += bindings/bindings_generated.rs bindings/bindings_helpers_generated.rs obj-$(CONFIG_RUST) += bindings.o kernel.o always-$(CONFIG_RUST) += exports_helpers_generated.h \ @@ -38,9 +35,14 @@ obj-$(CONFIG_RUST_KERNEL_DOCTESTS) += doctests_kernel_generated_kunit.o always-$(subst y,$(CONFIG_RUST),$(CONFIG_JUMP_LABEL)) += kernel/generated_arch_static_branch_asm.rs -# Avoids running `$(RUSTC)` for the sysroot when it may not be available. +# Avoids running `$(RUSTC)` when it may not be available. ifdef CONFIG_RUST +libmacros_name := $(shell MAKEFLAGS= $(RUSTC) --print file-names --crate-name macros --crate-type proc-macro - Date: Sat, 23 Nov 2024 10:50:28 +0100 Subject: [PATCH 17/31] rust: init: replace unwraps with question mark operators Use `?` operator in the doctests. Since it is in the examples, using unwraps can convey a wrong impression that unwrapping is fine in general, thus this patch removes this unwrapping. Suggested-by: Miguel Ojeda Link: https://lore.kernel.org/rust-for-linux/CANiq72nsK1D4NuQ1U7NqMWoYjXkqQSj4QuUEL98OmFbq022Z9A@mail.gmail.com/ Signed-off-by: Daniel Sedlak Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123095033.41240-2-daniel@sedlak.dev [ Reworded commit slightly. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/init.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 347049df556b..81d69d22090c 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -1076,8 +1076,9 @@ pub fn uninit() -> impl Init, E> { /// ```rust /// use kernel::{alloc::KBox, error::Error, init::init_array_from_fn}; /// let array: KBox<[usize; 1_000]> = -/// KBox::init::(init_array_from_fn(|i| i), GFP_KERNEL).unwrap(); +/// KBox::init::(init_array_from_fn(|i| i), GFP_KERNEL)?; /// assert_eq!(array.len(), 1_000); +/// # Ok::<(), Error>(()) /// ``` pub fn init_array_from_fn( mut make_init: impl FnMut(usize) -> I, @@ -1120,8 +1121,9 @@ where /// ```rust /// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex}; /// let array: Arc<[Mutex; 1_000]> = -/// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i)), GFP_KERNEL).unwrap(); +/// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i)), GFP_KERNEL)?; /// assert_eq!(array.len(), 1_000); +/// # Ok::<(), Error>(()) /// ``` pub fn pin_init_array_from_fn( mut make_init: impl FnMut(usize) -> I, From 3a518544829630d172b067be8697e018e258c445 Mon Sep 17 00:00:00 2001 From: Daniel Sedlak Date: Sat, 23 Nov 2024 10:50:29 +0100 Subject: [PATCH 18/31] rust: rbtree: remove unwrap in asserts Remove `unwrap` in asserts and replace it with `Option::Some` matching. By doing it this way, the examples are more descriptive, so it disambiguates the return type of the `get(...)` and `next(...)`, because the `unwrap(...)` can also be called on `Result`. Signed-off-by: Daniel Sedlak Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241123095033.41240-3-daniel@sedlak.dev [ Reworded title slightly. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/rbtree.rs | 46 +++++++++++++++++++++---------------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/rust/kernel/rbtree.rs b/rust/kernel/rbtree.rs index cb4415a12258..ee2731dad72d 100644 --- a/rust/kernel/rbtree.rs +++ b/rust/kernel/rbtree.rs @@ -36,17 +36,17 @@ use core::{ /// /// // Check the nodes we just inserted. /// { -/// assert_eq!(tree.get(&10).unwrap(), &100); -/// assert_eq!(tree.get(&20).unwrap(), &200); -/// assert_eq!(tree.get(&30).unwrap(), &300); +/// assert_eq!(tree.get(&10), Some(&100)); +/// assert_eq!(tree.get(&20), Some(&200)); +/// assert_eq!(tree.get(&30), Some(&300)); /// } /// /// // Iterate over the nodes we just inserted. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &300))); /// assert!(iter.next().is_none()); /// } /// @@ -61,9 +61,9 @@ use core::{ /// // Check that the tree reflects the replacement. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &1000)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert_eq!(iter.next(), Some((&10, &1000))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &300))); /// assert!(iter.next().is_none()); /// } /// @@ -73,9 +73,9 @@ use core::{ /// // Check that the tree reflects the update. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &1000)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert_eq!(iter.next(), Some((&10, &1000))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &3000))); /// assert!(iter.next().is_none()); /// } /// @@ -85,8 +85,8 @@ use core::{ /// // Check that the tree reflects the removal. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &3000)); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &3000))); /// assert!(iter.next().is_none()); /// } /// @@ -128,20 +128,20 @@ use core::{ /// // Check the nodes we just inserted. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); -/// assert_eq!(iter.next().unwrap(), (&30, &300)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&20, &200))); +/// assert_eq!(iter.next(), Some((&30, &300))); /// assert!(iter.next().is_none()); /// } /// /// // Remove a node, getting back ownership of it. -/// let existing = tree.remove(&30).unwrap(); +/// let existing = tree.remove(&30); /// /// // Check that the tree reflects the removal. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&20, &200))); /// assert!(iter.next().is_none()); /// } /// @@ -155,9 +155,9 @@ use core::{ /// // Check that the tree reflect the new insertion. /// { /// let mut iter = tree.iter(); -/// assert_eq!(iter.next().unwrap(), (&10, &100)); -/// assert_eq!(iter.next().unwrap(), (&15, &150)); -/// assert_eq!(iter.next().unwrap(), (&20, &200)); +/// assert_eq!(iter.next(), Some((&10, &100))); +/// assert_eq!(iter.next(), Some((&15, &150))); +/// assert_eq!(iter.next(), Some((&20, &200))); /// assert!(iter.next().is_none()); /// } /// From 57c1ccc7e71a2f08ef0c1c525408195fb606bc36 Mon Sep 17 00:00:00 2001 From: Daniel Sedlak Date: Sat, 23 Nov 2024 10:50:30 +0100 Subject: [PATCH 19/31] rust: page: remove unnecessary helper function from doctest Doctests in `page.rs` contained a helper function `dox` which acted as a wrapper for using the `?` operator. However, this is not needed because doctests are implicitly wrapped in function see [1]. Link: https://doc.rust-lang.org/rustdoc/write-documentation/documentation-tests.html#using--in-doc-tests [1] Suggested-by: Dirk Behme Suggested-by: Miguel Ojeda Link: https://lore.kernel.org/rust-for-linux/459782fe-afca-4fe6-8ffb-ba7c7886de0a@de.bosch.com/ Reviewed-by: Alice Ryhl Reviewed-by: Tamir Duberstein Signed-off-by: Daniel Sedlak Link: https://lore.kernel.org/r/20241123095033.41240-4-daniel@sedlak.dev [ Fixed typo in SoB. Slightly reworded commit. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/page.rs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs index fdac6c375fe4..f6126aca33a6 100644 --- a/rust/kernel/page.rs +++ b/rust/kernel/page.rs @@ -57,9 +57,8 @@ impl Page { /// ``` /// use kernel::page::Page; /// - /// # fn dox() -> Result<(), kernel::alloc::AllocError> { /// let page = Page::alloc_page(GFP_KERNEL)?; - /// # Ok(()) } + /// # Ok::<(), kernel::alloc::AllocError>(()) /// ``` /// /// Allocate memory for a page and zero its contents. @@ -67,9 +66,8 @@ impl Page { /// ``` /// use kernel::page::Page; /// - /// # fn dox() -> Result<(), kernel::alloc::AllocError> { /// let page = Page::alloc_page(GFP_KERNEL | __GFP_ZERO)?; - /// # Ok(()) } + /// # Ok::<(), kernel::alloc::AllocError>(()) /// ``` pub fn alloc_page(flags: Flags) -> Result { // SAFETY: Depending on the value of `gfp_flags`, this call may sleep. Other than that, it From b6357e26865a25650e49c4eb5abe6ef57ae4ede1 Mon Sep 17 00:00:00 2001 From: Daniel Sedlak Date: Sat, 23 Nov 2024 10:50:31 +0100 Subject: [PATCH 20/31] rust: str: replace unwraps with question mark operators Simplify the error handling by replacing unwraps with the question mark operator. Furthermore, unwraps can convey a wrong impression that unwrapping is fine in general, thus this patch removes this unwrapping. Suggested-by: Miguel Ojeda Link: https://lore.kernel.org/rust-for-linux/CANiq72nsK1D4NuQ1U7NqMWoYjXkqQSj4QuUEL98OmFbq022Z9A@mail.gmail.com/ Reviewed-by: Alice Ryhl Signed-off-by: Daniel Sedlak Link: https://lore.kernel.org/r/20241123095033.41240-5-daniel@sedlak.dev [ Slightly reworded commit. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/str.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs index 5dfddb0d41d9..28e2201604d6 100644 --- a/rust/kernel/str.rs +++ b/rust/kernel/str.rs @@ -39,12 +39,13 @@ impl fmt::Display for BStr { /// ``` /// # use kernel::{fmt, b_str, str::{BStr, CString}}; /// let ascii = b_str!("Hello, BStr!"); - /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); + /// let s = CString::try_from_fmt(fmt!("{}", ascii))?; /// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes()); /// /// let non_ascii = b_str!("🦀"); - /// let s = CString::try_from_fmt(fmt!("{}", non_ascii)).unwrap(); + /// let s = CString::try_from_fmt(fmt!("{}", non_ascii))?; /// assert_eq!(s.as_bytes(), "\\xf0\\x9f\\xa6\\x80".as_bytes()); + /// # Ok::<(), kernel::error::Error>(()) /// ``` fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { for &b in &self.0 { @@ -70,12 +71,13 @@ impl fmt::Debug for BStr { /// # use kernel::{fmt, b_str, str::{BStr, CString}}; /// // Embedded double quotes are escaped. /// let ascii = b_str!("Hello, \"BStr\"!"); - /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap(); + /// let s = CString::try_from_fmt(fmt!("{:?}", ascii))?; /// assert_eq!(s.as_bytes(), "\"Hello, \\\"BStr\\\"!\"".as_bytes()); /// /// let non_ascii = b_str!("😺"); - /// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii)).unwrap(); + /// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii))?; /// assert_eq!(s.as_bytes(), "\"\\xf0\\x9f\\x98\\xba\"".as_bytes()); + /// # Ok::<(), kernel::error::Error>(()) /// ``` fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_char('"')?; @@ -273,8 +275,9 @@ impl CStr { /// /// ``` /// # use kernel::str::CStr; - /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap(); + /// 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> { @@ -384,12 +387,13 @@ impl fmt::Display for CStr { /// # use kernel::str::CStr; /// # use kernel::str::CString; /// let penguin = c_str!("🐧"); - /// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap(); + /// let s = CString::try_from_fmt(fmt!("{}", penguin))?; /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes()); /// /// let ascii = c_str!("so \"cool\""); - /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); + /// 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 { for &c in self.as_bytes() { @@ -413,13 +417,14 @@ impl fmt::Debug for CStr { /// # use kernel::str::CStr; /// # use kernel::str::CString; /// let penguin = c_str!("🐧"); - /// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap(); + /// 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)).unwrap(); + /// 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("\"")?; @@ -801,16 +806,17 @@ impl fmt::Write for Formatter { /// ``` /// use kernel::{str::CString, fmt}; /// -/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20))?; /// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes()); /// /// let tmp = "testing"; -/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap(); +/// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123))?; /// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes()); /// /// // This fails because it has an embedded `NUL` byte. /// let s = CString::try_from_fmt(fmt!("a\0b{}", 123)); /// assert_eq!(s.is_ok(), false); +/// # Ok::<(), kernel::error::Error>(()) /// ``` pub struct CString { buf: KVec, From 7871c612cade8943694cc254740a374e3fb42a7c Mon Sep 17 00:00:00 2001 From: Jimmy Ostler Date: Thu, 19 Dec 2024 22:25:31 -0800 Subject: [PATCH 21/31] rust: error: import `kernel`'s `LayoutError` instead of `core`'s Import the internal (`kernel::alloc`) version of `LayoutError` instead of the `core::alloc` one. In particular, this results in switching the type in the existing `From for Error` implementation. Acked-by: Danilo Krummrich Signed-off-by: Jimmy Ostler Link: https://lore.kernel.org/r/fe58a02189e8804a9eabdd01cb1927d4c491d79c.1734674670.git.jtostler1@gmail.com [ Reworded commit. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/error.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/rust/kernel/error.rs b/rust/kernel/error.rs index 914e8dec1abd..f6ecf09cb65f 100644 --- a/rust/kernel/error.rs +++ b/rust/kernel/error.rs @@ -4,9 +4,10 @@ //! //! C header: [`include/uapi/asm-generic/errno-base.h`](srctree/include/uapi/asm-generic/errno-base.h) -use crate::{alloc::AllocError, str::CStr}; - -use core::alloc::LayoutError; +use crate::{ + alloc::{layout::LayoutError, AllocError}, + str::CStr, +}; use core::fmt; use core::num::NonZeroI32; From 59d5846594e9f82c11af72151de7cef3f325dd4b Mon Sep 17 00:00:00 2001 From: Jimmy Ostler Date: Thu, 19 Dec 2024 22:25:32 -0800 Subject: [PATCH 22/31] rust: init: update `stack_try_pin_init` examples Change documentation imports to use `kernel::alloc::AllocError`, because `KBox::new()` now returns that, instead of the `core`'s `AllocError`. Reviewed-by: Danilo Krummrich Signed-off-by: Jimmy Ostler Link: https://lore.kernel.org/r/ec8badbe94c5e78f22315325a7f2ae96129d6a65.1734674670.git.jtostler1@gmail.com [ Fixed formatting of imports (still unordered). Slightly reworded commit. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/init.rs | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/rust/kernel/init.rs b/rust/kernel/init.rs index 81d69d22090c..3f9236c1c9d5 100644 --- a/rust/kernel/init.rs +++ b/rust/kernel/init.rs @@ -290,9 +290,17 @@ macro_rules! stack_pin_init { /// /// ```rust,ignore /// # #![expect(clippy::disallowed_names)] -/// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex}; +/// # use kernel::{ +/// # init, +/// # pin_init, +/// # stack_try_pin_init, +/// # init::*, +/// # sync::Mutex, +/// # new_mutex, +/// # alloc::AllocError, +/// # }; /// # use macros::pin_data; -/// # use core::{alloc::AllocError, pin::Pin}; +/// # use core::pin::Pin; /// #[pin_data] /// struct Foo { /// #[pin] @@ -316,9 +324,17 @@ macro_rules! stack_pin_init { /// /// ```rust,ignore /// # #![expect(clippy::disallowed_names)] -/// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex}; +/// # use kernel::{ +/// # init, +/// # pin_init, +/// # stack_try_pin_init, +/// # init::*, +/// # sync::Mutex, +/// # new_mutex, +/// # alloc::AllocError, +/// # }; /// # use macros::pin_data; -/// # use core::{alloc::AllocError, pin::Pin}; +/// # use core::pin::Pin; /// #[pin_data] /// struct Foo { /// #[pin] From 91da5a24144e5a82bf88c5f72068cf1628198668 Mon Sep 17 00:00:00 2001 From: Jimmy Ostler Date: Thu, 19 Dec 2024 22:25:33 -0800 Subject: [PATCH 23/31] rust: alloc: add doctest for `ArrayLayout::new()` Add a rustdoc example and Kunit test to the `ArrayLayout` struct's `ArrayLayout::new()` function. This patch depends on the first patch in this series in order for the KUnit test to compile. Suggested-by: Boqun Feng Link: https://github.com/Rust-for-Linux/linux/issues/1131 Reviewed-by: Danilo Krummrich Signed-off-by: Jimmy Ostler Link: https://lore.kernel.org/r/f1564da5bcaa6be87aee312767a1d1694a03d1b7.1734674670.git.jtostler1@gmail.com [ Added periods to example comments. Reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/layout.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/rust/kernel/alloc/layout.rs b/rust/kernel/alloc/layout.rs index 4b3cd7fdc816..93ed514f7cc7 100644 --- a/rust/kernel/alloc/layout.rs +++ b/rust/kernel/alloc/layout.rs @@ -43,6 +43,25 @@ impl ArrayLayout { /// # Errors /// /// When `len * size_of::()` overflows or when `len * size_of::() > isize::MAX`. + /// + /// # Examples + /// + /// ``` + /// # use kernel::alloc::layout::{ArrayLayout, LayoutError}; + /// let layout = ArrayLayout::::new(15)?; + /// assert_eq!(layout.len(), 15); + /// + /// // Errors because `len * size_of::()` overflows. + /// let layout = ArrayLayout::::new(isize::MAX as usize); + /// assert!(layout.is_err()); + /// + /// // Errors because `len * size_of::() > isize::MAX`, + /// // even though `len < isize::MAX`. + /// let layout = ArrayLayout::::new(isize::MAX as usize / 2); + /// assert!(layout.is_err()); + /// + /// # Ok::<(), Error>(()) + /// ``` pub const fn new(len: usize) -> Result { match len.checked_mul(core::mem::size_of::()) { Some(size) if size <= ISIZE_MAX => { From 47cb6bf7860ce33bdd000198f8b65cf9fb3324b4 Mon Sep 17 00:00:00 2001 From: Xiangfei Ding Date: Wed, 4 Dec 2024 04:47:49 +0800 Subject: [PATCH 24/31] rust: use derive(CoercePointee) on rustc >= 1.84.0 The `kernel` crate relies on both `coerce_unsized` and `dispatch_from_dyn` unstable features. Alice Ryhl has proposed [1] the introduction of the unstable macro `SmartPointer` to reduce such dependence, along with a RFC patch [2]. Since Rust 1.81.0 this macro, later renamed to `CoercePointee` in Rust 1.84.0 [3], has been fully implemented with the naming discussion resolved. This feature is now on track to stabilization in the language. In order to do so, we shall start using this macro in the `kernel` crate to prove the functionality and utility of the macro as the justification of its stabilization. This patch makes this switch in such a way that the crate remains backward compatible with older Rust compiler versions, via the new Kconfig option `RUSTC_HAS_COERCE_POINTEE`. A minimal demonstration example is added to the `samples/rust/rust_print_main.rs` module. Link: https://rust-lang.github.io/rfcs/3621-derive-smart-pointer.html [1] Link: https://lore.kernel.org/all/20240823-derive-smart-pointer-v1-1-53769cd37239@google.com/ [2] Link: https://github.com/rust-lang/rust/pull/131284 [3] Signed-off-by: Xiangfei Ding Reviewed-by: Fiona Behrens Reviewed-by: Alice Ryhl Link: https://lore.kernel.org/r/20241203205050.679106-2-dingxiangfei2009@gmail.com [ Fixed version to 1.84. Renamed option to `RUSTC_HAS_COERCE_POINTEE` to match `CC_HAS_*` ones. Moved up new config option, closer to the `CC_HAS_*` ones. Simplified Kconfig line. Fixed typos and slightly reworded example and commit. Added Link to PR. - Miguel ] Signed-off-by: Miguel Ojeda --- init/Kconfig | 3 +++ rust/kernel/alloc.rs | 2 +- rust/kernel/lib.rs | 7 ++++--- rust/kernel/list/arc.rs | 9 ++++++--- rust/kernel/sync/arc.rs | 15 +++++++++++---- samples/rust/rust_print_main.rs | 18 ++++++++++++++++++ 6 files changed, 43 insertions(+), 11 deletions(-) diff --git a/init/Kconfig b/init/Kconfig index e8d2b5128f87..868ffa922b2c 100644 --- a/init/Kconfig +++ b/init/Kconfig @@ -129,6 +129,9 @@ config CC_HAS_COUNTED_BY # https://github.com/llvm/llvm-project/pull/112636 depends on !(CC_IS_CLANG && CLANG_VERSION < 190103) +config RUSTC_HAS_COERCE_POINTEE + def_bool RUSTC_VERSION >= 108400 + config PAHOLE_VERSION int default $(shell,$(srctree)/scripts/pahole-version.sh $(PAHOLE)) diff --git a/rust/kernel/alloc.rs b/rust/kernel/alloc.rs index f2f7f3a53d29..fc9c9c41cd79 100644 --- a/rust/kernel/alloc.rs +++ b/rust/kernel/alloc.rs @@ -123,7 +123,7 @@ pub mod flags { /// [`Allocator`] is designed to be implemented as a ZST; [`Allocator`] functions do not operate on /// an object instance. /// -/// In order to be able to support `#[derive(SmartPointer)]` later on, we need to avoid a design +/// In order to be able to support `#[derive(CoercePointee)]` later on, we need to avoid a design /// that requires an `Allocator` to be instantiated, hence its functions must not contain any kind /// of `self` parameter. /// diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs index 6063f4a3d9c0..545d1170ee63 100644 --- a/rust/kernel/lib.rs +++ b/rust/kernel/lib.rs @@ -13,11 +13,12 @@ #![no_std] #![feature(arbitrary_self_types)] -#![feature(coerce_unsized)] -#![feature(dispatch_from_dyn)] +#![cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, feature(derive_coerce_pointee))] +#![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(coerce_unsized))] +#![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(dispatch_from_dyn))] +#![cfg_attr(not(CONFIG_RUSTC_HAS_COERCE_POINTEE), feature(unsize))] #![feature(inline_const)] #![feature(lint_reasons)] -#![feature(unsize)] // Ensure conditional compilation based on the kernel configuration works; // otherwise we may silently break things like initcall handling. diff --git a/rust/kernel/list/arc.rs b/rust/kernel/list/arc.rs index 3483d8c232c4..13c50df37b89 100644 --- a/rust/kernel/list/arc.rs +++ b/rust/kernel/list/arc.rs @@ -7,7 +7,7 @@ use crate::alloc::{AllocError, Flags}; use crate::prelude::*; use crate::sync::{Arc, ArcBorrow, UniqueArc}; -use core::marker::{PhantomPinned, Unsize}; +use core::marker::PhantomPinned; use core::ops::Deref; use core::pin::Pin; use core::sync::atomic::{AtomicBool, Ordering}; @@ -159,6 +159,7 @@ pub use impl_list_arc_safe; /// /// [`List`]: crate::list::List #[repr(transparent)] +#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))] pub struct ListArc where T: ListArcSafe + ?Sized, @@ -443,18 +444,20 @@ where // This is to allow coercion from `ListArc` to `ListArc` if `T` can be converted to the // dynamically-sized type (DST) `U`. +#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] impl core::ops::CoerceUnsized> for ListArc where - T: ListArcSafe + Unsize + ?Sized, + T: ListArcSafe + core::marker::Unsize + ?Sized, U: ListArcSafe + ?Sized, { } // This is to allow `ListArc` to be dispatched on when `ListArc` can be coerced into // `ListArc`. +#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] impl core::ops::DispatchFromDyn> for ListArc where - T: ListArcSafe + Unsize + ?Sized, + T: ListArcSafe + core::marker::Unsize + ?Sized, U: ListArcSafe + ?Sized, { } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 9f0b04400e8e..25d2185df4cb 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -26,7 +26,7 @@ use crate::{ use core::{ alloc::Layout, fmt, - marker::{PhantomData, Unsize}, + marker::PhantomData, mem::{ManuallyDrop, MaybeUninit}, ops::{Deref, DerefMut}, pin::Pin, @@ -125,6 +125,8 @@ mod std_vendor; /// let coerced: Arc = obj; /// # Ok::<(), Error>(()) /// ``` +#[repr(transparent)] +#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))] pub struct Arc { ptr: NonNull>, // NB: this informs dropck that objects of type `ArcInner` may be used in ` as @@ -180,10 +182,12 @@ impl ArcInner { // This is to allow coercion from `Arc` to `Arc` if `T` can be converted to the // dynamically-sized type (DST) `U`. -impl, U: ?Sized> core::ops::CoerceUnsized> for Arc {} +#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] +impl, U: ?Sized> core::ops::CoerceUnsized> for Arc {} // This is to allow `Arc` to be dispatched on when `Arc` can be coerced into `Arc`. -impl, U: ?Sized> core::ops::DispatchFromDyn> for Arc {} +#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] +impl, U: ?Sized> core::ops::DispatchFromDyn> for Arc {} // SAFETY: It is safe to send `Arc` to another thread when the underlying `T` is `Sync` because // it effectively means sharing `&T` (which is safe because `T` is `Sync`); additionally, it needs @@ -479,6 +483,8 @@ impl From>> for Arc { /// obj.as_arc_borrow().use_reference(); /// # Ok::<(), Error>(()) /// ``` +#[repr(transparent)] +#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))] pub struct ArcBorrow<'a, T: ?Sized + 'a> { inner: NonNull>, _p: PhantomData<&'a ()>, @@ -486,7 +492,8 @@ pub struct ArcBorrow<'a, T: ?Sized + 'a> { // This is to allow `ArcBorrow` to be dispatched on when `ArcBorrow` can be coerced into // `ArcBorrow`. -impl, U: ?Sized> core::ops::DispatchFromDyn> +#[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))] +impl, U: ?Sized> core::ops::DispatchFromDyn> for ArcBorrow<'_, T> { } diff --git a/samples/rust/rust_print_main.rs b/samples/rust/rust_print_main.rs index 7935b4772ec6..7e8af5f176a3 100644 --- a/samples/rust/rust_print_main.rs +++ b/samples/rust/rust_print_main.rs @@ -34,6 +34,24 @@ fn arc_print() -> Result { // Uses `dbg` to print, will move `c` (for temporary debugging purposes). dbg!(c); + { + // `Arc` can be used to delegate dynamic dispatch and the following is an example. + // Both `i32` and `&str` implement `Display`. This enables us to express a unified + // behaviour, contract or protocol on both `i32` and `&str` into a single `Arc` of + // type `Arc`. + + use core::fmt::Display; + fn arc_dyn_print(arc: &Arc) { + pr_info!("Arc says {arc}"); + } + + let a_i32_display: Arc = Arc::new(42i32, GFP_KERNEL)?; + let a_str_display: Arc = a.clone(); + + arc_dyn_print(&a_i32_display); + arc_dyn_print(&a_str_display); + } + // Pretty-prints the debug formatting with lower-case hexadecimal integers. pr_info!("{:#x?}", a); From c6340da3d254ee491fc113d4dc5566bea7bebdf3 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Wed, 20 Nov 2024 06:46:00 -0500 Subject: [PATCH 25/31] rust: arc: use `NonNull::new_unchecked` There is no need to check (and panic on violations of) the safety requirements on `ForeignOwnable` functions. Avoiding the check is consistent with the implementation of `ForeignOwnable` for `Box`. Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-1-80dbadd00951@gmail.com Signed-off-by: Miguel Ojeda --- rust/kernel/sync/arc.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 25d2185df4cb..2f3156b6aacf 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -349,9 +349,9 @@ impl ForeignOwnable for Arc { } unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> ArcBorrow<'a, T> { - // By the safety requirement of this function, we know that `ptr` came from - // a previous call to `Arc::into_foreign`. - let inner = NonNull::new(ptr as *mut ArcInner).unwrap(); + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner) }; // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive // for the lifetime of the returned value. @@ -359,10 +359,14 @@ impl ForeignOwnable for Arc { } unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner) }; + // SAFETY: By the safety requirement of this function, we know that `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and // holds a reference count increment that is transferrable to us. - unsafe { Self::from_inner(NonNull::new(ptr as _).unwrap()) } + unsafe { Self::from_inner(inner) } } } From aa991a2a819535a0014e1159b455b64e3db87510 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Wed, 20 Nov 2024 06:46:01 -0500 Subject: [PATCH 26/31] rust: types: avoid `as` casts Replace `as` casts with `cast{,_mut}` calls which are a bit safer. In one instance, remove an unnecessary `as` cast without replacement. Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Acked-by: Danilo Krummrich Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-2-80dbadd00951@gmail.com Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/kbox.rs | 8 ++++---- rust/kernel/sync/arc.rs | 9 +++++---- rust/kernel/types.rs | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index 19e227351918..05dd45c4b604 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -356,13 +356,13 @@ where type Borrowed<'a> = &'a T; fn into_foreign(self) -> *const crate::ffi::c_void { - Box::into_raw(self) as _ + Box::into_raw(self).cast() } unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr as _) } + unsafe { Box::from_raw(ptr.cast_mut().cast()) } } unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> &'a T { @@ -380,13 +380,13 @@ where fn into_foreign(self) -> *const crate::ffi::c_void { // SAFETY: We are still treating the box as pinned. - Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }) as _ + Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }).cast() } unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - unsafe { Pin::new_unchecked(Box::from_raw(ptr as _)) } + unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast_mut().cast())) } } unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> Pin<&'a T> { diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 2f3156b6aacf..378925e553ec 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -213,10 +213,11 @@ impl Arc { }; let inner = KBox::new(value, flags)?; + let inner = KBox::leak(inner).into(); // SAFETY: We just created `inner` with a reference count of 1, which is owned by the new // `Arc` object. - Ok(unsafe { Self::from_inner(KBox::leak(inner).into()) }) + Ok(unsafe { Self::from_inner(inner) }) } } @@ -345,13 +346,13 @@ impl ForeignOwnable for Arc { type Borrowed<'a> = ArcBorrow<'a, T>; fn into_foreign(self) -> *const crate::ffi::c_void { - ManuallyDrop::new(self).ptr.as_ptr() as _ + ManuallyDrop::new(self).ptr.as_ptr().cast() } unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> ArcBorrow<'a, T> { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner) }; + let inner = unsafe { NonNull::new_unchecked(ptr.cast_mut().cast::>()) }; // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive // for the lifetime of the returned value. @@ -361,7 +362,7 @@ impl ForeignOwnable for Arc { unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - let inner = unsafe { NonNull::new_unchecked(ptr as *mut ArcInner) }; + let inner = unsafe { NonNull::new_unchecked(ptr.cast_mut().cast::>()) }; // SAFETY: By the safety requirement of this function, we know that `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index ec6457bb3084..318d2140470a 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -434,7 +434,7 @@ impl ARef { /// } /// /// let mut data = Empty {}; - /// let ptr = NonNull::::new(&mut data as *mut _).unwrap(); + /// let ptr = NonNull::::new(&mut data).unwrap(); /// # // SAFETY: TODO. /// let data_ref: ARef = unsafe { ARef::from_raw(ptr) }; /// let raw_ptr: NonNull = ARef::into_raw(data_ref); From 5d385a356f628bd4a1d9f403588272d9626e3245 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Wed, 20 Nov 2024 06:46:02 -0500 Subject: [PATCH 27/31] rust: arc: split unsafe block, add missing comment The new SAFETY comment style is taken from existing comments in `deref` and `drop. Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-3-80dbadd00951@gmail.com Signed-off-by: Miguel Ojeda --- rust/kernel/sync/arc.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 378925e553ec..93eac650146a 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -389,10 +389,14 @@ impl AsRef for Arc { impl Clone for Arc { fn clone(&self) -> Self { + // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is + // safe to dereference it. + let refcount = unsafe { self.ptr.as_ref() }.refcount.get(); + // INVARIANT: C `refcount_inc` saturates the refcount, so it cannot overflow to zero. // SAFETY: By the type invariant, there is necessarily a reference to the object, so it is // safe to increment the refcount. - unsafe { bindings::refcount_inc(self.ptr.as_ref().refcount.get()) }; + unsafe { bindings::refcount_inc(refcount) }; // SAFETY: We just incremented the refcount. This increment is now owned by the new `Arc`. unsafe { Self::from_inner(self.ptr) } From 14686571a914833e38eef0f907202f58df4ffcd2 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Wed, 20 Nov 2024 06:46:03 -0500 Subject: [PATCH 28/31] rust: kernel: change `ForeignOwnable` pointer to mut It is slightly more convenient to operate on mut pointers, and this also properly conveys the desired ownership semantics of the trait. Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Acked-by: Danilo Krummrich Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-4-80dbadd00951@gmail.com [ Reworded title slightly. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/kbox.rs | 16 ++++++++-------- rust/kernel/miscdevice.rs | 2 +- rust/kernel/sync/arc.rs | 10 +++++----- rust/kernel/types.rs | 14 +++++++------- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index 05dd45c4b604..d811edbf9b3b 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -355,17 +355,17 @@ where { type Borrowed<'a> = &'a T; - fn into_foreign(self) -> *const crate::ffi::c_void { + fn into_foreign(self) -> *mut crate::ffi::c_void { Box::into_raw(self).cast() } - unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { + unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - unsafe { Box::from_raw(ptr.cast_mut().cast()) } + unsafe { Box::from_raw(ptr.cast()) } } - unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> &'a T { + unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> &'a T { // SAFETY: The safety requirements of this method ensure that the object remains alive and // immutable for the duration of 'a. unsafe { &*ptr.cast() } @@ -378,18 +378,18 @@ where { type Borrowed<'a> = Pin<&'a T>; - fn into_foreign(self) -> *const crate::ffi::c_void { + fn into_foreign(self) -> *mut crate::ffi::c_void { // SAFETY: We are still treating the box as pinned. Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }).cast() } - unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { + unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast_mut().cast())) } + unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast())) } } - unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> Pin<&'a T> { + unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Pin<&'a T> { // SAFETY: The safety requirements for this function ensure that the object is still alive, // so it is safe to dereference the raw pointer. // The safety requirements of `from_foreign` also ensure that the object remains alive for diff --git a/rust/kernel/miscdevice.rs b/rust/kernel/miscdevice.rs index 9e1b9c0fae9d..b3a6cc50b240 100644 --- a/rust/kernel/miscdevice.rs +++ b/rust/kernel/miscdevice.rs @@ -189,7 +189,7 @@ unsafe extern "C" fn fops_open( }; // SAFETY: The open call of a file owns the private data. - unsafe { (*file).private_data = ptr.into_foreign().cast_mut() }; + unsafe { (*file).private_data = ptr.into_foreign() }; 0 } diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index 93eac650146a..fe334394c328 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -345,24 +345,24 @@ impl Arc { impl ForeignOwnable for Arc { type Borrowed<'a> = ArcBorrow<'a, T>; - fn into_foreign(self) -> *const crate::ffi::c_void { + fn into_foreign(self) -> *mut crate::ffi::c_void { ManuallyDrop::new(self).ptr.as_ptr().cast() } - unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> ArcBorrow<'a, T> { + unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T> { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - let inner = unsafe { NonNull::new_unchecked(ptr.cast_mut().cast::>()) }; + let inner = unsafe { NonNull::new_unchecked(ptr.cast::>()) }; // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive // for the lifetime of the returned value. unsafe { ArcBorrow::new(inner) } } - unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self { + unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. - let inner = unsafe { NonNull::new_unchecked(ptr.cast_mut().cast::>()) }; + let inner = unsafe { NonNull::new_unchecked(ptr.cast::>()) }; // SAFETY: By the safety requirement of this function, we know that `ptr` came from // a previous call to `Arc::into_foreign`, which guarantees that `ptr` is valid and diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index 318d2140470a..f9b398ee31fd 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -29,7 +29,7 @@ pub trait ForeignOwnable: Sized { /// For example, it might be invalid, dangling or pointing to uninitialized memory. Using it in /// any way except for [`ForeignOwnable::from_foreign`], [`ForeignOwnable::borrow`], /// [`ForeignOwnable::try_from_foreign`] can result in undefined behavior. - fn into_foreign(self) -> *const crate::ffi::c_void; + fn into_foreign(self) -> *mut crate::ffi::c_void; /// Borrows a foreign-owned object. /// @@ -37,7 +37,7 @@ pub trait ForeignOwnable: Sized { /// /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. - unsafe fn borrow<'a>(ptr: *const crate::ffi::c_void) -> Self::Borrowed<'a>; + unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'a>; /// Converts a foreign-owned object back to a Rust-owned one. /// @@ -47,7 +47,7 @@ pub trait ForeignOwnable: Sized { /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for /// this object must have been dropped. - unsafe fn from_foreign(ptr: *const crate::ffi::c_void) -> Self; + unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self; /// Tries to convert a foreign-owned object back to a Rust-owned one. /// @@ -58,7 +58,7 @@ pub trait ForeignOwnable: Sized { /// /// `ptr` must either be null or satisfy the safety requirements for /// [`ForeignOwnable::from_foreign`]. - unsafe fn try_from_foreign(ptr: *const crate::ffi::c_void) -> Option { + unsafe fn try_from_foreign(ptr: *mut crate::ffi::c_void) -> Option { if ptr.is_null() { None } else { @@ -72,13 +72,13 @@ pub trait ForeignOwnable: Sized { impl ForeignOwnable for () { type Borrowed<'a> = (); - fn into_foreign(self) -> *const crate::ffi::c_void { + fn into_foreign(self) -> *mut crate::ffi::c_void { core::ptr::NonNull::dangling().as_ptr() } - unsafe fn borrow<'a>(_: *const crate::ffi::c_void) -> Self::Borrowed<'a> {} + unsafe fn borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a> {} - unsafe fn from_foreign(_: *const crate::ffi::c_void) -> Self {} + unsafe fn from_foreign(_: *mut crate::ffi::c_void) -> Self {} } /// Runs a cleanup function/closure when dropped. From c6b97538c2c0f4de5902b5bb78eb89bd34219df9 Mon Sep 17 00:00:00 2001 From: Tamir Duberstein Date: Wed, 20 Nov 2024 06:46:04 -0500 Subject: [PATCH 29/31] rust: kernel: reorder `ForeignOwnable` items `{into,from}_foreign` before `borrow` is slightly more logical. This removes an inconsistency with `kbox.rs` which already uses this ordering. Reviewed-by: Alice Ryhl Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-5-80dbadd00951@gmail.com [ Reworded title slightly. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/sync/arc.rs | 20 ++++++++++---------- rust/kernel/types.rs | 20 ++++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index fe334394c328..e351c701c166 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -349,16 +349,6 @@ impl ForeignOwnable for Arc { ManuallyDrop::new(self).ptr.as_ptr().cast() } - unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T> { - // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous - // call to `Self::into_foreign`. - let inner = unsafe { NonNull::new_unchecked(ptr.cast::>()) }; - - // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive - // for the lifetime of the returned value. - unsafe { ArcBorrow::new(inner) } - } - unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self { // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous // call to `Self::into_foreign`. @@ -369,6 +359,16 @@ impl ForeignOwnable for Arc { // holds a reference count increment that is transferrable to us. unsafe { Self::from_inner(inner) } } + + unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T> { + // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous + // call to `Self::into_foreign`. + let inner = unsafe { NonNull::new_unchecked(ptr.cast::>()) }; + + // SAFETY: The safety requirements of `from_foreign` ensure that the object remains alive + // for the lifetime of the returned value. + unsafe { ArcBorrow::new(inner) } + } } impl Deref for Arc { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index f9b398ee31fd..af316e291908 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -31,14 +31,6 @@ pub trait ForeignOwnable: Sized { /// [`ForeignOwnable::try_from_foreign`] can result in undefined behavior. fn into_foreign(self) -> *mut crate::ffi::c_void; - /// Borrows a foreign-owned object. - /// - /// # Safety - /// - /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for - /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. - unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'a>; - /// Converts a foreign-owned object back to a Rust-owned one. /// /// # Safety @@ -67,6 +59,14 @@ pub trait ForeignOwnable: Sized { unsafe { Some(Self::from_foreign(ptr)) } } } + + /// Borrows a foreign-owned object. + /// + /// # Safety + /// + /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for + /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. + unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'a>; } impl ForeignOwnable for () { @@ -76,9 +76,9 @@ impl ForeignOwnable for () { core::ptr::NonNull::dangling().as_ptr() } - unsafe fn borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a> {} - unsafe fn from_foreign(_: *mut crate::ffi::c_void) -> Self {} + + unsafe fn borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a> {} } /// Runs a cleanup function/closure when dropped. From c27e705cb2b71769dbb4bb1bee1920d2fa01a597 Mon Sep 17 00:00:00 2001 From: Alice Ryhl Date: Wed, 20 Nov 2024 06:46:05 -0500 Subject: [PATCH 30/31] rust: kernel: add improved version of `ForeignOwnable::borrow_mut` Previously, the `ForeignOwnable` trait had a method called `borrow_mut` that was intended to provide mutable access to the inner value. However, the method accidentally made it possible to change the address of the object being modified, which usually isn't what we want. (And when we want that, it can be done by calling `from_foreign` and `into_foreign`, like how the old `borrow_mut` was implemented.) In this patch, we introduce an alternate definition of `borrow_mut` that solves the previous problem. Conceptually, given a pointer type `P` that implements `ForeignOwnable`, the `borrow_mut` method gives you the same kind of access as an `&mut P` would, except that it does not let you change the pointer `P` itself. This is analogous to how the existing `borrow` method provides the same kind of access to the inner value as an `&P`. Note that for types like `Arc`, having an `&mut Arc` only gives you immutable access to the inner `T`. This is because mutable references assume exclusive access, but there might be other handles to the same reference counted value, so the access isn't exclusive. The `Arc` type implements this by making `borrow_mut` return the same type as `borrow`. Signed-off-by: Alice Ryhl Reviewed-by: Boqun Feng Reviewed-by: Benno Lossin Reviewed-by: Martin Rodriguez Reboredo Reviewed-by: Andreas Hindborg Signed-off-by: Tamir Duberstein Acked-by: Danilo Krummrich Link: https://lore.kernel.org/r/20241120-borrow-mut-v6-6-80dbadd00951@gmail.com [ Updated to `crate::ffi::`. Reworded title slightly. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/alloc/kbox.rs | 21 ++++++++++++ rust/kernel/sync/arc.rs | 7 ++++ rust/kernel/types.rs | 71 ++++++++++++++++++++++++++++++++------- 3 files changed, 86 insertions(+), 13 deletions(-) diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs index d811edbf9b3b..cb4ebea3b074 100644 --- a/rust/kernel/alloc/kbox.rs +++ b/rust/kernel/alloc/kbox.rs @@ -354,6 +354,7 @@ where A: Allocator, { type Borrowed<'a> = &'a T; + type BorrowedMut<'a> = &'a mut T; fn into_foreign(self) -> *mut crate::ffi::c_void { Box::into_raw(self).cast() @@ -370,6 +371,13 @@ where // immutable for the duration of 'a. unsafe { &*ptr.cast() } } + + unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> &'a mut T { + let ptr = ptr.cast(); + // SAFETY: The safety requirements of this method ensure that the pointer is valid and that + // nothing else will access the value for the duration of 'a. + unsafe { &mut *ptr } + } } impl ForeignOwnable for Pin> @@ -377,6 +385,7 @@ where A: Allocator, { type Borrowed<'a> = Pin<&'a T>; + type BorrowedMut<'a> = Pin<&'a mut T>; fn into_foreign(self) -> *mut crate::ffi::c_void { // SAFETY: We are still treating the box as pinned. @@ -399,6 +408,18 @@ where // SAFETY: This pointer originates from a `Pin>`. unsafe { Pin::new_unchecked(r) } } + + unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Pin<&'a mut T> { + let ptr = ptr.cast(); + // SAFETY: The safety requirements for this function ensure that the object is still alive, + // so it is safe to dereference the raw pointer. + // The safety requirements of `from_foreign` also ensure that the object remains alive for + // the lifetime of the returned value. + let r = unsafe { &mut *ptr }; + + // SAFETY: This pointer originates from a `Pin>`. + unsafe { Pin::new_unchecked(r) } + } } impl Deref for Box diff --git a/rust/kernel/sync/arc.rs b/rust/kernel/sync/arc.rs index e351c701c166..3cefda7a4372 100644 --- a/rust/kernel/sync/arc.rs +++ b/rust/kernel/sync/arc.rs @@ -344,6 +344,7 @@ impl Arc { impl ForeignOwnable for Arc { type Borrowed<'a> = ArcBorrow<'a, T>; + type BorrowedMut<'a> = Self::Borrowed<'a>; fn into_foreign(self) -> *mut crate::ffi::c_void { ManuallyDrop::new(self).ptr.as_ptr().cast() @@ -369,6 +370,12 @@ impl ForeignOwnable for Arc { // for the lifetime of the returned value. unsafe { ArcBorrow::new(inner) } } + + unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> ArcBorrow<'a, T> { + // SAFETY: The safety requirements for `borrow_mut` are a superset of the safety + // requirements for `borrow`. + unsafe { Self::borrow(ptr) } + } } impl Deref for Arc { diff --git a/rust/kernel/types.rs b/rust/kernel/types.rs index af316e291908..0dfaf45a755c 100644 --- a/rust/kernel/types.rs +++ b/rust/kernel/types.rs @@ -19,26 +19,33 @@ use core::{ /// This trait is meant to be used in cases when Rust objects are stored in C objects and /// eventually "freed" back to Rust. pub trait ForeignOwnable: Sized { - /// Type of values borrowed between calls to [`ForeignOwnable::into_foreign`] and - /// [`ForeignOwnable::from_foreign`]. + /// Type used to immutably borrow a value that is currently foreign-owned. type Borrowed<'a>; + /// Type used to mutably borrow a value that is currently foreign-owned. + type BorrowedMut<'a>; + /// Converts a Rust-owned object to a foreign-owned one. /// /// The foreign representation is a pointer to void. There are no guarantees for this pointer. /// For example, it might be invalid, dangling or pointing to uninitialized memory. Using it in - /// any way except for [`ForeignOwnable::from_foreign`], [`ForeignOwnable::borrow`], - /// [`ForeignOwnable::try_from_foreign`] can result in undefined behavior. + /// any way except for [`from_foreign`], [`try_from_foreign`], [`borrow`], or [`borrow_mut`] can + /// result in undefined behavior. + /// + /// [`from_foreign`]: Self::from_foreign + /// [`try_from_foreign`]: Self::try_from_foreign + /// [`borrow`]: Self::borrow + /// [`borrow_mut`]: Self::borrow_mut fn into_foreign(self) -> *mut crate::ffi::c_void; /// Converts a foreign-owned object back to a Rust-owned one. /// /// # Safety /// - /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for - /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. - /// Additionally, all instances (if any) of values returned by [`ForeignOwnable::borrow`] for - /// this object must have been dropped. + /// The provided pointer must have been returned by a previous call to [`into_foreign`], and it + /// must not be passed to `from_foreign` more than once. + /// + /// [`into_foreign`]: Self::into_foreign unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self; /// Tries to convert a foreign-owned object back to a Rust-owned one. @@ -48,8 +55,9 @@ pub trait ForeignOwnable: Sized { /// /// # Safety /// - /// `ptr` must either be null or satisfy the safety requirements for - /// [`ForeignOwnable::from_foreign`]. + /// `ptr` must either be null or satisfy the safety requirements for [`from_foreign`]. + /// + /// [`from_foreign`]: Self::from_foreign unsafe fn try_from_foreign(ptr: *mut crate::ffi::c_void) -> Option { if ptr.is_null() { None @@ -60,17 +68,53 @@ pub trait ForeignOwnable: Sized { } } - /// Borrows a foreign-owned object. + /// Borrows a foreign-owned object immutably. + /// + /// This method provides a way to access a foreign-owned value from Rust immutably. It provides + /// you with exactly the same abilities as an `&Self` when the value is Rust-owned. /// /// # Safety /// - /// `ptr` must have been returned by a previous call to [`ForeignOwnable::into_foreign`] for - /// which a previous matching [`ForeignOwnable::from_foreign`] hasn't been called yet. + /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if + /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of + /// the lifetime 'a. + /// + /// [`into_foreign`]: Self::into_foreign + /// [`from_foreign`]: Self::from_foreign unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Self::Borrowed<'a>; + + /// Borrows a foreign-owned object mutably. + /// + /// This method provides a way to access a foreign-owned value from Rust mutably. It provides + /// you with exactly the same abilities as an `&mut Self` when the value is Rust-owned, except + /// that the address of the object must not be changed. + /// + /// Note that for types like [`Arc`], an `&mut Arc` only gives you immutable access to the + /// inner value, so this method also only provides immutable access in that case. + /// + /// In the case of `Box`, this method gives you the ability to modify the inner `T`, but it + /// does not let you change the box itself. That is, you cannot change which allocation the box + /// points at. + /// + /// # Safety + /// + /// The provided pointer must have been returned by a previous call to [`into_foreign`], and if + /// the pointer is ever passed to [`from_foreign`], then that call must happen after the end of + /// the lifetime 'a. + /// + /// The lifetime 'a must not overlap with the lifetime of any other call to [`borrow`] or + /// `borrow_mut` on the same object. + /// + /// [`into_foreign`]: Self::into_foreign + /// [`from_foreign`]: Self::from_foreign + /// [`borrow`]: Self::borrow + /// [`Arc`]: crate::sync::Arc + unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Self::BorrowedMut<'a>; } impl ForeignOwnable for () { type Borrowed<'a> = (); + type BorrowedMut<'a> = (); fn into_foreign(self) -> *mut crate::ffi::c_void { core::ptr::NonNull::dangling().as_ptr() @@ -79,6 +123,7 @@ impl ForeignOwnable for () { unsafe fn from_foreign(_: *mut crate::ffi::c_void) -> Self {} unsafe fn borrow<'a>(_: *mut crate::ffi::c_void) -> Self::Borrowed<'a> {} + unsafe fn borrow_mut<'a>(_: *mut crate::ffi::c_void) -> Self::BorrowedMut<'a> {} } /// Runs a cleanup function/closure when dropped. From c80dd3fc45d573458bc763d599d97c82cf5dc212 Mon Sep 17 00:00:00 2001 From: Filipe Xavier Date: Tue, 7 Jan 2025 16:25:39 -0300 Subject: [PATCH 31/31] rust: uaccess: generalize userSliceReader to support any Vec The UserSliceReader::read_all function is currently restricted to use only Vec with the kmalloc allocator. However, there is no reason for this limitation. This patch generalizes the function to accept any Vec regardless of the allocator used. There's a use-case for a KVVec in Binder to avoid maximum sizes for a certain array. Link: https://github.com/Rust-for-Linux/linux/issues/1136 Signed-off-by: Filipe Xavier Reviewed-by: Alice Ryhl Reviewed-by: Boqun Feng Link: https://lore.kernel.org/r/20250107-gen-userslice-readall-alloc-v2-1-d7fe4d19241a@gmail.com [ Reflowed and slightly reworded title. - Miguel ] Signed-off-by: Miguel Ojeda --- rust/kernel/uaccess.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/rust/kernel/uaccess.rs b/rust/kernel/uaccess.rs index cc044924867b..719b0a48ff55 100644 --- a/rust/kernel/uaccess.rs +++ b/rust/kernel/uaccess.rs @@ -5,7 +5,7 @@ //! C header: [`include/linux/uaccess.h`](srctree/include/linux/uaccess.h) use crate::{ - alloc::Flags, + alloc::{Allocator, Flags}, bindings, error::Result, ffi::c_void, @@ -127,7 +127,7 @@ impl UserSlice { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(self, buf: &mut KVec, flags: Flags) -> Result { + pub fn read_all(self, buf: &mut Vec, flags: Flags) -> Result { self.reader().read_all(buf, flags) } @@ -281,7 +281,7 @@ impl UserSliceReader { /// Reads the entirety of the user slice, appending it to the end of the provided buffer. /// /// Fails with [`EFAULT`] if the read happens on a bad address. - pub fn read_all(mut self, buf: &mut KVec, flags: Flags) -> Result { + pub fn read_all(mut self, buf: &mut Vec, flags: Flags) -> Result { let len = self.length; buf.reserve(len, flags)?;