summaryrefslogtreecommitdiff
path: root/rust/kernel/platform.rs
AgeCommit message (Collapse)Author
7 hoursMerge tag 'rust-6.17' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux Pull Rust updates from Miguel Ojeda: "Toolchain and infrastructure: - Enable a set of Clippy lints: 'ptr_as_ptr', 'ptr_cast_constness', 'as_ptr_cast_mut', 'as_underscore', 'cast_lossless' and 'ref_as_ptr' These are intended to avoid type casts with the 'as' operator, which are quite powerful, into restricted variants that are less powerful and thus should help to avoid mistakes - Remove the 'author' key now that most instances were moved to the plural one in the previous cycle 'kernel' crate: - New 'bug' module: add 'warn_on!' macro which reuses the existing 'BUG'/'WARN' infrastructure, i.e. it respects the usual sysctls and kernel parameters: warn_on!(value == 42); To avoid duplicating the assembly code, the same strategy is followed as for the static branch code in order to share the assembly between both C and Rust This required a few rearrangements on C arch headers -- the existing C macros should still generate the same outputs, thus no functional change expected there - 'workqueue' module: add delayed work items, including a 'DelayedWork' struct, a 'impl_has_delayed_work!' macro and an 'enqueue_delayed' method, e.g.: /// Enqueue the struct for execution on the system workqueue, /// where its value will be printed 42 jiffies later. fn print_later(value: Arc<MyStruct>) { let _ = workqueue::system().enqueue_delayed(value, 42); } - New 'bits' module: add support for 'bit' and 'genmask' functions, with runtime- and compile-time variants, e.g.: static_assert!(0b00010000 == bit_u8(4)); static_assert!(0b00011110 == genmask_u8(1..=4)); assert!(checked_bit_u32(u32::BITS).is_none()); - 'uaccess' module: add 'UserSliceReader::strcpy_into_buf', which reads NUL-terminated strings from userspace into a '&CStr' Introduce 'UserPtr' newtype, similar in purpose to '__user' in C, to minimize mistakes handling userspace pointers, including mixing them up with integers and leaking them via the 'Debug' trait. Add it to the prelude, too - Start preparations for the replacement of our custom 'CStr' type with the analogous type in the 'core' standard library. This will take place across several cycles to make it easier. For this one, it includes a new 'fmt' module, using upstream method names and some other cleanups Replace 'fmt!' with a re-export, which helps Clippy lint properly, and clean up the found 'uninlined-format-args' instances - 'dma' module: - Clarify wording and be consistent in 'coherent' nomenclature - Convert the 'read!()' and 'write!()' macros to return a 'Result' - Add 'as_slice()', 'write()' methods in 'CoherentAllocation' - Expose 'count()' and 'size()' in 'CoherentAllocation' and add the corresponding type invariants - Implement 'CoherentAllocation::dma_handle_with_offset()' - 'time' module: - Make 'Instant' generic over clock source. This allows the compiler to assert that arithmetic expressions involving the 'Instant' use 'Instants' based on the same clock source - Make 'HrTimer' generic over the timer mode. 'HrTimer' timers take a 'Duration' or an 'Instant' when setting the expiry time, depending on the timer mode. With this change, the compiler can check the type matches the timer mode - Add an abstraction for 'fsleep'. 'fsleep' is a flexible sleep function that will select an appropriate sleep method depending on the requested sleep time - Avoid 64-bit divisions on 32-bit hardware when calculating timestamps - Seal the 'HrTimerMode' trait. This prevents users of the 'HrTimerMode' from implementing the trait on their own types - Pass the correct timer mode ID to 'hrtimer_start_range_ns()' - 'list' module: remove 'OFFSET' constants, allowing to remove pointer arithmetic; now 'impl_list_item!' invokes 'impl_has_list_links!' or 'impl_has_list_links_self_ptr!'. Other simplifications too - 'types' module: remove 'ForeignOwnable::PointedTo' in favor of a constant, which avoids exposing the type of the opaque pointer, and require 'into_foreign' to return non-null Remove the 'Either<L, R>' type as well. It is unused, and we want to encourage the use of custom enums for concrete use cases - 'sync' module: implement 'Borrow' and 'BorrowMut' for 'Arc' types to allow them to be used in generic APIs - 'alloc' module: implement 'Borrow' and 'BorrowMut' for 'Box<T, A>'; and 'Borrow', 'BorrowMut' and 'Default' for 'Vec<T, A>' - 'Opaque' type: add 'cast_from' method to perform a restricted cast that cannot change the inner type and use it in callers of 'container_of!'. Rename 'raw_get' to 'cast_into' to match it - 'rbtree' module: add 'is_empty' method - 'sync' module: new 'aref' submodule to hold 'AlwaysRefCounted' and 'ARef', which are moved from the too general 'types' module which we want to reduce or eventually remove. Also fix a safety comment in 'static_lock_class' 'pin-init' crate: - Add 'impl<T, E> [Pin]Init<T, E> for Result<T, E>', so results are now (pin-)initializers - Add 'Zeroable::init_zeroed()' that delegates to 'init_zeroed()' - New 'zeroed()', a safe version of 'mem::zeroed()' and also provide it via 'Zeroable::zeroed()' - Implement 'Zeroable' for 'Option<&T>', 'Option<&mut T>' and for 'Option<[unsafe] [extern "abi"] fn(...args...) -> ret>' for '"Rust"' and '"C"' ABIs and up to 20 arguments - Changed blanket impls of 'Init' and 'PinInit' from 'impl<T, E> [Pin]Init<T, E> for T' to 'impl<T> [Pin]Init<T> for T' - Renamed 'zeroed()' to 'init_zeroed()' - Upstream dev news: improve CI more to deny warnings, use '--all-targets'. Check the synchronization status of the two '-next' branches in upstream and the kernel MAINTAINERS: - Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo Stoakes as reviewers (thanks everyone) And a few other cleanups and improvements" * tag 'rust-6.17' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux: (76 commits) rust: Add warn_on macro arm64/bug: Add ARCH_WARN_ASM macro for BUG/WARN asm code sharing with Rust riscv/bug: Add ARCH_WARN_ASM macro for BUG/WARN asm code sharing with Rust x86/bug: Add ARCH_WARN_ASM macro for BUG/WARN asm code sharing with Rust rust: kernel: move ARef and AlwaysRefCounted to sync::aref rust: sync: fix safety comment for `static_lock_class` rust: types: remove `Either<L, R>` rust: kernel: use `core::ffi::CStr` method names rust: str: add `CStr` methods matching `core::ffi::CStr` rust: str: remove unnecessary qualification rust: use `kernel::{fmt,prelude::fmt!}` rust: kernel: add `fmt` module rust: kernel: remove `fmt!`, fix clippy::uninlined-format-args scripts: rust: emit path candidates in panic message scripts: rust: replace length checks with match rust: list: remove nonexistent generic parameter in link rust: bits: add support for bits/genmask macros rust: list: remove OFFSET constants rust: list: add `impl_list_item!` examples rust: list: use fully qualified path ...
2025-07-20rust: platform: add resource accessorsDaniel Almeida
The previous patches have added the abstractions for Resources and the ability to map them and therefore read and write the underlying memory . The only thing missing to make this accessible for platform devices is to provide accessors that return instances of IoRequest<'a>. These ensure that the resource are valid only for the lifetime of the platform device, and that the platform device is in the Bound state. Therefore, add these accessors. Also make it possible to retrieve resources from platform devices in Rust using either a name or an index. Acked-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com> Link: https://lore.kernel.org/r/20250717-topics-tyr-platform_iomem-v15-3-beca780b77e3@collabora.com [ Remove #[expect(dead_code)] from IoRequest::new() and move SAFETY comments right on top of unsafe blocks to avoid clippy warnings for some (older) clippy versions. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-19rust: platform: implement the `dma::Device` traitDanilo Krummrich
The platform bus is potentially capable of performing DMA, hence implement the `dma:Device` trait for `platform::Device`. Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Link: https://lore.kernel.org/r/20250716150354.51081-5-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-16device: rust: rename Device::as_ref() to Device::from_raw()Alice Ryhl
The prefix as_* should not be used for a constructor. Constructors usually use the prefix from_* instead. Some prior art in the stdlib: Box::from_raw, CString::from_raw, Rc::from_raw, Arc::from_raw, Waker::from_raw, File::from_raw_fd. There is also prior art in the kernel crate: cpufreq::Policy::from_raw, fs::File::from_raw_file, Kuid::from_raw, ARef::from_raw, SeqFile::from_raw, VmaNew::from_raw, Io::from_raw. Link: https://lore.kernel.org/r/aCd8D5IA0RXZvtcv@pollux Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <lossin@kernel.org> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Link: https://lore.kernel.org/r/20250711-device-as-ref-v2-1-1b16ab6402d7@google.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-14rust: types: add FOREIGN_ALIGN to ForeignOwnableAndreas Hindborg
The current implementation of `ForeignOwnable` is leaking the type of the opaque pointer to consumers of the API. This allows consumers of the opaque pointer to rely on the information that can be extracted from the pointer type. To prevent this, change the API to the version suggested by Maira Canal (link below): Remove `ForeignOwnable::PointedTo` in favor of a constant, which specifies the alignment of the pointers returned by `into_foreign`. With this change, `ArcInner` no longer needs `pub` visibility, so change it to private. Suggested-by: Alice Ryhl <aliceryhl@google.com> Suggested-by: Maíra Canal <mcanal@igalia.com> Link: https://lore.kernel.org/r/20240309235927.168915-3-mcanal@igalia.com Acked-by: Danilo Krummrich <dakr@kernel.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250612-pointed-to-v3-1-b009006d86a1@kernel.org Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-09rust: platform: implement Driver::unbind()Danilo Krummrich
Currently, there's really only one core callback for drivers, which is probe(). Now, this isn't entirely true, since there is also the drop() callback of the driver type (serving as the driver's private data), which is returned by probe() and is dropped in remove(). On the C side remove() mainly serves two purposes: (1) Tear down the device that is operated by the driver, e.g. call bus specific functions, write I/O memory to reset the device, etc. (2) Free the resources that have been allocated by a driver for a specific device. The drop() callback mentioned above is intended to cover (2) as the Rust idiomatic way. However, it is partially insufficient and inefficient to cover (1) properly, since drop() can't be called with additional arguments, such as the reference to the corresponding device that has the correct device context, i.e. the Core device context. This makes it inefficient (but not impossible) to access device resources, e.g. to write device registers, and impossible to call device methods, which are only accessible under the Core device context. In order to solve this, add an additional callback for (1), which we call unbind(). The reason for calling it unbind() is that, unlike remove(), it is *only* meant to be used to perform teardown operations on the device (1), but *not* to release resources (2). Link: https://lore.kernel.org/r/20250621195118.124245-7-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-09rust: platform: use generic device drvdata accessorsDanilo Krummrich
Take advantage of the generic drvdata accessors of the generic Device type. While at it, use from_result() instead of match. Link: https://lore.kernel.org/r/20250621195118.124245-4-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-05rust: platform: remove unnecessary importTamir Duberstein
`kernel::str::CStr` is included in the prelude. Signed-off-by: Tamir Duberstein <tamird@gmail.com> Link: https://lore.kernel.org/r/20250704-cstr-include-platform-v1-1-ff7803ee7a81@gmail.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-26rust: platform: Add ACPI match table support to `Driver` traitIgor Korotin
Extend the `platform::Driver` trait to support ACPI device matching by adding the `ACPI_ID_TABLE` constant. This allows Rust platform drivers to define ACPI match tables alongside their existing OF match tables. These changes mirror the existing OF support and allow Rust platform drivers to match devices based on ACPI identifiers. Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com> Link: https://lore.kernel.org/r/20250620154334.298320-1-igor.korotin.linux@gmail.com [ Use 'LNUXBEEF' as ACPI ID. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-26rust: platform: Set `OF_ID_TABLE` default to `None` in `Driver` traitIgor Korotin
Provide a default value of `None` for `Driver::OF_ID_TABLE` to simplify driver implementations. Drivers that do not require OpenFirmware matching no longer need to import the `of` module or define the constant explicitly. This reduces unnecessary boilerplate and avoids pulling in unused dependencies. Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com> Link: https://lore.kernel.org/r/20250620154124.297158-1-igor.korotin.linux@gmail.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-26rust: driver: Add ACPI id table support to Adapter traitIgor Korotin
Extend the `Adapter` trait to support ACPI device identification. This mirrors the existing Open Firmware (OF) support (`of_id_table`) and enables Rust drivers to match and retrieve ACPI-specific device data when `CONFIG_ACPI` is enabled. To avoid breaking compilation, a stub implementation of `acpi_id_table()` is added to the Platform adapter; the full implementation will be provided in a subsequent patch. Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com> Link: https://lore.kernel.org/r/20250620153914.295679-1-igor.korotin.linux@gmail.com [ Fix clippy warning if #[cfg(not(CONFIG_OF))]; fix checkpatch.pl line length warnings. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-24rust: Use consistent "# Examples" heading style in rustdocViresh Kumar
Use a consistent `# Examples` heading in rustdoc across the codebase. Some modules previously used `## Examples` (even when they should be available as top-level headers), while others used `# Example`, which deviates from the preferred `# Examples` style. Suggested-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org> Acked-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/ddd5ce0ac20c99a72a4f1e4322d3de3911056922.1749545815.git.viresh.kumar@linaro.org Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22rust: enable `clippy::ptr_as_ptr` lintTamir Duberstein
In Rust 1.51.0, Clippy introduced the `ptr_as_ptr` lint [1]: > Though `as` casts between raw pointers are not terrible, > `pointer::cast` is safer because it cannot accidentally change the > pointer's mutability, nor cast the pointer to other types like `usize`. There are a few classes of changes required: - Modules generated by bindgen are marked `#[allow(clippy::ptr_as_ptr)]`. - Inferred casts (` as _`) are replaced with `.cast()`. - Ascribed casts (` as *... T`) are replaced with `.cast::<T>()`. - Multistep casts from references (` as *const _ as *const T`) are replaced with `core::ptr::from_ref(&x).cast()` with or without `::<T>` according to the previous rules. The `core::ptr::from_ref` call is required because `(x as *const _).cast::<T>()` results in inference failure. - Native literal C strings are replaced with `c_str!().as_char_ptr()`. - `*mut *mut T as _` is replaced with `let *mut *const T = (*mut *mut T)`.cast();` since pointer to pointer can be confusing. Apply these changes and enable the lint -- no functional change intended. Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_as_ptr [1] Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Boqun Feng <boqun.feng@gmail.com> Signed-off-by: Tamir Duberstein <tamird@gmail.com> Acked-by: Viresh Kumar <viresh.kumar@linaro.org> Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Acked-by: Tejun Heo <tj@kernel.org> Acked-by: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-1-f43b024581e8@gmail.com [ Added `.cast()` for `opp`. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-04Merge tag 'rust-6.16' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux Pull Rust updates from Miguel Ojeda: "Toolchain and infrastructure: - KUnit '#[test]'s: - Support KUnit-mapped 'assert!' macros. The support that landed last cycle was very basic, and the 'assert!' macros panicked since they were the standard library ones. Now, they are mapped to the KUnit ones in a similar way to how is done for doctests, reusing the infrastructure there. With this, a failing test like: #[test] fn my_first_test() { assert_eq!(42, 43); } will report: # my_first_test: ASSERTION FAILED at rust/kernel/lib.rs:251 Expected 42 == 43 to be true, but is false # my_first_test.speed: normal not ok 1 my_first_test - Support tests with checked 'Result' return types. The return value of test functions that return a 'Result' will be checked, thus one can now easily catch errors when e.g. using the '?' operator in tests. With this, a failing test like: #[test] fn my_test() -> Result { f()?; Ok(()) } will report: # my_test: ASSERTION FAILED at rust/kernel/lib.rs:321 Expected is_test_result_ok(my_test()) to be true, but is false # my_test.speed: normal not ok 1 my_test - Add 'kunit_tests' to the prelude. - Clarify the remaining language unstable features in use. - Compile 'core' with edition 2024 for Rust >= 1.87. - Workaround 'bindgen' issue with forward references to 'enum' types. - objtool: relax slice condition to cover more 'noreturn' functions. - Use absolute paths in macros referencing 'core' and 'kernel' crates. - Skip '-mno-fdpic' flag for bindgen in GCC 32-bit arm builds. - Clean some 'doc_markdown' lint hits -- we may enable it later on. 'kernel' crate: - 'alloc' module: - 'Box': support for type coercion, e.g. 'Box<T>' to 'Box<dyn U>' if 'T' implements 'U'. - 'Vec': implement new methods (prerequisites for nova-core and binder): 'truncate', 'resize', 'clear', 'pop', 'push_within_capacity' (with new error type 'PushError'), 'drain_all', 'retain', 'remove' (with new error type 'RemoveError'), insert_within_capacity' (with new error type 'InsertError'). In addition, simplify 'push' using 'spare_capacity_mut', split 'set_len' into 'inc_len' and 'dec_len', add type invariant 'len <= capacity' and simplify 'truncate' using 'dec_len'. - 'time' module: - Morph the Rust hrtimer subsystem into the Rust timekeeping subsystem, covering delay, sleep, timekeeping, timers. This new subsystem has all the relevant timekeeping C maintainers listed in the entry. - Replace 'Ktime' with 'Delta' and 'Instant' types to represent a duration of time and a point in time. - Temporarily add 'Ktime' to 'hrtimer' module to allow 'hrtimer' to delay converting to 'Instant' and 'Delta'. - 'xarray' module: - Add a Rust abstraction for the 'xarray' data structure. This abstraction allows Rust code to leverage the 'xarray' to store types that implement 'ForeignOwnable'. This support is a dependency for memory backing feature of the Rust null block driver, which is waiting to be merged. - Set up an entry in 'MAINTAINERS' for the XArray Rust support. Patches will go to the new Rust XArray tree and then via the Rust subsystem tree for now. - Allow 'ForeignOwnable' to carry information about the pointed-to type. This helps asserting alignment requirements for the pointer passed to the foreign language. - 'container_of!': retain pointer mut-ness and add a compile-time check of the type of the first parameter ('$field_ptr'). - Support optional message in 'static_assert!'. - Add C FFI types (e.g. 'c_int') to the prelude. - 'str' module: simplify KUnit tests 'format!' macro, convert 'rusttest' tests into KUnit, take advantage of the '-> Result' support in KUnit '#[test]'s. - 'list' module: add examples for 'List', fix path of 'assert_pinned!' (so far unused macro rule). - 'workqueue' module: remove 'HasWork::OFFSET'. - 'page' module: add 'inline' attribute. 'macros' crate: - 'module' macro: place 'cleanup_module()' in '.exit.text' section. 'pin-init' crate: - Add 'Wrapper<T>' trait for creating pin-initializers for wrapper structs with a structurally pinned value such as 'UnsafeCell<T>' or 'MaybeUninit<T>'. - Add 'MaybeZeroable' derive macro to try to derive 'Zeroable', but not error if not all fields implement it. This is needed to derive 'Zeroable' for all bindgen-generated structs. - Add 'unsafe fn cast_[pin_]init()' functions to unsafely change the initialized type of an initializer. These are utilized by the 'Wrapper<T>' implementations. - Add support for visibility in 'Zeroable' derive macro. - Add support for 'union's in 'Zeroable' derive macro. - Upstream dev news: streamline CI, fix some bugs. Add new workflows to check if the user-space version and the one in the kernel tree have diverged. Use the issues tab [1] to track them, which should help folks report and diagnose issues w.r.t. 'pin-init' better. [1] https://github.com/rust-for-linux/pin-init/issues Documentation: - Testing: add docs on the new KUnit '#[test]' tests. - Coding guidelines: explain that '///' vs. '//' applies to private items too. Add section on C FFI types. - Quick Start guide: update Ubuntu instructions and split them into "25.04" and "24.04 LTS and older". And a few other cleanups and improvements" * tag 'rust-6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux: (78 commits) rust: list: Fix typo `much` in arc.rs rust: check type of `$ptr` in `container_of!` rust: workqueue: remove HasWork::OFFSET rust: retain pointer mut-ness in `container_of!` Documentation: rust: testing: add docs on the new KUnit `#[test]` tests Documentation: rust: rename `#[test]`s to "`rusttest` host tests" rust: str: take advantage of the `-> Result` support in KUnit `#[test]`'s rust: str: simplify KUnit tests `format!` macro rust: str: convert `rusttest` tests into KUnit rust: add `kunit_tests` to the prelude rust: kunit: support checked `-> Result`s in KUnit `#[test]`s rust: kunit: support KUnit-mapped `assert!` macros in `#[test]`s rust: make section names plural rust: list: fix path of `assert_pinned!` rust: compile libcore with edition 2024 for 1.87+ rust: dma: add missing Markdown code span rust: task: add missing Markdown code spans and intra-doc links rust: pci: fix docs related to missing Markdown code spans rust: alloc: add missing Markdown code span rust: alloc: add missing Markdown code spans ...
2025-05-25rust: platform: fix docs related to missing Markdown code spansMiguel Ojeda
Convert `TODO` from documentation to a normal comment, and put code in block. This was found using the Clippy `doc_markdown` lint, which we may want to enable. Fixes: 683a63befc73 ("rust: platform: add basic platform device / driver abstractions") Reviewed-by: Benno Lossin <benno.lossin@proton.me> Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Link: https://lore.kernel.org/r/20250324210359.1199574-9-ojeda@kernel.org Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-01rust: types: add `ForeignOwnable::PointedTo`Tamir Duberstein
Allow implementors to specify the foreign pointer type; this exposes information about the pointed-to type such as its alignment. This requires the trait to be `unsafe` since it is now possible for implementors to break soundness by returning a misaligned pointer. Encoding the pointer type in the trait (and avoiding pointer casts) allows the compiler to check that implementors return the correct pointer type. This is preferable to directly encoding the alignment in the trait using a constant as the compiler would be unable to check it. Acked-by: Danilo Krummrich <dakr@kernel.org> Signed-off-by: Tamir Duberstein <tamird@gmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250423-rust-xarray-bindings-v19-1-83cdcf11c114@gmail.com Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-04-19rust: platform: impl TryFrom<&Device> for &platform::DeviceDanilo Krummrich
Implement TryFrom<&device::Device> for &Device. This allows us to get a &platform::Device from a generic &Device in a safe way; the conversion fails if the device' bus type does not match with the platform bus type. Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20250321214826.140946-4-dakr@kernel.org [ Support device context types, use dev_is_platform() helper. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-17rust: platform: preserve device context in AsRefDanilo Krummrich
Since device::Device has a generic over its context, preserve this device context in AsRef. For instance, when calling platform::Device<Core> the new AsRef implementation returns device::Device<Core>. Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20250413173758.12068-5-dakr@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-17rust: device: implement impl_device_context_into_aref!Danilo Krummrich
Implement a macro to implement all From conversions of a certain device to ARef<Device>. This avoids unnecessary boiler plate code for every device implementation. Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20250413173758.12068-3-dakr@kernel.org [ Add missing `::` prefix in macros. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-17rust: device: implement impl_device_context_deref!Danilo Krummrich
The Deref hierarchy for device context generics is the same for every (bus specific) device. Implement those with a generic macro to avoid duplicated boiler plate code and ensure the correct Deref hierarchy for every device implementation. Co-developed-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Christian Schrefl <chrisi.schrefl@gmail.com> Link: https://lore.kernel.org/r/20250413173758.12068-2-dakr@kernel.org [ Add missing `::` prefix in macros. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-04-01Merge tag 'driver-core-6.15-rc1' of ↵Linus Torvalds
git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/driver-core Pull driver core updatesk from Greg KH: "Here is the big set of driver core updates for 6.15-rc1. Lots of stuff happened this development cycle, including: - kernfs scaling changes to make it even faster thanks to rcu - bin_attribute constify work in many subsystems - faux bus minor tweaks for the rust bindings - rust binding updates for driver core, pci, and platform busses, making more functionaliy available to rust drivers. These are all due to people actually trying to use the bindings that were in 6.14. - make Rafael and Danilo full co-maintainers of the driver core codebase - other minor fixes and updates" * tag 'driver-core-6.15-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/driver-core: (52 commits) rust: platform: require Send for Driver trait implementers rust: pci: require Send for Driver trait implementers rust: platform: impl Send + Sync for platform::Device rust: pci: impl Send + Sync for pci::Device rust: platform: fix unrestricted &mut platform::Device rust: pci: fix unrestricted &mut pci::Device rust: device: implement device context marker rust: pci: use to_result() in enable_device_mem() MAINTAINERS: driver core: mark Rafael and Danilo as co-maintainers rust/kernel/faux: mark Registration methods inline driver core: faux: only create the device if probe() succeeds rust/faux: Add missing parent argument to Registration::new() rust/faux: Drop #[repr(transparent)] from faux::Registration rust: io: fix devres test with new io accessor functions rust: io: rename `io::Io` accessors kernfs: Move dput() outside of the RCU section. efi: rci2: mark bin_attribute as __ro_after_init rapidio: constify 'struct bin_attribute' firmware: qemu_fw_cfg: constify 'struct bin_attribute' powerpc/perf/hv-24x7: Constify 'struct bin_attribute' ...
2025-03-20rust: platform: require Send for Driver trait implementersDanilo Krummrich
The instance of Self, returned and created by Driver::probe() is dropped in the bus' remove() callback. Request implementers of the Driver trait to implement Send, since the remove() callback is not guaranteed to run from the same thread as probe(). Fixes: 683a63befc73 ("rust: platform: add basic platform device / driver abstractions") Cc: stable <stable@kernel.org> Reported-by: Alice Ryhl <aliceryhl@google.com> Closes: https://lore.kernel.org/lkml/Z9rDxOJ2V2bPjj5i@google.com/ Signed-off-by: Danilo Krummrich <dakr@kernel.org> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20250319145350.69543-2-dakr@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-03-18rust: platform: impl Send + Sync for platform::DeviceDanilo Krummrich
Commit 4d320e30ee04 ("rust: platform: fix unrestricted &mut platform::Device") changed the definition of platform::Device and discarded the implicitly derived Send and Sync traits. This isn't required by upstream code yet, and hence did not cause any issues. However, it is relied on by upcoming drivers, hence add it back in. Signed-off-by: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/20250318212940.137577-2-dakr@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-03-17rust: platform: fix unrestricted &mut platform::DeviceDanilo Krummrich
As by now, platform::Device is implemented as: #[derive(Clone)] pub struct Device(ARef<device::Device>); This may be convenient, but has the implication that drivers can call device methods that require a mutable reference concurrently at any point of time. Instead define platform::Device as pub struct Device<Ctx: DeviceContext = Normal>( Opaque<bindings::platform_dev>, PhantomData<Ctx>, ); and manually implement the AlwaysRefCounted trait. With this we can implement methods that should only be called from bus callbacks (such as probe()) for platform::Device<Core>. Consequently, we make this type accessible in bus callbacks only. Arbitrary references taken by the driver are still of type ARef<platform::Device> and hence don't provide access to methods that are reserved for bus callbacks. Fixes: 683a63befc73 ("rust: platform: add basic platform device / driver abstractions") Reviewed-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Acked-by: Boqun Feng <boqun.feng@gmail.com> Link: https://lore.kernel.org/r/20250314160932.100165-5-dakr@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-03-10rust: module: introduce `authors` keyGuilherme Giacomo Simoes
In the `module!` macro, the `author` field is currently of type `String`. Since modules can have multiple authors, this limitation prevents specifying more than one. Add an `authors` field as `Option<Vec<String>>` to allow creating modules with multiple authors, and change the documentation and all current users to use it. Eventually, the single `author` field may be removed. [ The `modinfo` key needs to still be `author`; otherwise, tooling may not work properly, e.g.: $ modinfo --author samples/rust/rust_print.ko Rust for Linux Contributors I have also kept the original `author` field (undocumented), so that we can drop it more easily in a kernel cycle or two. - Miguel ] Suggested-by: Miguel Ojeda <ojeda@kernel.org> Link: https://github.com/Rust-for-Linux/linux/issues/244 Reviewed-by: Charalampos Mitrodimas <charmitro@posteo.net> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Signed-off-by: Guilherme Giacomo Simoes <trintaeoitogc@gmail.com> Link: https://lore.kernel.org/r/20250309175712.845622-2-trintaeoitogc@gmail.com [ Fixed `modinfo` key. Kept `author` field. Reworded message accordingly. Updated my email. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-01-07rust: driver: address soundness issue in `RegistrationOps`Danilo Krummrich
The `RegistrationOps` trait holds some obligations to the caller and implementers. While being documented, the trait and the corresponding functions haven't been marked as unsafe. Hence, markt the trait and functions unsafe and add the corresponding safety comments. This patch does not include any fuctional changes. Reported-by: Gary Guo <gary@garyguo.net> Closes: https://lore.kernel.org/rust-for-linux/20241224195821.3b43302b.gary@garyguo.net/ Signed-off-by: Danilo Krummrich <dakr@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Link: https://lore.kernel.org/r/20250103164655.96590-4-dakr@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2024-12-20rust: platform: add basic platform device / driver abstractionsDanilo Krummrich
Implement the basic platform bus abstractions required to write a basic platform driver. This includes the following data structures: The `platform::Driver` trait represents the interface to the driver and provides `platform::Driver::probe` for the driver to implement. The `platform::Device` abstraction represents a `struct platform_device`. In order to provide the platform bus specific parts to a generic `driver::Registration` the `driver::RegistrationOps` trait is implemented by `platform::Adapter`. Reviewed-by: Rob Herring (Arm) <robh@kernel.org> Signed-off-by: Danilo Krummrich <dakr@kernel.org> Tested-by: Dirk Behme <dirk.behme@de.bosch.com> Link: https://lore.kernel.org/r/20241219170425.12036-15-dakr@kernel.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>