summaryrefslogtreecommitdiff
path: root/rust
AgeCommit message (Collapse)AuthorFilesLines
2023-04-12rust: init: add `PinnedDrop` trait and macrosBenno Lossin5-0/+488
The `PinnedDrop` trait that facilitates destruction of pinned types. It has to be implemented via the `#[pinned_drop]` macro, since the `drop` function should not be called by normal code, only by other destructors. It also only works on structs that are annotated with `#[pin_data(PinnedDrop)]`. Co-developed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Gary Guo <gary@garyguo.net> Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Link: https://lore.kernel.org/r/20230408122429.1103522-10-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: init/sync: add `InPlaceInit` trait to pin-initialize smart pointersBenno Lossin2-13/+139
The `InPlaceInit` trait that provides two functions, for initializing using `PinInit<T, E>` and `Init<T>`. It is implemented by `Arc<T>`, `UniqueArc<T>` and `Box<T>`. Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Link: https://lore.kernel.org/r/20230408122429.1103522-9-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: init: add initialization macrosBenno Lossin6-7/+1747
Add the following initializer macros: - `#[pin_data]` to annotate structurally pinned fields of structs, needed for `pin_init!` and `try_pin_init!` to select the correct initializer of fields. - `pin_init!` create a pin-initializer for a struct with the `Infallible` error type. - `try_pin_init!` create a pin-initializer for a struct with a custom error type (`kernel::error::Error` is the default). - `init!` create an in-place-initializer for a struct with the `Infallible` error type. - `try_init!` create an in-place-initializer for a struct with a custom error type (`kernel::error::Error` is the default). Also add their needed internal helper traits and structs. Co-developed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Gary Guo <gary@garyguo.net> Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Link: https://lore.kernel.org/r/20230408122429.1103522-8-y86-dev@protonmail.com [ Fixed three typos. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: add pin-init API coreBenno Lossin3-0/+226
This API is used to facilitate safe pinned initialization of structs. It replaces cumbersome `unsafe` manual initialization with elegant safe macro invocations. Due to the size of this change it has been split into six commits: 1. This commit introducing the basic public interface: traits and functions to represent and create initializers. 2. Adds the `#[pin_data]`, `pin_init!`, `try_pin_init!`, `init!` and `try_init!` macros along with their internal types. 3. Adds the `InPlaceInit` trait that allows using an initializer to create an object inside of a `Box<T>` and other smart pointers. 4. Adds the `PinnedDrop` trait and adds macro support for it in the `#[pin_data]` macro. 5. Adds the `stack_pin_init!` macro allowing to pin-initialize a struct on the stack. 6. Adds the `Zeroable` trait and `init::zeroed` function to initialize types that have `0x00` in all bytes as a valid bit pattern. -- In this section the problem that the new pin-init API solves is outlined. This message describes the entirety of the API, not just the parts introduced in this commit. For a more granular explanation and additional information on pinning and this issue, view [1]. Pinning is Rust's way of enforcing the address stability of a value. When a value gets pinned it will be impossible for safe code to move it to another location. This is done by wrapping pointers to said object with `Pin<P>`. This wrapper prevents safe code from creating mutable references to the object, preventing mutable access, which is needed to move the value. `Pin<P>` provides `unsafe` functions to circumvent this and allow modifications regardless. It is then the programmer's responsibility to uphold the pinning guarantee. Many kernel data structures require a stable address, because there are foreign pointers to them which would get invalidated by moving the structure. Since these data structures are usually embedded in structs to use them, this pinning property propagates to the container struct. Resulting in most structs in both Rust and C code needing to be pinned. So if we want to have a `mutex` field in a Rust struct, this struct also needs to be pinned, because a `mutex` contains a `list_head`. Additionally initializing a `list_head` requires already having the final memory location available, because it is initialized by pointing it to itself. But this presents another challenge in Rust: values have to be initialized at all times. There is the `MaybeUninit<T>` wrapper type, which allows handling uninitialized memory, but this requires using the `unsafe` raw pointers and a casting the type to the initialized variant. This problem gets exacerbated when considering encapsulation and the normal safety requirements of Rust code. The fields of the Rust `Mutex<T>` should not be accessible to normal driver code. After all if anyone can modify the fields, there is no way to ensure the invariants of the `Mutex<T>` are upheld. But if the fields are inaccessible, then initialization of a `Mutex<T>` needs to be somehow achieved via a function or a macro. Because the `Mutex<T>` must be pinned in memory, the function cannot return it by value. It also cannot allocate a `Box` to put the `Mutex<T>` into, because that is an unnecessary allocation and indirection which would hurt performance. The solution in the rust tree (e.g. this commit: [2]) that is replaced by this API is to split this function into two parts: 1. A `new` function that returns a partially initialized `Mutex<T>`, 2. An `init` function that requires the `Mutex<T>` to be pinned and that fully initializes the `Mutex<T>`. Both of these functions have to be marked `unsafe`, since a call to `new` needs to be accompanied with a call to `init`, otherwise using the `Mutex<T>` could result in UB. And because calling `init` twice also is not safe. While `Mutex<T>` initialization cannot fail, other structs might also have to allocate memory, which would result in conditional successful initialization requiring even more manual accommodation work. Combine this with the problem of pin-projections -- the way of accessing fields of a pinned struct -- which also have an `unsafe` API, pinned initialization is riddled with `unsafe` resulting in very poor ergonomics. Not only that, but also having to call two functions possibly multiple lines apart makes it very easy to forget it outright or during refactoring. Here is an example of the current way of initializing a struct with two synchronization primitives (see [3] for the full example): struct SharedState { state_changed: CondVar, inner: Mutex<SharedStateInner>, } impl SharedState { fn try_new() -> Result<Arc<Self>> { let mut state = Pin::from(UniqueArc::try_new(Self { // SAFETY: `condvar_init!` is called below. state_changed: unsafe { CondVar::new() }, // SAFETY: `mutex_init!` is called below. inner: unsafe { Mutex::new(SharedStateInner { token_count: 0 }) }, })?); // SAFETY: `state_changed` is pinned when `state` is. let pinned = unsafe { state.as_mut().map_unchecked_mut(|s| &mut s.state_changed) }; kernel::condvar_init!(pinned, "SharedState::state_changed"); // SAFETY: `inner` is pinned when `state` is. let pinned = unsafe { state.as_mut().map_unchecked_mut(|s| &mut s.inner) }; kernel::mutex_init!(pinned, "SharedState::inner"); Ok(state.into()) } } The pin-init API of this patch solves this issue by providing a comprehensive solution comprised of macros and traits. Here is the example from above using the pin-init API: #[pin_data] struct SharedState { #[pin] state_changed: CondVar, #[pin] inner: Mutex<SharedStateInner>, } impl SharedState { fn new() -> impl PinInit<Self> { pin_init!(Self { state_changed <- new_condvar!("SharedState::state_changed"), inner <- new_mutex!( SharedStateInner { token_count: 0 }, "SharedState::inner", ), }) } } Notably the way the macro is used here requires no `unsafe` and thus comes with the usual Rust promise of safe code not introducing any memory violations. Additionally it is now up to the caller of `new()` to decide the memory location of the `SharedState`. They can choose at the moment `Arc<T>`, `Box<T>` or the stack. -- The API has the following architecture: 1. Initializer traits `PinInit<T, E>` and `Init<T, E>` that act like closures. 2. Macros to create these initializer traits safely. 3. Functions to allow manually writing initializers. The initializers (an `impl PinInit<T, E>`) receive a raw pointer pointing to uninitialized memory and their job is to fully initialize a `T` at that location. If initialization fails, they return an error (`E`) by value. This way of initializing cannot be safely exposed to the user, since it relies upon these properties outside of the control of the trait: - the memory location (slot) needs to be valid memory, - if initialization fails, the slot should not be read from, - the value in the slot should be pinned, so it cannot move and the memory cannot be deallocated until the value is dropped. This is why using an initializer is facilitated by another trait that ensures these requirements. These initializers can be created manually by just supplying a closure that fulfills the same safety requirements as `PinInit<T, E>`. But this is an `unsafe` operation. To allow safe initializer creation, the `pin_init!` is provided along with three other variants: `try_pin_init!`, `try_init!` and `init!`. These take a modified struct initializer as a parameter and generate a closure that initializes the fields in sequence. The macros take great care in upholding the safety requirements: - A shadowed struct type is used as the return type of the closure instead of `()`. This is to prevent early returns, as these would prevent full initialization. - To ensure every field is only initialized once, a normal struct initializer is placed in unreachable code. The type checker will emit errors if a field is missing or specified multiple times. - When initializing a field fails, the whole initializer will fail and automatically drop fields that have been initialized earlier. - Only the correct initializer type is allowed for unpinned fields. You cannot use a `impl PinInit<T, E>` to initialize a structurally not pinned field. To ensure the last point, an additional macro `#[pin_data]` is needed. This macro annotates the struct itself and the user specifies structurally pinned and not pinned fields. Because dropping a pinned struct is also not allowed to break the pinning invariants, another macro attribute `#[pinned_drop]` is needed. This macro is introduced in a following commit. These two macros also have mechanisms to ensure the overall safety of the API. Additionally, they utilize a combined proc-macro, declarative macro design: first a proc-macro enables the outer attribute syntax `#[...]` and does some important pre-parsing. Notably this prepares the generics such that the declarative macro can handle them using token trees. Then the actual parsing of the structure and the emission of code is handled by a declarative macro. For pin-projections the crates `pin-project` [4] and `pin-project-lite` [5] had been considered, but were ultimately rejected: - `pin-project` depends on `syn` [6] which is a very big dependency, around 50k lines of code. - `pin-project-lite` is a more reasonable 5k lines of code, but contains a very complex declarative macro to parse generics. On top of that it would require modification that would need to be maintained independently. Link: https://rust-for-linux.com/the-safe-pinned-initialization-problem [1] Link: https://github.com/Rust-for-Linux/linux/tree/0a04dc4ddd671efb87eef54dde0fb38e9074f4be [2] Link: https://github.com/Rust-for-Linux/linux/blob/f509ede33fc10a07eba3da14aa00302bd4b5dddd/samples/rust/rust_miscdev.rs [3] Link: https://crates.io/crates/pin-project [4] Link: https://crates.io/crates/pin-project-lite [5] Link: https://crates.io/crates/syn [6] Co-developed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Gary Guo <gary@garyguo.net> Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Link: https://lore.kernel.org/r/20230408122429.1103522-7-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: types: add `Opaque::raw_get`Benno Lossin1-0/+8
This function mirrors `UnsafeCell::raw_get`. It avoids creating a reference and allows solely using raw pointers. The `pin-init` API will be using this, since uninitialized memory requires raw pointers. Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20230408122429.1103522-6-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: sync: change error type of constructor functionsBenno Lossin1-4/+4
Change the error type of the constructors of `Arc` and `UniqueArc` to be `AllocError` instead of `Error`. This makes the API more clear as to what can go wrong when calling `try_new` or its variants. Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Link: https://lore.kernel.org/r/20230408122429.1103522-4-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: macros: add `quote!` macroGary Guo2-0/+147
Add the `quote!` macro for creating `TokenStream`s directly via the given Rust tokens. It also supports repetitions using iterators. It will be used by the pin-init API proc-macros to generate code. Signed-off-by: Gary Guo <gary@garyguo.net> Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20230408122429.1103522-3-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: enable the `pin_macro` featureBenno Lossin1-0/+1
This feature enables the use of the `pin!` macro for the `stack_pin_init!` macro. This feature is already stabilized in Rust version 1.68. Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Link: https://lore.kernel.org/r/20230408122429.1103522-2-y86-dev@protonmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: error: Add from_result() helperWedson Almeida Filho1-0/+39
Add a helper function to easily return C result codes from a Rust function that calls functions which return a Result<T>. Lina: Imported from rust-for-linux/rust, originally developed by Wedson as part of file_operations.rs. Added the allow() flags since there is no user in the kernel crate yet and fixed a typo in a comment. Replaced the macro with a function taking a closure, per discussion on the ML. Co-developed-by: Fox Chen <foxhlchen@gmail.com> Signed-off-by: Fox Chen <foxhlchen@gmail.com> Co-developed-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-error-v3-6-03779bddc02b@asahilina.net Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: error: Add a helper to convert a C ERR_PTR to a `Result`Sven Van Asbroeck2-1/+61
Some kernel C API functions return a pointer which embeds an optional `errno`. Callers are supposed to check the returned pointer with `IS_ERR()` and if this returns `true`, retrieve the `errno` using `PTR_ERR()`. Create a Rust helper function to implement the Rust equivalent: transform a `*mut T` to `Result<*mut T>`. Lina: Imported from rust-for-linux/linux, with subsequent refactoring and contributions squashed in and attributed below. Renamed the function to from_err_ptr(). Co-developed-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Boqun Feng <boqun.feng@gmail.com> Co-developed-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Co-developed-by: Fox Chen <foxhlchen@gmail.com> Signed-off-by: Fox Chen <foxhlchen@gmail.com> Co-developed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Gary Guo <gary@garyguo.net> Signed-off-by: Sven Van Asbroeck <thesven73@gmail.com> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-error-v3-5-03779bddc02b@asahilina.net [ Add a removal of `#[allow(dead_code)]`. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: error: Add to_result() helperWedson Almeida Filho1-1/+10
Add a to_result() helper to convert kernel C return values to a Rust Result, mapping >=0 values to Ok(()) and negative values to Err(...), with Error::from_errno() ensuring that the errno is within range. Lina: Imported from rust-for-linux/rust, originally developed by Wedson as part of the AMBA device driver support. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-error-v3-4-03779bddc02b@asahilina.net [ Add a removal of `#[allow(dead_code)]`. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: error: Add Error::from_errno{_unchecked}()Miguel Ojeda1-0/+32
Add a function to create `Error` values out of a kernel error return, which safely upholds the invariant that the error code is well-formed (negative and greater than -MAX_ERRNO). If a malformed code is passed in, it will be converted to EINVAL. Lina: Imported from rust-for-linux/rust as authored by Miguel and Fox with refactoring from Wedson, renamed from_kernel_errno() to from_errno(). Co-developed-by: Fox Chen <foxhlchen@gmail.com> Signed-off-by: Fox Chen <foxhlchen@gmail.com> Co-developed-by: Wedson Almeida Filho <wedsonaf@gmail.com> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-error-v3-3-03779bddc02b@asahilina.net [ Mark the new associated functions as `#[allow(dead_code)]`. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: error: Add Error::to_ptr()Asahi Lina2-0/+14
This is the Rust equivalent to ERR_PTR(), for use in C callbacks. Marked as #[allow(dead_code)] for now, since it does not have any consumers yet. Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Reviewed-by: Gary Guo <gary@garyguo.net> Link: https://lore.kernel.org/r/20230224-rust-error-v3-2-03779bddc02b@asahilina.net Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: error: Rename to_kernel_errno() -> to_errno()Asahi Lina2-2/+2
This is kernel code, so specifying "kernel" is redundant. Let's simplify things and just call it to_errno(). Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-error-v3-1-03779bddc02b@asahilina.net Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-12rust: sync: arc: Add UniqueArc<MaybeUninit<T>::assume_init()Asahi Lina1-0/+11
We can already create `UniqueArc<MaybeUninit<T>>` instances with `UniqueArc::try_new_uninit()` and write to them with `write()`. Add the missing unsafe `assume_init()` function to promote it to `UniqueArc<T>`, so users can do piece-wise initialization of the contents instead of doing it all at once as long as they keep the invariants (the same requirements as `MaybeUninit::assume_init()`). This mirrors the std `Arc::assume_init()` function. In the kernel, since we have `UniqueArc`, arguably this only belongs there since most use cases will initialize it immediately after creating it, before demoting it to `Arc` to share it. [ Miguel: The "Rust pin-init API for pinned initialization of structs" patch series [1] from Benno Lossin contains a very similar patch: rust: sync: add `assume_init` to `UniqueArc` Adds the `assume_init` function to `UniqueArc<MaybeUninit<T>>` that unsafely assumes the value to be initialized and yields a value of type `UniqueArc<T>`. This function is used when manually initializing the pointee of an `UniqueArc`. To make that patch a noop and thus drop it, I adjusted the `SAFETY` comment here to be the same as in the current latest version of that series (v7). I have also brought the `Reviewed-by`s there into here, and reworded the `Co-authored-by` into `Co-developed-by`. ] Link: https://lore.kernel.org/r/20230408122429.1103522-5-y86-dev@protonmail.com [1] Co-developed-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Asahi Lina <lina@asahilina.net> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Wedson Almeida Filho <walmeida@microsoft.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20230224-rust-arc-v2-2-5c97a865b276@asahilina.net Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-11rust: sync: arc: Implement Arc<dyn Any + Send + Sync>::downcast()Asahi Lina2-0/+30
This mirrors the standard library's alloc::sync::Arc::downcast(). Based on the Rust standard library implementation, ver 1.62.0, licensed under "Apache-2.0 OR MIT", from: https://github.com/rust-lang/rust/tree/1.62.0/library/alloc/src For copyright details, please see: https://github.com/rust-lang/rust/blob/1.62.0/COPYRIGHT Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-arc-v2-1-5c97a865b276@asahilina.net [ Moved `mod std_vendor;` up. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-11rust: macros: Allow specifying multiple module aliasesAsahi Lina2-6/+34
Modules can (and usually do) have multiple alias tags, in order to specify multiple possible device matches for autoloading. Allow this by changing the alias ModuleInfo field to an Option<Vec<String>>. Note: For normal device IDs this is autogenerated by modpost (which is not properly integrated with Rust support yet), so it is useful to be able to manually add device match aliases for now, and should still be useful in the future for corner cases that modpost does not handle. This pulls in the expect_group() helper from the rfl/rust branch (with credit to authors). Co-developed-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Co-developed-by: Finn Behrens <me@kloenk.dev> Signed-off-by: Finn Behrens <me@kloenk.dev> Co-developed-by: Sumera Priyadarsini <sylphrenadin@gmail.com> Signed-off-by: Sumera Priyadarsini <sylphrenadin@gmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-macros-v2-1-7396e8b7018d@asahilina.net Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-11rust: alloc: vec: Add some try_* methods we needMiguel Ojeda2-3/+219
Add some missing fallible methods that we need. They are all marked as: #[stable(feature = "kernel", since = "1.0.0")] for easy identification. Lina: Extracted from commit 487d7578bd03 ("rust: alloc: add some `try_*` methods we need") in rust-for-linux/rust. Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://github.com/Rust-for-Linux/linux/commit/487d7578bd03 Link: https://lore.kernel.org/r/20230224-rust-vec-v1-4-733b5b5a57c5@asahilina.net [ Match the non-fallible methods from version 1.62.0, since those in commit 487d7578bd03 were written for 1.54.0-beta.1. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-11rust: Add SPDX headers to alloc::vec::{spec_extend, set_len_on_drop}Asahi Lina2-0/+4
Add the missing SPDX headers to these modules, which were just imported from the Rust stdlib. Doing this in a separate commit makes it easier to audit that the files have not been modified in the original import. See the preceding two commits for attribution and licensing details. Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-vec-v1-3-733b5b5a57c5@asahilina.net [ Reworded for typo. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-10rust: Import upstream `alloc::vec::spec_extend` moduleAsahi Lina1-0/+87
This is a subset of the Rust standard library `alloc` crate, version 1.62.0, licensed under "Apache-2.0 OR MIT", from: https://github.com/rust-lang/rust/tree/1.62.0/library/alloc/src The file is copied as-is, with no modifications whatsoever (not even adding the SPDX identifiers). For copyright details, please see: https://github.com/rust-lang/rust/blob/1.62.0/COPYRIGHT Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-vec-v1-2-733b5b5a57c5@asahilina.net [ Import version 1.62.0 instead, to match the one in mainline. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-10rust: Import upstream `alloc::vec::set_len_on_drop` moduleAsahi Lina1-0/+28
This is a subset of the Rust standard library `alloc` crate, version 1.62.0, licensed under "Apache-2.0 OR MIT", from: https://github.com/rust-lang/rust/tree/1.62.0/library/alloc/src The file is copied as-is, with no modifications whatsoever (not even adding the SPDX identifiers). For copyright details, please see: https://github.com/rust-lang/rust/blob/1.62.0/COPYRIGHT Signed-off-by: Asahi Lina <lina@asahilina.net> Link: https://lore.kernel.org/r/20230224-rust-vec-v1-1-733b5b5a57c5@asahilina.net [ Import version 1.62.0 instead, to match the one in mainline. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-10rust: Enable the new_uninit feature for kernel and driver cratesAsahi Lina1-0/+1
The unstable new_uninit feature enables various library APIs to create uninitialized containers, such as `Box::assume_init()`. This is necessary to build abstractions that directly initialize memory at the target location, instead of doing copies through the stack. Will be used by the DRM scheduler abstraction in the kernel crate, and by field-wise initialization (e.g. using `place!()` or a future replacement macro which may itself live in `kernel`) in driver crates. Link: https://github.com/Rust-for-Linux/linux/issues/879 Link: https://github.com/Rust-for-Linux/linux/issues/2 Link: https://github.com/rust-lang/rust/issues/63291 Signed-off-by: Asahi Lina <lina@asahilina.net> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Link: https://lore.kernel.org/r/20230224-rust-new_uninit-v1-1-c951443d9e26@asahilina.net [ Reworded to use `Link` tags. ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-10rust: sync: impl {Debug,Display} for {Unique,}ArcBoqun Feng1-0/+25
This allows printing the inner data of `Arc` and its friends if the inner data implements `Display` or `Debug`. It's useful for logging and debugging purpose. Signed-off-by: Boqun Feng <boqun.feng@gmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Reviewed-by: Björn Roy Baron <bjorn3_gh@protonmail.com> Link: https://lore.kernel.org/r/20230207185216.1314638-2-boqun.feng@gmail.com Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-07rust: build: Fix grep warningVincenzo Palazzo1-1/+1
Fix grep warning during the build, with GNU grep 3.8 with the following command `grep -v '^\#\|^$$' rust/bindgen_parameters` I see the following warning ``` grep: warning: stray \ before # --opaque-type xregs_state --opaque-type desc_struct --opaque-type arch_lbr_state --opaque-type local_apic --opaque-type x86_msi_data --opaque-type x86_msi_addr_lo --opaque-type kunit_try_catch --opaque-type spinlock --no-doc-comments ``` Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Tested-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-07rust: kernel: Mark rust_fmt_argument as extern "C"David Gow1-1/+5
The rust_fmt_argument function is called from printk() to handle the %pA format specifier. Since it's called from C, we should mark it extern "C" to make sure it's ABI compatible. Cc: stable@vger.kernel.org Fixes: 247b365dc8dc ("rust: add `kernel` crate") Signed-off-by: David Gow <davidgow@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Björn Roy Baron <bjorn3_gh@protonmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> [Applied `rustfmt`] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-04-06rust: str: fix requierments->requirements typoPatrick Blass1-1/+1
Fix a trivial spelling error in the `rust/kernel/str.rs` file. Fixes: 247b365dc8dc ("rust: add `kernel` crate") Reported-by: Miguel Ojeda <ojeda@kernel.org> Link: https://github.com/Rust-for-Linux/linux/issues/978 Signed-off-by: Patrick Blass <patrickblass@mailbox.org> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> [Reworded slightly] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-03-04Merge tag 'rust-fixes-6.3-rc1' of https://github.com/Rust-for-Linux/linuxLinus Torvalds1-0/+1
Pull Rust fix from Miguel Ojeda: "A single build error fix: there was a change during the merge window to a C header parsed by the Rust bindings generator, introducing a type that it does not handle well. The fix tells the generator to treat the type as opaque (for now)" * tag 'rust-fixes-6.3-rc1' of https://github.com/Rust-for-Linux/linux: rust: bindgen: Add `alt_instr` as opaque type
2023-03-03rust: bindgen: Add `alt_instr` as opaque typeArnaldo Carvalho de Melo1-0/+1
To address this build error: BINDGEN rust/bindings/bindings_generated.rs BINDGEN rust/bindings/bindings_helpers_generated.rs EXPORTS rust/exports_core_generated.h RUSTC P rust/libmacros.so RUSTC L rust/compiler_builtins.o RUSTC L rust/alloc.o RUSTC L rust/bindings.o RUSTC L rust/build_error.o EXPORTS rust/exports_alloc_generated.h error[E0588]: packed type cannot transitively contain a `#[repr(align)]` type --> /var/home/acme/git/linux/rust/bindings/bindings_generated.rs:10094:1 | 10094 | / pub struct alt_instr { 10095 | | pub instr_offset: s32, 10096 | | pub repl_offset: s32, 10097 | | pub __bindgen_anon_1: alt_instr__bindgen_ty_1, 10098 | | pub instrlen: u8_, 10099 | | pub replacementlen: u8_, 10100 | | } | |_^ | note: `alt_instr__bindgen_ty_1__bindgen_ty_1` has a `#[repr(align)]` attribute --> /var/home/acme/git/linux/rust/bindings/bindings_generated.rs:10111:1 | 10111 | / pub struct alt_instr__bindgen_ty_1__bindgen_ty_1 { 10112 | | pub _bitfield_1: __BindgenBitfieldUnit<[u8; 4usize], u16>, 10113 | | } | |_^ note: `alt_instr` contains a field of type `alt_instr__bindgen_ty_1` --> /var/home/acme/git/linux/rust/bindings/bindings_generated.rs:10097:9 | 10097 | pub __bindgen_anon_1: alt_instr__bindgen_ty_1, | ^^^^^^^^^^^^^^^^ note: ...which contains a field of type `alt_instr__bindgen_ty_1__bindgen_ty_1` --> /var/home/acme/git/linux/rust/bindings/bindings_generated.rs:10104:9 | 10104 | pub __bindgen_anon_1: alt_instr__bindgen_ty_1__bindgen_ty_1, | ^^^^^^^^^^^^^^^^ error: aborting due to previous error For more information about this error, try `rustc --explain E0588`. make[1]: *** [rust/Makefile:389: rust/bindings.o] Error 1 make: *** [Makefile:1293: prepare] Error 2 Cc: Derek Barbosa <debarbos@redhat.com> Cc: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Arnaldo Carvalho de Melo <acme@redhat.com> Fixes: 5d1dd961e743 ("x86/alternatives: Add alt_instr.flags") Reported-by: kernel test robot <lkp@intel.com> Reported-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-02-26Merge tag 'kbuild-v6.3' of ↵Linus Torvalds2-20/+8
git://git.kernel.org/pub/scm/linux/kernel/git/masahiroy/linux-kbuild Pull Kbuild updates from Masahiro Yamada: - Change V=1 option to print both short log and full command log - Allow V=1 and V=2 to be combined as V=12 - Make W=1 detect wrong .gitignore files - Tree-wide cleanups for unused command line arguments passed to Clang - Stop using -Qunused-arguments with Clang - Make scripts/setlocalversion handle only correct release tags instead of any arbitrary annotated tag - Create Debian and RPM source packages without cleaning the source tree - Various cleanups for packaging * tag 'kbuild-v6.3' of git://git.kernel.org/pub/scm/linux/kernel/git/masahiroy/linux-kbuild: (74 commits) kbuild: rpm-pkg: remove unneeded KERNELRELEASE from modules/headers_install docs: kbuild: remove description of KBUILD_LDS_MODULE .gitattributes: use 'dts' diff driver for *.dtso files kbuild: deb-pkg: improve the usability of source package kbuild: deb-pkg: fix binary-arch and clean in debian/rules kbuild: tar-pkg: use tar rules in scripts/Makefile.package kbuild: make perf-tar*-src-pkg work without relying on git kbuild: deb-pkg: switch over to source format 3.0 (quilt) kbuild: deb-pkg: make .orig tarball a hard link if possible kbuild: deb-pkg: hide KDEB_SOURCENAME from Makefile kbuild: srcrpm-pkg: create source package without cleaning kbuild: rpm-pkg: build binary packages from source rpm kbuild: deb-pkg: create source package without cleaning kbuild: add a tool to list files ignored by git Documentation/llvm: add Chimera Linux, Google and Meta datacenters setlocalversion: use only the correct release tag for git-describe setlocalversion: clean up the construction of version output .gitignore: ignore *.cover and *.mbx kbuild: remove --include-dir MAKEFLAG from top Makefile kbuild: fix trivial typo in comment ...
2023-02-20Merge tag 'rust-6.3' of https://github.com/Rust-for-Linux/linuxLinus Torvalds13-502/+806
Pull Rust updates from Miguel Ojeda: "More core additions, getting closer to a point where the first Rust modules can be upstreamed. The major ones being: - Sync: new types 'Arc', 'ArcBorrow' and 'UniqueArc'. - Types: new trait 'ForeignOwnable' and new type 'ScopeGuard'. There is also a substantial removal in terms of lines: - 'alloc' crate: remove the 'borrow' module (type 'Cow' and trait 'ToOwned')" * tag 'rust-6.3' of https://github.com/Rust-for-Linux/linux: rust: delete rust-project.json when running make clean rust: MAINTAINERS: Add the zulip link rust: types: implement `ForeignOwnable` for `Arc<T>` rust: types: implement `ForeignOwnable` for the unit type rust: types: implement `ForeignOwnable` for `Box<T>` rust: types: introduce `ForeignOwnable` rust: types: introduce `ScopeGuard` rust: prelude: prevent doc inline of external imports rust: sync: add support for dispatching on Arc and ArcBorrow. rust: sync: introduce `UniqueArc` rust: sync: allow type of `self` to be `ArcBorrow<T>` rust: sync: introduce `ArcBorrow` rust: sync: allow coercion from `Arc<T>` to `Arc<U>` rust: sync: allow type of `self` to be `Arc<T>` or variants rust: sync: add `Arc` for ref-counted allocations rust: compiler_builtins: make stubs non-global rust: alloc: remove the `borrow` module (`ToOwned`, `Cow`)
2023-02-07rust: types: implement `ForeignOwnable` for `Arc<T>`Wedson Almeida Filho1-1/+31
This allows us to hand ownership of Rust ref-counted objects to the C side of the kernel. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Alice Ferrazzi <alice.ferrazzi@miraclelinux.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-02-01rust: types: implement `ForeignOwnable` for the unit typeWedson Almeida Filho1-0/+12
This allows us to use the unit type `()` when we have no object whose ownership must be managed but one implementing the `ForeignOwnable` trait is needed. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-02-01rust: types: implement `ForeignOwnable` for `Box<T>`Wedson Almeida Filho1-0/+23
This allows us to hand ownership of Rust dynamically allocated objects to the C side of the kernel. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Alice Ferrazzi <alice.ferrazzi@miraclelinux.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-02-01rust: types: introduce `ForeignOwnable`Wedson Almeida Filho2-0/+55
It was originally called `PointerWrapper`. It is used to convert a Rust object to a pointer representation (void *) that can be stored on the C side, used, and eventually returned to Rust. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-02-01rust: types: introduce `ScopeGuard`Wedson Almeida Filho1-1/+125
This allows us to run some code when the guard is dropped (e.g., implicitly when it goes out of scope). We can also prevent the guard from running by calling its `dismiss()` method. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@samsung.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-22kbuild: rust: move rust/target.json to scripts/Masahiro Yamada2-10/+1
scripts/ is a better place to generate files used treewide. With target.json moved to scripts/, you do not need to add target.json to no-clean-files or MRPROPER_FILES. 'make clean' does not visit scripts/, but 'make mrproper' does. Signed-off-by: Masahiro Yamada <masahiroy@kernel.org> Reviewed-by: Miguel Ojeda <ojeda@kernel.org> Tested-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-22kbuild: remove sed commands after rustc rulesMasahiro Yamada1-4/+2
rustc may put comments in dep-info, so sed is used to drop them before passing it to fixdep. Now that fixdep can remove comments, Makefiles do not need to run sed. Signed-off-by: Masahiro Yamada <masahiroy@kernel.org> Reviewed-by: Miguel Ojeda <ojeda@kernel.org> Tested-by: Miguel Ojeda <ojeda@kernel.org> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-01-22kbuild: specify output names separately for each emission type from rustcMasahiro Yamada1-6/+5
In Kbuild, two different rules must not write to the same file, but it happens when compiling rust source files. For example, set CONFIG_SAMPLE_RUST_MINIMAL=m and run the following: $ make -j$(nproc) samples/rust/rust_minimal.o samples/rust/rust_minimal.rsi \ samples/rust/rust_minimal.s samples/rust/rust_minimal.ll [snip] RUSTC [M] samples/rust/rust_minimal.o RUSTC [M] samples/rust/rust_minimal.rsi RUSTC [M] samples/rust/rust_minimal.s RUSTC [M] samples/rust/rust_minimal.ll mv: cannot stat 'samples/rust/rust_minimal.d': No such file or directory make[3]: *** [scripts/Makefile.build:334: samples/rust/rust_minimal.ll] Error 1 make[3]: *** Waiting for unfinished jobs.... mv: cannot stat 'samples/rust/rust_minimal.d': No such file or directory make[3]: *** [scripts/Makefile.build:309: samples/rust/rust_minimal.o] Error 1 mv: cannot stat 'samples/rust/rust_minimal.d': No such file or directory make[3]: *** [scripts/Makefile.build:326: samples/rust/rust_minimal.s] Error 1 make[2]: *** [scripts/Makefile.build:504: samples/rust] Error 2 make[1]: *** [scripts/Makefile.build:504: samples] Error 2 make: *** [Makefile:2008: .] Error 2 The reason for the error is that 4 threads running in parallel renames the same file, samples/rust/rust_minimal.d. This does not happen when compiling C or assembly files because -Wp,-MMD,$(depfile) explicitly specifies the dependency filepath. $(depfile) is a unique path for each target. Currently, rustc is only given --out-dir and --emit=<list-of-types> So, all the rust build rules output the dep-info into the default <CRATE_NAME>.d, which causes the path conflict. Fortunately, the --emit option is able to specify the output path individually, with the form --emit=<type>=<path>. Add --emit=dep-info=$(depfile) to the common part. Also, remove the redundant --out-dir because the output path is specified for each type. The code gets much cleaner because we do not need to rename *.d files. Signed-off-by: Masahiro Yamada <masahiroy@kernel.org> Reviewed-by: Miguel Ojeda <ojeda@kernel.org> Tested-by: Miguel Ojeda <ojeda@kernel.org> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-01-17rust: prelude: prevent doc inline of external importsFinn Behrens1-1/+7
This shows exactly where the items are from, previously the items from macros, alloc and core were shown as a declaration from the kernel crate, this shows the correct path. Link: https://github.com/rust-lang/rust/issues/106713 Signed-off-by: Finn Behrens <fin@nyantec.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> [Reworded to add Link, fixed two typos and comment style] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: add support for dispatching on Arc and ArcBorrow.Wedson Almeida Filho2-2/+19
Trait objects (`dyn T`) require trait `T` to be "object safe". One of the requirements for "object safety" is that the receiver have one of the allowed types. This commit adds `Arc<T>` and `ArcBorrow<'_, T>` to the list of allowed types. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: introduce `UniqueArc`Wedson Almeida Filho2-3/+151
Since `Arc<T>` does not allow mutating `T` directly (i.e., without inner mutability), it is currently not possible to do some initialisation of `T` post construction but before being shared. `UniqueArc<T>` addresses this problem essentially being an `Arc<T>` that has a refcount of 1 and is therefore writable. Once initialisation is completed, it can be transitioned (without failure paths) into an `Arc<T>`. Suggested-by: Gary Guo <gary@garyguo.net> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: allow type of `self` to be `ArcBorrow<T>`Wedson Almeida Filho1-0/+23
This allows associated functions whose `self` argument has `ArcBorrow<T>` as their type. This, in turn, allows callers to use the dot syntax to make calls. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: introduce `ArcBorrow`Wedson Almeida Filho2-1/+98
This allows us to create references to a ref-counted allocation without double-indirection and that still allow us to increment the refcount to a new `Arc<T>`. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: allow coercion from `Arc<T>` to `Arc<U>`Wedson Almeida Filho2-1/+28
The coercion is only allowed if `U` is a compatible dynamically-sized type (DST). For example, if we have some type `X` that implements trait `Y`, then this allows `Arc<X>` to be coerced into `Arc<dyn Y>`. Suggested-by: Gary Guo <gary@garyguo.net> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: allow type of `self` to be `Arc<T>` or variantsWedson Almeida Filho2-0/+29
This allows associated functions whose `self` argument has `Arc<T>` or variants as their type. This, in turn, allows callers to use the dot syntax to make calls. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-17rust: sync: add `Arc` for ref-counted allocationsWedson Almeida Filho6-0/+189
This is a basic implementation of `Arc` backed by C's `refcount_t`. It allows Rust code to idiomatically allocate memory that is ref-counted. Cc: Will Deacon <will@kernel.org> Cc: Peter Zijlstra <peterz@infradead.org> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Mark Rutland <mark.rutland@arm.com> Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com> Acked-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-16rust: compiler_builtins: make stubs non-globalGary Guo2-1/+18
Currently we define a number of stubs for compiler-builtin intrinsics that compiled libcore generates. The defined stubs are weak so they will not conflict with genuine implementation of these intrinsics, but their effect is global and will cause non-libcore code that accidently generate these intrinsics calls compile and bug on runtime. Instead of defining a stub that can affect all code, this patch uses objcopy's `--redefine-sym` flag to redirect these calls (from libcore only) to a prefixed version (e.g. redirect `__multi3` to `__rust_multi3`), so we can define panciking stubs that are only visible to libcore. This patch was previously discussed on GitHub [1]. This approach was also independently proposed by Nick Desaulniers in [2]. Link: https://github.com/Rust-for-Linux/linux/pull/779 [1] Link: https://lore.kernel.org/lkml/CAKwvOdkc0Qhwu=gfe1+H23TnAa6jnO6A3ZCO687dH6mSrATmDA@mail.gmail.com/ Suggested-by: Nick Desaulniers <ndesaulniers@google.com> Acked-by: Nick Desaulniers <ndesaulniers@google.com> Signed-off-by: Gary Guo <gary@garyguo.net> Reviewed-by: Wei Liu <wei.liu@kernel.org> Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2023-01-16rust: alloc: remove the `borrow` module (`ToOwned`, `Cow`)Miguel Ojeda4-499/+6
The `Cow` type [1] requires that its generic parameter type implements the `ToOwned` trait [2], which provides a method to create owned data from borrowed data, usually by cloning. However, it is infallible, and thus in most cases it is not useful for the kernel. [3] Therefore, introduce `cfg(no_borrow)` to remove the `borrow` module (which contains `ToOwned` and `Cow`) from `alloc`. Link: https://doc.rust-lang.org/alloc/borrow/enum.Cow.html [1] Link: https://doc.rust-lang.org/alloc/borrow/trait.ToOwned.html [2] Link: https://lore.kernel.org/rust-for-linux/20221204103153.117675b1@GaryWorkstation/ [3] Cc: Gary Guo <gary@garyguo.net> Cc: Wedson Almeida Filho <wedsonaf@gmail.com> Cc: Josh Triplett <josh@joshtriplett.org> Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Reviewed-by: Wei Liu <wei.liu@kernel.org> Reviewed-by: Finn Behrens <fin@nyantec.com>
2023-01-16rust: print: avoid evaluating arguments in `pr_*` macros in `unsafe` blocksMiguel Ojeda1-11/+18
At the moment it is possible to perform unsafe operations in the arguments of `pr_*` macros since they are evaluated inside an `unsafe` block: let x = &10u32 as *const u32; pr_info!("{}", *x); In other words, this is a soundness issue. Fix it so that it requires an explicit `unsafe` block. Reported-by: Wedson Almeida Filho <wedsonaf@gmail.com> Reported-by: Domen Puncer Kugler <domen.puncerkugler@nccgroup.com> Link: https://github.com/Rust-for-Linux/linux/issues/479 Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Reviewed-by: Boqun Feng <boqun.feng@gmail.com> Reviewed-by: Gary Guo <gary@garyguo.net> Reviewed-by: Björn Roy Baron <bjorn3_gh@protonmail.com> Reviewed-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2022-12-04rust: types: add `Opaque` typeWedson Almeida Filho1-0/+25
Add the `Opaque` type, which is meant to be used with FFI objects that are never interpreted by Rust code, e.g.: struct Waiter { completion: Opaque<bindings::completion>, next: *mut Waiter, } It has the advantage that the objects don't have to be zero-initialised before calling their init functions, making the code performance closer to C. Signed-off-by: Wedson Almeida Filho <wedsonaf@gmail.com> [Reworded, adapted for upstream and applied latest changes] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>