summaryrefslogtreecommitdiff
path: root/rust
AgeCommit message (Collapse)Author
2025-05-22rust: remove unneeded Rust 1.87.0 `allow(clippy::ptr_eq)`Miguel Ojeda
For the Rust 1.87.0 release, Clippy was expected to warn with: error: use `core::ptr::eq` when comparing raw pointers --> rust/kernel/list.rs:438:12 | 438 | if self.first == item { | ^^^^^^^^^^^^^^^^^^ help: try: `core::ptr::eq(self.first, item)` | = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#ptr_eq = note: `-D clippy::ptr-eq` implied by `-D warnings` = help: to override `-D warnings` add `#[allow(clippy::ptr_eq)]` However, a backport to relax a bit the `clippy::ptr_eq` finally landed, and thus Clippy did not warn by the time the release happened. Thus remove the `allow`s added back then, which were added just in case the backport did not land in time. See commit a39f30870927 ("rust: allow Rust 1.87.0's `clippy::ptr_eq` lint") for details. Link: https://github.com/rust-lang/rust/pull/140859 [1] Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250520182125.806758-1-ojeda@kernel.org [ Reworded for clarity. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-21net: phy: pass PHY driver to .match_phy_device OPChristian Marangi
Pass PHY driver pointer to .match_phy_device OP in addition to phydev. Having access to the PHY driver struct might be useful to check the PHY ID of the driver is being matched for in case the PHY ID scanned in the phydev is not consistent. A scenario for this is a PHY that change PHY ID after a firmware is loaded, in such case, the PHY ID stored in PHY device struct is not valid anymore and PHY will manually scan the ID in the match_phy_device function. Having the PHY driver info is also useful for those PHY driver that implement multiple simple .match_phy_device OP to match specific MMD PHY ID. With this extra info if the parsing logic is the same, the matching function can be generalized by using the phy_id in the PHY driver instead of hardcoding. Rust wrapper callback is updated to align to the new match_phy_device arguments. Suggested-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk> Reviewed-by: Russell King (Oracle) <rmk+kernel@armlinux.org.uk> Signed-off-by: Christian Marangi <ansuelsmth@gmail.com> Reviewed-by: Benno Lossin <lossin@kernel.org> # for Rust Reviewed-by: FUJITA Tomonori <fujita.tomonori@gmail.com> Link: https://patch.msgid.link/20250517201353.5137-2-ansuelsmth@gmail.com Signed-off-by: Jakub Kicinski <kuba@kernel.org>
2025-05-21Merge tag 'cpufreq-arm-updates-6.16' of ↵Rafael J. Wysocki
git://git.kernel.org/pub/scm/linux/kernel/git/vireshk/pm Merge ARM CPUFreq updates for 6.16 from Viresh Kumar: "- Rust abstractions for CPUFreq framework (Viresh Kumar). - Rust abstractions for OPP framework (Viresh Kumar). - Basic Rust abstractions for Clk and Cpumask frameworks (Viresh Kumar). - Minor cleanup to the SCMI cpufreq driver (Mike Tipton)." * tag 'cpufreq-arm-updates-6.16' of git://git.kernel.org/pub/scm/linux/kernel/git/vireshk/pm: (24 commits) cpufreq: scmi: Skip SCMI devices that aren't used by the CPUs cpufreq: Add Rust-based cpufreq-dt driver rust: opp: Extend OPP abstractions with cpufreq support rust: cpufreq: Extend abstractions for driver registration rust: cpufreq: Extend abstractions for policy and driver ops rust: cpufreq: Add initial abstractions for cpufreq framework rust: opp: Add abstractions for the configuration options rust: opp: Add abstractions for the OPP table rust: opp: Add initial abstractions for OPP framework rust: cpu: Add from_cpu() rust: macros: enable use of hyphens in module names rust: clk: Add initial abstractions rust: clk: Add helpers for Rust code MAINTAINERS: Add entry for Rust cpumask API rust: cpumask: Add initial abstractions rust: cpumask: Add few more helpers rust: devres: require a bound device rust: pci: move iomap_region() to impl Device<Bound> rust: device: implement Bound device context rust: pci: preserve device context in AsRef ...
2025-05-21rust: miscdevice: fix typo in MiscDevice::ioctl documentationChristian Schrefl
Fixes one small typo (`utilties` to `utilities`) in the documentation of `MiscDevice::ioctl`. Fixes: f893691e7426 ("rust: miscdevice: add base miscdevice abstraction") Signed-off-by: Christian Schrefl <chrisi.schrefl@gmail.com> Reviewed-by: Benno Lossin <lossin@kernel.org> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250517-rust_miscdevice_fix_typo-v1-1-8c30a6237ba9@gmail.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-05-20rust: str: fix typo in commentJihed Chaibi
Fix a typo ("then" to "than") in a comment. Signed-off-by: Jihed Chaibi <jihed.chaibi.dev@gmail.com> Reviewed-by: Benno Lossin <lossin@kernel.org> Fixes: fffed679eeea ("rust: str: add `Formatter` type") Link: https://lore.kernel.org/r/20250517002604.603223-1-jihed.chaibi.dev@gmail.com [ Reworded. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-21Merge tag 'nova-next-v6.16-2025-05-20' of ↵Dave Airlie
https://gitlab.freedesktop.org/drm/nova into drm-next Nova changes for v6.16 auxiliary: - bus abstractions - implementation for driver registration - add sample driver drm: - implement __drm_dev_alloc() - DRM core infrastructure Rust abstractions - device, driver and registration - DRM IOCTL - DRM File - GEM object - IntoGEMObject rework - generically implement AlwaysRefCounted through IntoGEMObject - refactor unsound from_gem_obj() into as_ref() - refactor into_gem_obj() into as_raw() driver-core: - merge topic/device-context-2025-04-17 from driver-core tree - implement Devres::access() - fix: doctest build under `!CONFIG_PCI` - accessor for Device::parent() - fix: conditionally expect `dead_code` for `parent()` - impl TryFrom<&Device> bus devices (PCI, platform) nova-core: - remove completed Vec extentions from task list - register auxiliary device for nova-drm - derive useful traits for Chipset - add missing GA100 chipset - take &Device<Bound> in Gpu::new() - infrastructure to generate register definitions - fix register layout of NV_PMC_BOOT_0 - move Firmware into own (Rust) module - fix: select AUXILIARY_BUS nova-drm: - initial driver skeleton (depends on drm and auxiliary bus abstractions) - fix: select AUXILIARY_BUS Rust (dependencies): - implement Opaque::zeroed() - implement Revocable::try_access_with() - implement Revocable::access() From: Danilo Krummrich <dakr@kernel.org> Link: https://lore.kernel.org/r/aCxAf3RqQAXLDhAj@cassiopeiae
2025-05-20rust: opp: Extend OPP abstractions with cpufreq supportViresh Kumar
Extend the OPP abstractions to include support for interacting with the cpufreq core, including the ability to retrieve frequency tables from OPP table. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: cpufreq: Extend abstractions for driver registrationViresh Kumar
Extend the cpufreq abstractions to support driver registration from Rust. Reviewed-by: Danilo Krummrich <dakr@kernel.org> Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: cpufreq: Extend abstractions for policy and driver opsViresh Kumar
Extend the cpufreq abstractions to include support for policy handling and driver operations. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: cpufreq: Add initial abstractions for cpufreq frameworkViresh Kumar
Introduce initial Rust abstractions for the cpufreq core. This includes basic representations for cpufreq flags, relation types, and the cpufreq table. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: opp: Add abstractions for the configuration optionsViresh Kumar
Introduce Rust abstractions for the OPP core configuration options, enabling safe access to various configurable aspects of the OPP framework. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: opp: Add abstractions for the OPP tableViresh Kumar
Introduce Rust abstractions for `struct opp_table`, enabling access to OPP tables from Rust. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: opp: Add initial abstractions for OPP frameworkViresh Kumar
Introduce initial Rust abstractions for the Operating Performance Points (OPP) framework. This includes bindings for `struct dev_pm_opp` and `struct dev_pm_opp_data`, laying the groundwork for further OPP integration. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: cpu: Add from_cpu()Viresh Kumar
This implements cpu::from_cpu(), which returns a reference to Device for a CPU. The C struct is created at initialization time for CPUs and is never freed and so ARef isn't returned from this function. The new helper will be used by Rust based cpufreq drivers. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-20rust: macros: enable use of hyphens in module namesAnisse Astier
Some modules might need naming that contains hyphens "-" to match the auto-probing by name in the platform devices that comes from the device tree. But Rust identifier cannot contain hyphens, so replace them with underscores. Signed-off-by: Anisse Astier <anisse@astier.eu> Reviewed-by: Alice Ryhl <aliceryhl@google.com> [ Viresh: Replace "-" with '-', minor commit log fix, rename variable and fix line length checkpatch warnings ] Reviewed-by: Benno Lossin <lossin@kernel.org> Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-19rust: clk: Add initial abstractionsViresh Kumar
Add initial abstractions for the clk APIs. These provide the minimal functionality needed for common use cases, making them straightforward to introduce in the first iteration. These will be used by Rust based cpufreq / OPP layers to begin with. Tested-by: Daniel Almeida <daniel.almeida@collabora.com> Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-19rust: clk: Add helpers for Rust codeViresh Kumar
Non-trivial C macros and inlined C functions cannot be used directly in the Rust code and are used via functions ("helpers") that wrap those so that they can be called from Rust. In order to prepare for adding Rust abstractions for the clock APIs, add clock helpers required by the Rust implementation. Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-05-19rust: cpumask: Add initial abstractionsViresh Kumar
Add initial Rust abstractions for struct cpumask, covering a subset of its APIs. Additional APIs can be added as needed. These abstractions will be used in upcoming Rust support for cpufreq and OPP frameworks. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org> Reviewed-by: Yury Norov [NVIDIA] <yury.norov@gmail.com>
2025-05-19rust: cpumask: Add few more helpersViresh Kumar
Add few more cpumask helpers that are required by the Rust abstraction. Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org> Acked-by: Yury Norov [NVIDIA] <yury.norov@gmail.com>
2025-05-18Merge tag 'alloc-next-v6.16-2025-05-13' of ↵Miguel Ojeda
https://github.com/Rust-for-Linux/linux into rust-next Pull alloc updates from Danilo Krummrich: "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) - Vec::truncate() - Vec::resize() - Vec::clear() - Vec::pop() - Vec::push_within_capacity() - New error type: PushError - Vec::drain_all() - Vec::retain() - Vec::remove() - New error type: RemoveError - Vec::insert_within_capacity - New error type: InsertError - Simplify Vec::push() using Vec::spare_capacity_mut() - Split Vec::set_len() into Vec::inc_len() and Vec::dec_len() - Add type invariant Vec::len() <= Vec::capacity - Simplify Vec::truncate() using Vec::dec_len()" * tag 'alloc-next-v6.16-2025-05-13' of https://github.com/Rust-for-Linux/linux: rust: alloc: add Vec::insert_within_capacity rust: alloc: add Vec::remove rust: alloc: add Vec::retain rust: alloc: add Vec::drain_all rust: alloc: add Vec::push_within_capacity rust: alloc: add Vec::pop rust: alloc: add Vec::clear rust: alloc: replace `Vec::set_len` with `inc_len` rust: alloc: refactor `Vec::truncate` using `dec_len` rust: alloc: add `Vec::dec_len` rust: alloc: add Vec::len() <= Vec::capacity invariant rust: alloc: allow coercion from `Box<T>` to `Box<dyn U>` if T implements U rust: alloc: use `spare_capacity_mut` to reduce unsafe rust: alloc: add Vec::resize method rust: alloc: add Vec::truncate method rust: alloc: add missing invariant in Vec::set_len()
2025-05-18Merge tag 'pin-init-v6.16' of https://github.com/Rust-for-Linux/linux into ↵Miguel Ojeda
rust-next Pull pin-init updates from Benno Lossin: "Added: - 'Wrapper<T>' trait for creating pin-initializers for wrapper structs with a structurally pinned value such as 'UnsafeCell<T>' or 'MaybeUninit<T>'. - '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. - 'unsafe fn cast_[pin_]init()' functions to unsafely change the initialized type of an initializer. These are utilized by the 'Wrapper<T>' implementations. Changed: - Added support for visibility in 'Zeroable' derive macro. - Added support for 'union's in 'Zeroable' derive macro. Upstream dev news: - The CI has been streamlined & some bugs with it have been fixed. I also added new workflows to check if the user-space version and the one in the kernel tree have diverged. - I also started to use the issues [1] tab to keep track of any problems or unexpected/unwanted things. This should help folks report and diagnose issues w.r.t. 'pin-init' better. [1] https://github.com/rust-for-linux/pin-init/issues" * tag 'pin-init-v6.16' of https://github.com/Rust-for-Linux/linux: rust: pin-init: improve documentation for `Zeroable` derive macros rust: pin-init: fix typos rust: pin-init: add `MaybeZeroable` derive macro rust: pin-init: allow `Zeroable` derive macro to also be applied to unions rust: pin-init: allow `pub` fields in `derive(Zeroable)` rust: pin-init: Update the structural pinning link in readme. rust: pin-init: Update Changelog and Readme rust: pin-init: Implement `Wrapper` for `UnsafePinned` behind feature flag. rust: pin-init: Add the `Wrapper` trait. rust: pin-init: add `cast_[pin_]init` functions to change the initialized type rust: pin-init: examples: use `allow` instead of `expect` rust: pin-init: examples: conditionally enable `feature(lint_reasons)` rust: pin-init: internal: skip rustfmt formatting of kernel-only module rust: pin-init: synchronize README.md
2025-05-18Merge tag 'rust-xarray-for-v6.16' of https://github.com/Rust-for-Linux/linux ↵Miguel Ojeda
into rust-next Pull XArray updates from Andreas Hindborg: "Introduce Rust support for the 'xarray' data structure: - 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. 'kernel' crate: - Allow 'ForeignOwnable' to carry information about the pointed-to type. This helps asserting alignment requirements for the pointer passed to the foreign language." * tag 'rust-xarray-for-v6.16' of https://github.com/Rust-for-Linux/linux: MAINTAINERS: add entry for Rust XArray API rust: xarray: Add an abstraction for XArray rust: types: add `ForeignOwnable::PointedTo`
2025-05-18Merge tag 'rust-timekeeping-for-v6.16-v2' of ↵Miguel Ojeda
https://github.com/Rust-for-Linux/linux into rust-next Pull timekeeping updates from Andreas Hindborg: - 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'. * tag 'rust-timekeeping-for-v6.16-v2' of https://github.com/Rust-for-Linux/linux: MAINTAINERS: rust: Add a new section for all of the time stuff rust: time: Introduce Instant type rust: time: Introduce Delta type rust: time: Add PartialEq/Eq/PartialOrd/Ord trait to Ktime rust: hrtimer: Add Ktime temporarily
2025-05-16rust: sync: rcu: Mark Guard methods as inlineI Hsin Cheng
Currently the implementation of "Guard" methods are basically wrappers around rcu's function within kernel. Building the kernel with llvm 18.1.8 on x86_64 machine will generate the following symbols: $ nm vmlinux | grep ' _R'.*Guard | rustfilt ffffffff817b6c90 T <kernel::sync::rcu::Guard>::new ffffffff817b6cb0 T <kernel::sync::rcu::Guard>::unlock ffffffff817b6cd0 T <kernel::sync::rcu::Guard as core::ops::drop::Drop>::drop ffffffff817b6c90 T <kernel::sync::rcu::Guard as core::default::Default>::default These Rust symbols are basically wrappers around functions "rcu_read_lock" and "rcu_read_unlock". Marking them as inline can reduce the generation of these symbols, and saves the size of code generation for 132 bytes. $ ./scripts/bloat-o-meter vmlinux_old vmlinux_new (Output is demangled for readability) add/remove: 0/10 grow/shrink: 0/1 up/down: 0/-132 (-132) Function old new delta rust_driver_pci::SampleDriver::probe 1041 1034 -7 kernel::sync::rcu::Guard::default 9 - -9 kernel::sync::rcu::Guard::drop 9 - -9 kernel::sync::rcu::read_lock 9 - -9 kernel::sync::rcu::Guard::unlock 9 - -9 kernel::sync::rcu::Guard::new 9 - -9 __pfx__kernel::sync::rcu::Guard::default 16 - -16 __pfx__kernel::sync::rcu::Guard::drop 16 - -16 __pfx__kernel::sync::rcu::read_lock 16 - -16 __pfx__kernel::sync::rcu::Guard::unlock 16 - -16 __pfx__kernel::sync::rcu::Guard::new 16 - -16 Total: Before=23365955, After=23365823, chg -0.00% Link: https://github.com/Rust-for-Linux/linux/issues/1145 Signed-off-by: I Hsin Cheng <richard120310@gmail.com> Reviewed-by: Joel Fernandes <joelagnelf@nvidia.com> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Charalampos Mitrodimas <charmitro@posteo.net> Acked-by: Miguel Ojeda <ojeda@kernel.org> Signed-off-by: Joel Fernandes <joelagnelf@nvidia.com>
2025-05-14rust: drm: gem: Implement AlwaysRefCounted for all gem objects automaticallyLyude Paul
Currently we are requiring AlwaysRefCounted in most trait bounds for gem objects, and implementing it by hand for our only current type of gem object. However, all gem objects use the same functions for reference counting - and all gem objects support reference counting. We're planning on adding support for shmem gem objects, let's move this around a bit by instead making IntoGEMObject require AlwaysRefCounted as a trait bound, and then provide a blanket AlwaysRefCounted implementation for any object that implements IntoGEMObject so all gem object types can use the same AlwaysRefCounted implementation. This also makes things less verbose by making the AlwaysRefCounted trait bound implicit for any IntoGEMObject bound. Signed-off-by: Lyude Paul <lyude@redhat.com> Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Link: https://lore.kernel.org/r/20250513221046.903358-5-lyude@redhat.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14rust: drm: gem: s/into_gem_obj()/as_raw()/Lyude Paul
There's a few changes here: * The rename, of course (this should also let us drop the clippy annotation here) * Return *mut bindings::drm_gem_object instead of &Opaque<bindings::drm_gem_object> - the latter doesn't really have any benefit and just results in conversion from the rust type to the C type having to be more verbose than necessary. Signed-off-by: Lyude Paul <lyude@redhat.com> Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Link: https://lore.kernel.org/r/20250513221046.903358-4-lyude@redhat.com [ Fixup s/into_gem_obj()/as_raw()/ in safety comment. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14rust: drm: gem: Refactor IntoGEMObject::from_gem_obj() to as_ref()Lyude Paul
There's a few issues with this function, mainly: * This function -probably- should have been unsafe from the start. Pointers are not always necessarily valid, but you want a function that does field-projection for a pointer that can travel outside of the original struct to be unsafe, at least if I understand properly. * *mut Self is not terribly useful in this context, the majority of uses of from_gem_obj() grab a *mut Self and then immediately convert it into a &'a Self. It also goes against the ffi conventions we've set in the rest of the kernel thus far. * from_gem_obj() also doesn't follow the naming conventions in the rest of the DRM bindings at the moment, as_ref() would be a better name. So, let's: * Make from_gem_obj() unsafe * Convert it to return &'a Self * Rename it to as_ref() * Update all call locations Signed-off-by: Lyude Paul <lyude@redhat.com> Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Link: https://lore.kernel.org/r/20250513221046.903358-3-lyude@redhat.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-14rust: drm: gem: Use NonNull for Object::devLyude Paul
There is usually not much of a reason to use a raw pointer in a data struct, so move this to NonNull instead. Signed-off-by: Lyude Paul <lyude@redhat.com> Reviewed-by: Daniel Almeida <daniel.almeida@collabora.com> Link: https://lore.kernel.org/r/20250513221046.903358-2-lyude@redhat.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-12drm: nova-drm: add initial driver skeletonDanilo Krummrich
Add the initial nova-drm driver skeleton. nova-drm is connected to nova-core through the auxiliary bus and implements the DRM parts of the nova driver stack. For now, it implements the fundamental DRM abstractions, i.e. creates a DRM device and registers it, exposing a three sample IOCTLs. DRM_IOCTL_NOVA_GETPARAM - provides the PCI bar size from the bar that maps the GPUs VRAM from nova-core DRM_IOCTL_NOVA_GEM_CREATE - creates a new dummy DRM GEM object and returns a handle DRM_IOCTL_NOVA_GEM_INFO - provides metadata for the DRM GEM object behind a given handle I implemented a small userspace test suite [1] that utilizes this interface. Link: https://gitlab.freedesktop.org/dakr/drm-test [1] Reviewed-by: Maxime Ripard <mripard@kernel.org> Acked-by: Dave Airlie <airlied@redhat.com> Link: https://lore.kernel.org/r/20250424160452.8070-3-dakr@kernel.org [ Kconfig: depend on DRM=y rather than just DRM. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-12rust: configfs: introduce rust support for configfsAndreas Hindborg
Add a Rust API for configfs, thus allowing Rust modules to use configfs for configuration. Make the implementation a shim on top of the C configfs implementation, allowing safe use of the C infrastructure from Rust. Link: https://lore.kernel.org/r/20250508-configfs-v8-1-8ebde6180edc@kernel.org Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-05-12rust: devres: fix doctest build under `!CONFIG_PCI`Miguel Ojeda
The doctest requires `CONFIG_PCI`: error[E0432]: unresolved import `kernel::pci` --> rust/doctests_kernel_generated.rs:2689:44 | 2689 | use kernel::{device::Core, devres::Devres, pci}; | ^^^ no `pci` in the root | note: found an item that was configured out --> rust/kernel/lib.rs:96:9 note: the item is gated here --> rust/kernel/lib.rs:95:1 Thus conditionally compile it (which still checks the syntax). Fixes: f301cb978c06 ("rust: devres: implement Devres::access()") Signed-off-by: Miguel Ojeda <ojeda@kernel.org> Link: https://lore.kernel.org/r/20250511182533.1016163-1-ojeda@kernel.org Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-11task: rust: rework how current is accessedAlice Ryhl
Introduce a new type called `CurrentTask` that lets you perform various operations that are only safe on the `current` task. Use the new type to provide a way to access the current mm without incrementing its refcount. With this change, you can write stuff such as let vma = current!().mm().lock_vma_under_rcu(addr); without incrementing any refcounts. This replaces the existing abstractions for accessing the current pid namespace. With the old approach, every field access to current involves both a macro and a unsafe helper function. The new approach simplifies that to a single safe function on the `CurrentTask` type. This makes it less heavy-weight to add additional current accessors in the future. That said, creating a `CurrentTask` type like the one in this patch requires that we are careful to ensure that it cannot escape the current task or otherwise access things after they are freed. To do this, I declared that it cannot escape the current "task context" where I defined a "task context" as essentially the region in which `current` remains unchanged. So e.g., release_task() or begin_new_exec() would leave the task context. If a userspace thread returns to userspace and later makes another syscall, then I consider the two syscalls to be different task contexts. This allows values stored in that task to be modified between syscalls, even if they're guaranteed to be immutable during a syscall. Ensuring correctness of `CurrentTask` is slightly tricky if we also want the ability to have a safe `kthread_use_mm()` implementation in Rust. To support that safely, there are two patterns we need to ensure are safe: // Case 1: current!() called inside the scope. let mm; kthread_use_mm(some_mm, || { mm = current!().mm(); }); drop(some_mm); mm.do_something(); // UAF and: // Case 2: current!() called before the scope. let mm; let task = current!(); kthread_use_mm(some_mm, || { mm = task.mm(); }); drop(some_mm); mm.do_something(); // UAF The existing `current!()` abstraction already natively prevents the first case: The `&CurrentTask` would be tied to the inner scope, so the borrow-checker ensures that no reference derived from it can escape the scope. Fixing the second case is a bit more tricky. The solution is to essentially pretend that the contents of the scope execute on an different thread, which means that only thread-safe types can cross the boundary. Since `CurrentTask` is marked `NotThreadSafe`, attempts to move it to another thread will fail, and this includes our fake pretend thread boundary. This has the disadvantage that other types that aren't thread-safe for reasons unrelated to `current` also cannot be moved across the `kthread_use_mm()` boundary. I consider this an acceptable tradeoff. Link: https://lkml.kernel.org/r/20250408-vma-v16-8-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Boqun Feng <boqun.feng@gmail.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: Jann Horn <jannh@google.com> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11rust: miscdevice: add mmap supportAlice Ryhl
Add the ability to write a file_operations->mmap hook in Rust when using the miscdevice abstraction. The `vma` argument to the `mmap` hook uses the `VmaNew` type from the previous commit; this type provides the correct set of operations for a file_operations->mmap hook. Link: https://lkml.kernel.org/r/20250408-vma-v16-7-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Jann Horn <jannh@google.com> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11mm: rust: add VmaNew for f_ops->mmap()Alice Ryhl
This type will be used when setting up a new vma in an f_ops->mmap() hook. Using a separate type from VmaRef allows us to have a separate set of operations that you are only able to use during the mmap() hook. For example, the VM_MIXEDMAP flag must not be changed after the initial setup that happens during the f_ops->mmap() hook. To avoid setting invalid flag values, the methods for clearing VM_MAYWRITE and similar involve a check of VM_WRITE, and return an error if VM_WRITE is set. Trying to use `try_clear_maywrite` without checking the return value results in a compilation error because the `Result` type is marked #[must_use]. For now, there's only a method for VM_MIXEDMAP and not VM_PFNMAP. When we add a VM_PFNMAP method, we will need some way to prevent you from setting both VM_MIXEDMAP and VM_PFNMAP on the same vma. Link: https://lkml.kernel.org/r/20250408-vma-v16-6-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Jann Horn <jannh@google.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Gary Guo <gary@garyguo.net> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11mm: rust: add mmput_async supportAlice Ryhl
Adds an MmWithUserAsync type that uses mmput_async when dropped but is otherwise identical to MmWithUser. This has to be done using a separate type because the thing we are changing is the destructor. Rust Binder needs this to avoid a certain deadlock. See commit 9a9ab0d96362 ("binder: fix race between mmput() and do_exit()") for details. It's also needed in the shrinker to avoid cleaning up the mm in the shrinker's context. Link: https://lkml.kernel.org/r/20250408-vma-v16-5-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: Jann Horn <jannh@google.com> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11mm: rust: add lock_vma_under_rcuAlice Ryhl
Currently, the binder driver always uses the mmap lock to make changes to its vma. Because the mmap lock is global to the process, this can involve significant contention. However, the kernel has a feature called per-vma locks, which can significantly reduce contention. For example, you can take a vma lock in parallel with an mmap write lock. This is important because contention on the mmap lock has been a long-term recurring challenge for the Binder driver. This patch introduces support for using `lock_vma_under_rcu` from Rust. The Rust Binder driver will be able to use this to reduce contention on the mmap lock. Link: https://lkml.kernel.org/r/20250408-vma-v16-4-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Jann Horn <jannh@google.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11mm: rust: add vm_insert_pageAlice Ryhl
The vm_insert_page method is only usable on vmas with the VM_MIXEDMAP flag, so we introduce a new type to keep track of such vmas. The approach used in this patch assumes that we will not need to encode many flag combinations in the type. I don't think we need to encode more than VM_MIXEDMAP and VM_PFNMAP as things are now. However, if that becomes necessary, using generic parameters in a single type would scale better as the number of flags increases. Link: https://lkml.kernel.org/r/20250408-vma-v16-3-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: Jann Horn <jannh@google.com> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11mm: rust: add vm_area_struct methods that require read accessAlice Ryhl
This adds a type called VmaRef which is used when referencing a vma that you have read access to. Here, read access means that you hold either the mmap read lock or the vma read lock (or stronger). Additionally, a vma_lookup method is added to the mmap read guard, which enables you to obtain a &VmaRef in safe Rust code. This patch only provides a way to lock the mmap read lock, but a follow-up patch also provides a way to just lock the vma read lock. Link: https://lkml.kernel.org/r/20250408-vma-v16-2-d8b446e885d9@google.com Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Reviewed-by: Jann Horn <jannh@google.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Balbir Singh <balbirs@nvidia.com> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-11mm: rust: add abstraction for struct mm_structAlice Ryhl
Patch series "Rust support for mm_struct, vm_area_struct, and mmap", v16. This updates the vm_area_struct support to use the approach we discussed at LPC where there are several different Rust wrappers for vm_area_struct depending on the kind of access you have to the vma. Each case allows a different set of operations on the vma. This includes an MM MAINTAINERS entry as proposed by Lorenzo: https://lore.kernel.org/all/33e64b12-aa07-4e78-933a-b07c37ff1d84@lucifer.local/ This patch (of 9): These abstractions allow you to reference a `struct mm_struct` using both mmgrab and mmget refcounts. This is done using two Rust types: * Mm - represents an mm_struct where you don't know anything about the value of mm_users. * MmWithUser - represents an mm_struct where you know at compile time that mm_users is non-zero. This allows us to encode in the type system whether a method requires that mm_users is non-zero or not. For instance, you can always call `mmget_not_zero` but you can only call `mmap_read_lock` when mm_users is non-zero. The struct is called Mm to keep consistency with the C side. The ability to obtain `current->mm` is added later in this series. The mm module is defined to only exist when CONFIG_MMU is set. This avoids various errors due to missing types and functions when CONFIG_MMU is disabled. More fine-grained cfgs can be considered in the future. See the thread at [1] for more info. Link: https://lkml.kernel.org/r/20250408-vma-v16-9-d8b446e885d9@google.com Link: https://lkml.kernel.org/r/20250408-vma-v16-1-d8b446e885d9@google.com Link: https://lore.kernel.org/all/202503091916.QousmtcY-lkp@intel.com/ Signed-off-by: Alice Ryhl <aliceryhl@google.com> Acked-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com> Acked-by: Liam R. Howlett <Liam.Howlett@Oracle.com> Acked-by: Balbir Singh <balbirs@nvidia.com> Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Gary Guo <gary@garyguo.net> Cc: Alex Gaynor <alex.gaynor@gmail.com> Cc: Arnd Bergmann <arnd@arndb.de> Cc: Benno Lossin <benno.lossin@proton.me> Cc: Björn Roy Baron <bjorn3_gh@protonmail.com> Cc: Boqun Feng <boqun.feng@gmail.com> Cc: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Cc: Jann Horn <jannh@google.com> Cc: John Hubbard <jhubbard@nvidia.com> Cc: Matthew Wilcox (Oracle) <willy@infradead.org> Cc: Miguel Ojeda <ojeda@kernel.org> Cc: Suren Baghdasaryan <surenb@google.com> Cc: Trevor Gross <tmgross@umich.edu> Cc: Vlastimil Babka <vbabka@suse.cz> Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
2025-05-12rust: replace rustdoc references to alloc::formatAndrew Ballance
Replace alloc::format[1] in the pr_* and dev_* macros' doc comments with std::format[2] because they are identical but less likely to get confused with the kernel's alloc crate. And add a url link for the std::format! macro. Link: https://doc.rust-lang.org/alloc/macro.format.html [1] Link: https://doc.rust-lang.org/std/macro.format.html [2] Reviewed-by: Benno Lossin <benno.lossin@proton.me> Signed-off-by: Andrew Ballance <andrewjballance@gmail.com> Link: https://lore.kernel.org/r/20250325133352.441425-1-andrewjballance@gmail.com [ Fixed typo and reworded slightly. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-12rust: convert raw URLs to Markdown autolinks in commentsXizhe Yin
Some comments in Rust files use raw URLs (http://example.com) rather than Markdown autolinks <URL>. This inconsistency makes the documentation less uniform and harder to maintain. This patch converts all remaining raw URLs in Rust code comments to use the Markdown autolink format, maintaining consistency with the rest of the codebase which already uses this style. Suggested-by: Miguel Ojeda <ojeda@kernel.org> Link: https://github.com/Rust-for-Linux/linux/issues/1153 Signed-off-by: Xizhe Yin <xizheyin@smail.nju.edu.cn> Link: https://lore.kernel.org/r/509F0B66E3C1575D+20250407033441.5567-1-xizheyin@smail.nju.edu.cn [ Used From form for Signed-off-by. Sorted tags. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-12rust: clarify the language unstable features in useMiguel Ojeda
We track the details of which Rust features we use at our usual "live list" [1] (and its sub-lists), but in light of a discussion in the LWN article [2], it would help to clarify it in the source code. In particular, we are very close to rely only on stable Rust language-wise -- essentially only two language features remain (including the `kernel` crate). Thus add some details in both the feature list of the `kernel` crate as well as the list of allowed features. This does not over every single feature, and there are quite a few non-language features that we use too. To have the full picture, please refer to [1]. Link: https://github.com/Rust-for-Linux/linux/issues/2 [1] Link: https://lwn.net/Articles/1015409/ [2] Suggested-by: Andreas Hindborg <a.hindborg@kernel.org> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Link: https://lore.kernel.org/r/20250327211302.286313-1-ojeda@kernel.org [ Improved comments with suggestions from the list. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-12rust: uaccess: take advantage of the prelude and `Result`'s defaultsMiguel Ojeda
The `kernel` prelude brings `Result` and the error codes; and the prelude itself is already available in the examples automatically. In addition, `Result` already defaults to `T = ()`. Thus simplify. Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250429151445.438977-1-ojeda@kernel.org Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-12rust: static_assert: add optional messageAltan Ozlu
Add an optional panic message to the `static_assert!` macro. The panic message doesn't support argument formatting, because the `assert!` macro only supports formatting in non-const contexts. Suggested-by: Miguel Ojeda <ojeda@kernel.org> Link: https://github.com/Rust-for-Linux/linux/issues/1149 Signed-off-by: Altan Ozlu <altan@ozlu.eu> Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Trevor Gross <tmgross@umich.edu> Link: https://lore.kernel.org/r/20250326202520.1176162-2-altan@ozlu.eu Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-12rust: page: optimize rust symbol generation for PageKunwu Chan
When build the kernel using the llvm-18.1.3-rust-1.85.0-x86_64 with ARCH=arm64, the following symbols are generated: $nm vmlinux | grep ' _R'.*Page | rustfilt ffff8000805b6f98 T <kernel::page::Page>::alloc_page ffff8000805b715c T <kernel::page::Page>::fill_zero_raw ffff8000805b720c T <kernel::page::Page>::copy_from_user_slice_raw ffff8000805b6fb4 T <kernel::page::Page>::read_raw ffff8000805b7088 T <kernel::page::Page>::write_raw ffff8000805b72fc T <kernel::page::Page as core::ops::drop::Drop>::drop These Rust symbols(alloc_page and drop) are trivial wrappers around the C functions alloc_pages and __free_pages. It doesn't make sense to go through a trivial wrapper for these functions, so mark them inline. Link: https://github.com/Rust-for-Linux/linux/issues/1145 Suggested-by: Alice Ryhl <aliceryhl@google.com> Co-developed-by: Grace Deng <Grace.Deng006@Gmail.com> Signed-off-by: Grace Deng <Grace.Deng006@Gmail.com> Signed-off-by: Kunwu Chan <kunwu.chan@hotmail.com> Reviewed-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20250321080124.484647-1-kunwu.chan@linux.dev [ Removed spurious colon in title. - Miguel ] Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-05-07rust: alloc: add Vec::insert_within_capacityAlice Ryhl
This adds a variant of Vec::insert that does not allocate memory. This makes it safe to use this function while holding a spinlock. Rust Binder uses it for the range allocator fast path. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/20250502-vec-methods-v5-7-06d20ad9366f@google.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07rust: alloc: add Vec::removeAlice Ryhl
This is needed by Rust Binder in the range allocator, and by upcoming GPU drivers during firmware initialization. Panics in the kernel are best avoided when possible, so an error is returned if the index is out of bounds. An error type is used rather than just returning Option<T> to let callers handle errors with ?. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/20250502-vec-methods-v5-6-06d20ad9366f@google.com [ Remove `# Panics` section; `Vec::remove() handles the error properly.` - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07rust: alloc: add Vec::retainAlice Ryhl
This adds a common Vec method called `retain` that removes all elements that don't match a certain condition. Rust Binder uses it to find all processes that match a given pid. The stdlib retain method takes &T rather than &mut T and has a separate retain_mut for the &mut T case. However, this is considered an API mistake that can't be fixed now due to backwards compatibility. There's no reason for us to repeat that mistake. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/20250502-vec-methods-v5-5-06d20ad9366f@google.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07rust: alloc: add Vec::drain_allAlice Ryhl
This is like the stdlib method drain, except that it's hard-coded to use the entire vector's range. Rust Binder uses it in the range allocator to take ownership of everything in a vector in a case where reusing the vector is desirable. Implementing `DrainAll` in terms of `slice::IterMut` lets us reuse some nice optimizations in core for the case where T is a ZST. Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/20250502-vec-methods-v5-4-06d20ad9366f@google.com Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-05-07rust: alloc: add Vec::push_within_capacityAlice Ryhl
This introduces a new method called `push_within_capacity` for appending to a vector without attempting to allocate if the capacity is full. Rust Binder will use this in various places to safely push to a vector while holding a spinlock. The implementation is moved to a push_within_capacity_unchecked method. This is preferred over having push() call push_within_capacity() followed by an unwrap_unchecked() for simpler unsafe. Panics in the kernel are best avoided when possible, so an error is returned if the vector does not have sufficient capacity. An error type is used rather than just returning Result<(),T> to make it more convenient for callers (i.e. they can use ? or unwrap). Signed-off-by: Alice Ryhl <aliceryhl@google.com> Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org> Reviewed-by: Benno Lossin <lossin@kernel.org> Link: https://lore.kernel.org/r/20250502-vec-methods-v5-3-06d20ad9366f@google.com [ Remove public visibility from `Vec::push_within_capacity_unchecked()`. - Danilo ] Signed-off-by: Danilo Krummrich <dakr@kernel.org>