Commit Graph

833 Commits

Author SHA1 Message Date
FUJITA Tomonori
f65a3218fd rust: net::phy represent DeviceId as transparent wrapper over mdio_device_id
Refactor the DeviceId struct to be a #[repr(transparent)] wrapper
around the C struct bindings::mdio_device_id.

This refactoring is a preparation for enabling the PHY abstractions to
use the RawDeviceId trait.

Acked-by: Jakub Kicinski <kuba@kernel.org>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://lore.kernel.org/r/20250711040947.1252162-3-fujita.tomonori@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-16 23:39:07 +02:00
FUJITA Tomonori
8d84b32075 rust: device_id: split out index support into a separate trait
Introduce a new trait `RawDeviceIdIndex`, which extends `RawDeviceId`
to provide support for device ID types that include an index or
context field (e.g., `driver_data`). This separates the concerns of
layout compatibility and index-based data embedding, and allows
`RawDeviceId` to be implemented for types that do not contain a
`driver_data` field. Several such structures are defined in
include/linux/mod_devicetable.h.

Refactor `IdArray::new()` into a generic `build()` function, which
takes an optional offset. Based on the presence of `RawDeviceIdIndex`,
index writing is conditionally enabled. A new `new_without_index()`
constructor is also provided for use cases where no index should be
written.

This refactoring is a preparation for enabling the PHY abstractions to
use the RawDeviceId trait.

The changes to acpi.rs and driver.rs were made by Danilo.

Reviewed-by: Trevor Gross <tmgross@umich.edu>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://lore.kernel.org/r/20250711040947.1252162-2-fujita.tomonori@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-16 23:38:21 +02:00
Alice Ryhl
2f5606afa4 device: rust: rename Device::as_ref() to Device::from_raw()
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-16 23:37:49 +02:00
Miguel Ojeda
8ecb65b7b6 Alloc & DMA changes for v6.17
Box:
   - Implement Borrow / BorrowMut for Box<T, A>.
 
 Vec:
   - Implement Default for Vec<T, A>.
 
   - Implement Borrow / BorrowMut for Vec<T, A>.
 
 DMA:
   - Clarify wording and be consistent in 'coherent' nomenclature.
 
   - Convert the read!() / write!() macros to return a Result.
 
   - Add as_slice() / write() methods in CoherentAllocation.
 
   - Fix doc-comment of dma_handle().
 
   - Expose count() and size() in CoherentAllocation and add the
     corresponding type invariants.
 
   - Implement CoherentAllocation::dma_handle_with_offset().
 
   - Require mutable reference for as_slice_mut() and write().
 
 - Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo Stoakes
   as reviewers (thanks everyone).
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaHZWlAAKCRBFlHeO1qrK
 LgBrAQDgp1+5ocMJKJDgBtCXpRCe2F9OBz9L7CY1EzSRz2JHTAD/YZ5D1DeSi1l8
 U+tqG9+5i8twB3PR/TC4d7+GaBfTcQQ=
 =LaOk
 -----END PGP SIGNATURE-----

Merge tag 'alloc-next-v6.17-2025-07-15' of https://github.com/Rust-for-Linux/linux into rust-next

Pull alloc and DMA updates from Danilo Krummrich:

  Box:
   - Implement Borrow / BorrowMut for Box<T, A>.

  Vec:
   - Implement Default for Vec<T, A>.

   - Implement Borrow / BorrowMut for Vec<T, A>.

  DMA:
   - Clarify wording and be consistent in 'coherent' nomenclature.

   - Convert the read!() / write!() macros to return a Result.

   - Add as_slice() / write() methods in CoherentAllocation.

   - Fix doc-comment of dma_handle().

   - Expose count() and size() in CoherentAllocation and add the
     corresponding type invariants.

   - Implement CoherentAllocation::dma_handle_with_offset().

   - Require mutable reference for as_slice_mut() and write().

  MAINTAINERS:
   - Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo
     Stoakes as reviewers (thanks everyone).

* tag 'alloc-next-v6.17-2025-07-15' of https://github.com/Rust-for-Linux/linux:
  MAINTAINERS: add mm folks as reviewers to rust alloc
  rust: dma: require mutable reference for as_slice_mut() and write()
  rust: dma: add dma_handle_with_offset method to CoherentAllocation
  rust: dma: expose the count and size of CoherentAllocation
  rust: dma: fix doc-comment of dma_handle()
  rust: dma: add as_slice/write functions for CoherentAllocation
  rust: dma: convert the read/write macros to return Result
  rust: dma: clarify wording and be consistent in `coherent` nomenclature
  rust: alloc: implement `Borrow` and `BorrowMut` for `KBox`
  rust: alloc: implement `Borrow` and `BorrowMut` for `Vec`
  rust: vec: impl Default for Vec with any allocator
2025-07-15 23:42:55 +02:00
Alice Ryhl
7c098cd5ea workqueue: rust: add delayed work items
This patch is being sent for use in the various Rust GPU drivers that
are under development. It provides the additional feature of work items
that are executed after a delay.

The design of the existing workqueue is rather extensible, as most of
the logic is reused for delayed work items even though a different work
item type is required. The new logic consists of:

* A new DelayedWork struct that wraps struct delayed_work.
* A new impl_has_delayed_work! macro that provides adjusted versions of
  the container_of logic, that is suitable with delayed work items.
* A `enqueue_delayed` method that can enqueue a delayed work item.

This patch does *not* rely on the fact that `struct delayed_work`
contains `struct work_struct` at offset zero. It will continue to work
even if the layout is changed to hold the `work` field at a different
offset.

Please see the example introduced at the top of the file for example
usage of delayed work items.

Acked-by: Tejun Heo <tj@kernel.org>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250711-workqueue-delay-v3-1-3fe17b18b9d1@google.com
[ Replaced `as _` with `as ffi::c_int` to clean warning. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-15 22:54:52 +02:00
Alice Ryhl
64fb810bce rust: types: rename Opaque::raw_get to cast_into
In the previous patch we added Opaque::cast_from() that performs the
opposite operation to Opaque::raw_get(). For consistency with this
naming, rename raw_get() to cast_from().

There are a few other options such as calling cast_from() something
closer to raw_get() rather than renaming this method. However, I could
not find a great naming scheme that works with raw_get(). The previous
version of this patch used from_raw(), but functions of that name
typically have a different signature, so that's not a great option.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Benno Lossin <lossin@kernel.org>
Acked-by: Andreas Hindborg <a.hindborg@kernel.org>
Acked-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250624-opaque-from-raw-v2-2-e4da40bdc59c@google.com
[ Removed `HrTimer::raw_get` change. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-15 22:26:11 +02:00
Alice Ryhl
8802e16843 rust: types: add Opaque::cast_from
Since commit b20fbbc08a ("rust: check type of `$ptr` in
`container_of!`") we have enforced that the field pointer passed to
container_of! must match the declared field. This caused mismatches when
using a pointer to bindings::x for fields of type Opaque<bindings::x>.

This situation encourages the user to simply pass field.cast() to the
container_of! macro, but this is not great because you might
accidentally pass a *mut bindings::y when the field type is
Opaque<bindings::x>, which would be wrong.

To help catch this kind of mistake, add a new Opaque::cast_from that
wraps a raw pointer in Opaque without changing the inner type. Also
update the docs to reflect this as well as some existing users.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Andreas Hindborg <a.hindborg@kernel.org>
Acked-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250624-opaque-from-raw-v2-1-e4da40bdc59c@google.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-15 21:01:48 +02:00
Daniel Almeida
9b614ceada
rust: regulator: add a bare minimum regulator abstraction
Add a bare minimum regulator abstraction to be used by Rust drivers.
This abstraction adds a small subset of the regulator API, which is
thought to be sufficient for the drivers we have now.

Regulators provide the power needed by many hardware blocks and thus are
likely to be needed by a lot of drivers.

It was tested on rk3588, where it was used to power up the "mali"
regulator in order to power up the GPU.

Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Daniel Almeida <daniel.almeida@collabora.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://patch.msgid.link/20250714-topics-tyr-regulator2-v8-1-c7ab3955d524@collabora.com
Signed-off-by: Mark Brown <broonie@kernel.org>
2025-07-15 15:07:40 +01:00
Danilo Krummrich
47e6715bb7 rust: device: implement Device::as_bound()
Provide an unsafe functions for abstractions to convert a regular
&Device to a &Device<Bound>.

This is useful for registrations that provide certain guarantees for the
scope of their callbacks, such as IRQs or certain class device
registrations (e.g. PWM, miscdevice).

Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250713182737.64448-2-dakr@kernel.org
[ Remove unnecessary cast(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-15 14:56:56 +02:00
Danilo Krummrich
85aa5b16fe rust: devres: provide an accessor for the device
Provide an accessor for the Device a Devres instance has been created
with.

For instance, this is useful when registrations want to provide a
&Device<Bound> for a scope that is protected by Devres.

Suggested-by: Benno Lossin <lossin@kernel.org>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250713182737.64448-1-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-15 14:46:13 +02:00
Danilo Krummrich
91ae26b06a rust: devres: initialize Devres::inner::data last
Users may want to access the Devres object from callbacks registered
through the initialization of Devres::inner::data.

For those accesses to be valid, Devres::inner::data must be initialized
last [1].

Credit to Boqun for spotting this [2].

Link: https://lore.kernel.org/lkml/DBBPHO26CPBS.2OVI1OERCB2J5@kernel.org/ [1]
Link: https://lore.kernel.org/lkml/aHSmxWeIy3L-AKIV@Mac.home/ [2]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250714113712.22158-1-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-15 14:46:09 +02:00
Ritvik Gupta
a507f8230d rust: cpumask: Replace MaybeUninit and mem::zeroed with Opaque APIs
Replace the following unsafe initializations:
1. `MaybeUninit::uninit().assume_init()` with `Opaque::uninit()`
2. `core::mem::zeroed()` with `Opaque::zeroed()`

Suggested-by: Benno Lossin <lossin@kernel.org>
Link: https://github.com/Rust-for-Linux/linux/issues/1178
Suggested-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/rust-for-linux/CAH5fLgj0OoCn56OkNUmiPQ=RAVa_VmS-yMZ4TNBSpGPNtZ5D0A@mail.gmail.com/
Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Ritvik Gupta <ritvikfoss@gmail.com>
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-07-15 08:31:12 +05:30
Andreas Hindborg
a68a6bef0e rust: types: require ForeignOwnable::into_foreign return non-null
The intended implementations of `ForeignOwnable` will not return null
pointers from `into_foreign`, as this would render the implementation of
`try_from_foreign` useless. Current users of `ForeignOwnable` rely on
`into_foreign` returning non-null pointers. So require `into_foreign` to
return non-null pointers.

Suggested-by: Benno Lossin <lossin@kernel.org>
Suggested-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250612-pointed-to-v3-2-b009006d86a1@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-14 23:55:24 +02:00
Andreas Hindborg
12717ebeff rust: types: add FOREIGN_ALIGN to ForeignOwnable
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-14 23:55:24 +02:00
Onur Özkan
b6f885060e rust: rbtree: simplify finding current in remove_current
The previous version used a verbose `match` to get
`current`, which may be slightly confusing at first
glance.

This change makes it shorter and more clearly expresses
the intent: prefer `next` if available, otherwise fall
back to `prev`.

Signed-off-by: Onur Özkan <work@onurozkan.dev>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250708075850.25789-1-work@onurozkan.dev
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-14 23:53:35 +02:00
Alice Ryhl
60ecf796cd rust: uaccess: use newtype for user pointers
Currently, Rust code uses a typedef for unsigned long to represent
userspace addresses. This is unfortunate because it means that userspace
addresses could accidentally be mixed up with other integers. To
alleviate that, we introduce a new UserPtr struct that wraps a raw
pointer to represent a userspace address. By using a struct, type
checking enforces that userspace addresses cannot be mixed up with
anything else.

This is similar to the __user annotation in C that detects cases where
user pointers are mixed with non-user pointers.

Note that unlike __user pointers in C, this type is just a pointer
without a target type. This means that it can't detect cases such as
mixing up which struct this user pointer references. However, that is
okay due to the way this is intended to be used - generally, you create
a UserPtr in your ioctl callback from the provided usize *before*
dispatching on which ioctl is in use, and then after dispatching on the
ioctl you pass the UserPtr into a UserSliceReader or UserSliceWriter;
selecting the target type does not happen until you have obtained the
UserSliceReader/Writer.

The UserPtr type is not marked with #[derive(Debug)], which means that
it's not possible to print values of this type. This avoids ASLR
leakage.

The type is added to the prelude as it is a fairly fundamental type
similar to c_int. The wrapping_add() method is renamed to
wrapping_byte_add() for consistency with the method name found on raw
pointers.

Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Christian Schrefl <chrisi.schrefl@gmail.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250616-userptr-newtype-v3-1-5ff7b2d18d9e@google.com
[ Reworded title. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-14 23:52:45 +02:00
Miguel Ojeda
7498159226 rust: use #[used(compiler)] to fix build and modpost with Rust >= 1.89.0
Starting with Rust 1.89.0 (expected 2025-08-07), the Rust compiler fails
to build the `rusttest` target due to undefined references such as:

    kernel...-cgu.0:(.text....+0x116): undefined reference to
    `rust_helper_kunit_get_current_test'

Moreover, tooling like `modpost` gets confused:

    WARNING: modpost: missing MODULE_DESCRIPTION() in drivers/gpu/drm/nova/nova.o
    ERROR: modpost: missing MODULE_LICENSE() in drivers/gpu/nova-core/nova_core.o

The reason behind both issues is that the Rust compiler will now [1]
treat `#[used]` as `#[used(linker)]` instead of `#[used(compiler)]`
for our targets. This means that the retain section flag (`R`,
`SHF_GNU_RETAIN`) will be used and that they will be marked as `unique`
too, with different IDs. In turn, that means we end up with undefined
references that did not get discarded in `rusttest` and that multiple
`.modinfo` sections are generated, which confuse tooling like `modpost`
because they only expect one.

Thus start using `#[used(compiler)]` to keep the previous behavior
and to be explicit about what we want. Sadly, it is an unstable feature
(`used_with_arg`) [2] -- we will talk to upstream Rust about it. The good
news is that it has been available for a long time (Rust >= 1.60) [3].

The changes should also be fine for previous Rust versions, since they
behave the same way as before [4].

Alternatively, we could use `#[no_mangle]` or `#[export_name = ...]`
since those still behave like `#[used(compiler)]`, but of course it is
not really what we want to express, and it requires other changes to
avoid symbol conflicts.

Cc: David Wood <david@davidtw.co>
Cc: Wesley Wiser <wwiser@gmail.com>
Cc: stable@vger.kernel.org # Needed in 6.12.y and later (Rust is pinned in older LTSs).
Link: https://github.com/rust-lang/rust/pull/140872 [1]
Link: https://github.com/rust-lang/rust/issues/93798 [2]
Link: https://github.com/rust-lang/rust/pull/91504 [3]
Link: https://godbolt.org/z/sxzWTMfzW [4]
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Björn Roy Baron <bjorn3_gh@protonmail.com>
Link: https://lore.kernel.org/r/20250712160103.1244945-3-ojeda@kernel.org
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-14 23:30:44 +02:00
Peter Zijlstra
8f2146159b Merge branch 'tip/sched/urgent'
Avoid merge conflicts

Signed-off-by: Peter Zijlstra <peterz@infradead.org>
2025-07-14 17:16:28 +02:00
Alice Ryhl
de747bd023
poll: rust: allow poll_table ptrs to be null
It's possible for a poll_table to be null. This can happen if an
end-user just wants to know if a resource has events right now without
registering a waiter for when events become available. Furthermore,
these null pointers should be handled transparently by the API, so we
should not change `from_ptr` to return an `Option`. Thus, change
`PollTable` to wrap a raw pointer rather than use a reference so that
you can pass null.

Comments mentioning `struct poll_table` are changed to just `poll_table`
since `poll_table` is a typedef. (It's a typedef because it's supposed
to be opaque.)

Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
2025-07-14 14:12:24 +02:00
Alice Ryhl
17bbbefbf6 rust: uaccess: add UserSliceReader::strcpy_into_buf
This patch adds a more convenient method for reading C strings from
userspace. Logic is added to NUL-terminate the buffer when necessary so
that a &CStr can be returned.

Note that we treat attempts to read past `self.length` as a fault, so
this returns EFAULT if that limit is exceeded before `buf.len()` is
reached.

Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250616-strncpy-from-user-v5-2-2d3fb0e1f5af@google.com
[ Use `from_mut` to clean `clippy::ref_as_ptr` lint. Reworded
  title. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-14 01:34:12 +02:00
Alice Ryhl
8da881d39c rust: uaccess: add strncpy_from_user
This patch adds a direct wrapper around the C function of the same name.
It's not really intended for direct use by Rust code since
strncpy_from_user has a somewhat unfortunate API where it only
nul-terminates the buffer if there's space for the nul-terminator. This
means that a direct Rust wrapper around it could not return a &CStr
since the buffer may not be a cstring. However, we still add the method
to build more convenient APIs on top of it, which will happen in
subsequent patches.

Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250616-strncpy-from-user-v5-1-2d3fb0e1f5af@google.com
[ Reworded title. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-14 01:33:26 +02:00
Miguel Ojeda
e8fa0481ea pin-init changes for v6.17
Added:
 
 - 'impl<T, E> [Pin]Init<T, E> for Result<T, E>', so results are now
   (pin-)initializers.
 
 - 'Zeroable::init_zeroed()' delegating to 'init_zeroed()'.
 
 - New 'zeroed()', a safe version of 'mem::zeroed()' and also provide
   it via 'Zeroable::zeroed()'.
 
 - Implement 'Zeroable' for 'Option<&T>' and 'Option<&mut T>'.
 
 - Implement 'Zeroable' 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:
 
 - More CI improvements to deny warnings, use '--all-targets'. Also check
   the synchronization status of the two '-next' branches in upstream and
   the kernel.
 -----BEGIN PGP SIGNATURE-----
 
 iIgEABYKADAWIQQjEG/HT3UeYLJybLTomd21rZaLygUCaGqd4RIcbG9zc2luQGtl
 cm5lbC5vcmcACgkQ6Jndta2Wi8qKagD/aBH4iwbal0DHbYx36TMfkvunp6pkKAo1
 uu7qbmNwMMwBAKuRb41xA2AvllcYy/aMsb5H00o3iVLOzpMUHNnOFdIJ
 =0DbP
 -----END PGP SIGNATURE-----

Merge tag 'pin-init-v6.17' of https://github.com/Rust-for-Linux/linux into rust-next

Pull pin-init updates from Benno Lossin:
 "Added:

   - 'impl<T, E> [Pin]Init<T, E> for Result<T, E>', so results are now
     (pin-)initializers.

   - 'Zeroable::init_zeroed()' delegating to 'init_zeroed()'.

   - New 'zeroed()', a safe version of 'mem::zeroed()' and also provide
     it via 'Zeroable::zeroed()'.

   - Implement 'Zeroable' for 'Option<&T>' and 'Option<&mut T>'.

   - Implement 'Zeroable' 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:

   - More CI improvements to deny warnings, use '--all-targets'. Also
     check the synchronization status of the two '-next' branches in
     upstream and the kernel."

Acked-by: Andreas Hindborg <a.hindborg@kernel.org>

* tag 'pin-init-v6.17' of https://github.com/Rust-for-Linux/linux:
  rust: pin-init: examples, tests: use `ignore` instead of conditionally compiling tests
  rust: init: remove doctest's `Error::from_errno` workaround
  rust: init: re-enable doctests
  rust: pin-init: implement `ZeroableOption` for function pointers with up to 20 arguments
  rust: pin-init: change `impl Zeroable for Option<NonNull<T>>` to `ZeroableOption for NonNull<T>`
  rust: pin-init: implement `ZeroableOption` for `&T` and `&mut T`
  rust: pin-init: add `zeroed()` & `Zeroable::zeroed()` functions
  rust: pin-init: add `Zeroable::init_zeroed`
  rust: pin-init: rename `zeroed` to `init_zeroed`
  rust: pin-init: feature-gate the `stack_init_reuse` test on the `std` feature
  rust: pin-init: examples: pthread_mutex: disable the main test for miri
  rust: pin-init: examples, tests: add conditional compilation in order to compile under any feature combination
  rust: pin-init: change blanket impls for `[Pin]Init` and add one for `Result<T, E>`
  rust: pin-init: improve safety documentation for `impl<T> [Pin]Init<T> for T`
2025-07-13 23:05:14 +02:00
Jason Devers
99214efede rust: sync: Add #[must_use] to Lock::try_lock()
The `Lock::try_lock()` function returns an `Option<Guard<...>>`, but it
currently does not issue a warning if the return value is unused.
To avoid potential bugs, the `#[must_use]` annotation is added to ensure
proper usage.

Note that `T` is `#[must_use]` but `Option<T>` is not.
For more context, see: https://github.com/rust-lang/rust/issues/71368.

Suggested-by: Alice Ryhl <aliceryhl@google.com>
Link: https://github.com/Rust-for-Linux/linux/issues/1133
Signed-off-by: Jason Devers <dev.json2@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20241212154753.139563-1-dev.json2@gmail.com
2025-07-11 15:11:54 -07:00
Alice Ryhl
917b10d909 drm: rust: rename as_ref() to from_raw() for drm constructors
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>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250711-device-as-ref-v2-2-1b16ab6402d7@google.com
2025-07-11 16:30:30 +02:00
Simona Vetter
b7dc79a633 Merge tag 'drm-misc-fixes-2025-07-10' of https://gitlab.freedesktop.org/drm/misc/kernel into drm-fixes
drm-misc-fixes for v6.16-rc6 or final:
- Fix nouveau fail on debugfs errors.
- Magic 50 ms to fix nouveau suspend.
- Call rust destructor on drm device release.
- Fix DMA api error handling in tegra/nvdec.
- Fix PVR device reset.
- Habanalabs maintainer update.
- Small memory leak fix when nouveau acpi init fails.
- Do not attempt to bind to any PCI device with AGP capability.
- Make FB's acquire handles on backing object, same as i915/xe already does.
- Fix race in drm_gem_handle_create_tail.

Signed-off-by: Simona Vetter <simona.vetter@ffwll.ch>
From: Maarten Lankhorst <maarten.lankhorst@linux.intel.com>
Link: https://patchwork.freedesktop.org/patch/msgid/e522cdc7-1787-48f2-97e5-0f94783970ab@linux.intel.com
2025-07-11 14:11:19 +02:00
Danilo Krummrich
18ebb25dfa rust: pci: implement Driver::unbind()
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-8-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-09 00:04:33 +02:00
Danilo Krummrich
4be5f3fff1 rust: platform: implement Driver::unbind()
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-09 00:04:33 +02:00
Danilo Krummrich
c46f60246f rust: auxiliary: use generic device drvdata accessors
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-6-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-09 00:04:33 +02:00
Danilo Krummrich
4231712c8e rust: pci: use generic device drvdata accessors
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-5-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-09 00:04:33 +02:00
Danilo Krummrich
f0a68a912c rust: platform: use generic device drvdata accessors
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-09 00:04:33 +02:00
Danilo Krummrich
880dec12a2 rust: device: add drvdata accessors
Implement generic accessors for the private data of a driver bound to a
device.

Those accessors should be used by bus abstractions from their
corresponding core callbacks, such as probe(), remove(), etc.

Implementing them for device::CoreInternal guarantees that driver's can't
interfere with the logic implemented by the bus abstraction.

Acked-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250621195118.124245-3-dakr@kernel.org
[ Improve safety comment as proposed by Benno. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-09 00:04:33 +02:00
Danilo Krummrich
fa7486d3f9 rust: device: introduce device::CoreInternal
Introduce an internal device context, which is semantically equivalent
to the Core device context, but reserved for bus abstractions.

This allows implementing methods for the Device type, which are limited
to be used within the core context of bus abstractions, i.e. restrict
the availability for drivers.

Link: https://lore.kernel.org/r/20250621195118.124245-2-dakr@kernel.org
[ Rename device::Internal to device::CoreInternal. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-09 00:04:05 +02:00
Maarten Lankhorst
e21354aea4 Merge remote-tracking branch 'drm/drm-next' into drm-misc-next
Pull in drm-intel-next for the updates to drm panic handling.

Signed-off-by: Maarten Lankhorst <dev@lankhorst.se>
2025-07-08 16:49:07 +02:00
Rahul Rameshbabu
5cddd546df rust: pci: fix documentation related to Device instances
Device instances in the pci crate represent a valid struct pci_dev, not a
struct device.

Fixes: 7b948a2af6 ("rust: pci: fix unrestricted &mut pci::Device")
Signed-off-by: Rahul Rameshbabu <sergeantsagara@protonmail.com>
Link: https://lore.kernel.org/r/20250706035944.18442-3-sergeantsagara@protonmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-07 14:32:09 +02:00
Tamir Duberstein
db15ec7abd rust: miscdevice: remove unnecessary import
`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-miscdevice-v1-1-bb9e9b17c892@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-07-06 10:38:27 +02:00
Tamir Duberstein
6d16cd5769 rust: devres: remove unused import
As far as I can tell, `c_str` was never used, hence remove it.

Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://lore.kernel.org/r/20250704-cstr-include-devres-v1-1-4ee9e56fca09@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-05 17:07:24 +02:00
Tamir Duberstein
65f8f0d4e0 rust: auxiliary: remove unnecessary import
`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-aux-v1-1-e1a404ae92ac@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-05 17:07:24 +02:00
Tamir Duberstein
8ae33576ea rust: platform: remove unnecessary import
`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-07-05 17:07:24 +02:00
Tamir Duberstein
31e4add7a3 rust: drm: remove unnecessary imports
`kernel::str::CStr` is included in the prelude.

Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250704-cstr-include-drm-v1-1-a279dfc4d753@gmail.com
2025-07-05 13:03:54 +02:00
Tamir Duberstein
3d44147494 rust: drm: remove unnecessary imports
`kernel::str::CStr` is included in the prelude.

Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250704-cstr-include-drm-v1-1-a279dfc4d753@gmail.com
2025-07-05 13:01:59 +02:00
Danilo Krummrich
2e9fdbe5ec rust: drm: device: drop_in_place() the drm::Device in release()
In drm::Device::new() we allocate with __drm_dev_alloc() and return an
ARef<drm::Device>.

When the reference count of the drm::Device falls to zero, the C code
automatically calls drm_dev_release(), which eventually frees the memory
allocated in drm::Device::new().

However, due to that, drm::Device::drop() is never called. As a result
the destructor of the user's private data, i.e. drm::Device::data is
never called. Hence, fix this by calling drop_in_place() from the DRM
device's release callback.

Fixes: 1e4b8896c0 ("rust: drm: add device abstraction")
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250629153747.72536-1-dakr@kernel.org
2025-07-04 00:33:56 +02:00
Alexandre Courbot
2009a2d569 rust: sync: implement Borrow and BorrowMut for Arc types
Implement `Borrow<T>` and `BorrowMut<T>` for `UniqueArc<T>`, and
`Borrow<T>` for `Arc<T>`. This allows these containers to be used in
generic APIs asking for types implementing those traits. `T` and `&mut
T` also implement those traits allowing users to use either owned,
shared or borrowed values.

`ForeignOwnable` makes a call to its own `borrow` method which must be
disambiguated.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250616-borrow_impls-v4-2-36f9beb3fe6a@nvidia.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-07-03 20:46:29 +02:00
Miguel Ojeda
97ba207a99 rust: acpi: remove unneeded cast to clean future Clippy warning
A future Clippy warning, `clippy::as_underscore`, is getting enabled in
parallel in the rust-next tree:

    error: using `as _` conversion
      --> rust/kernel/acpi.rs:25:9
       |
    25 |         self.0.driver_data as _
       |         ^^^^^^^^^^^^^^^^^^^^^^-
       |                               |
       |                               help: consider giving the type explicitly: `usize`

The type is already `ulong`, which nowadays is always `usize`, so the
cast is unneeded. Thus remove it, which in turn will avoid the warning
in the future.

Other abstractions of device tables do not use a cast here either.

Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Link: https://lore.kernel.org/r/20250701174656.62205-1-ojeda@kernel.org
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-07-03 19:18:59 +02:00
Danilo Krummrich
2dedf83d54 rust: dma: require mutable reference for as_slice_mut() and write()
Given the safety requirements of as_slice_mut() and write() taking an
immutable reference is technically not incorrect.

However, let's leverage the compiler's capabilities and require a
mutable reference to ensure exclusive access.

This also fixes a clippy warning introduced with 1.88:

  warning: mutable borrow from immutable input(s)
     --> rust/kernel/dma.rs:297:78
      |
  297 |     pub unsafe fn as_slice_mut(&self, offset: usize, count: usize) -> Result<&mut [T]> {
      |                                                                              ^^^^^^^^

Fixes: d37a39f607 ("rust: dma: add as_slice/write functions for CoherentAllocation")
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Abdiel Janulgue <abdiel.janulgue@gmail.com>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250628165120.90149-1-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-07-01 14:14:40 +02:00
Shankari Anand
b9ff1c2a26 rust: miscdevice: clarify invariant for MiscDeviceRegistration
Reword and expand the invariant documentation for `MiscDeviceRegistration`
to clarify what it means for the inner device to be "registered".
It expands to explain:
- `inner` points to a `miscdevice` registered via `misc_register`.
- This registration stays valid for the entire lifetime of the object.
- Deregistration is guaranteed on `Drop`, via `misc_deregister`.

Reported-by: Benno Lossin <lossin@kernel.org>
Closes: https://github.com/Rust-for-Linux/linux/issues/1168
Fixes: f893691e74 ("rust: miscdevice: add base miscdevice abstraction")
Signed-off-by: Shankari Anand <shankari.ak0208@gmail.com>
Link: https://lore.kernel.org/r/20250626104520.563036-1-shankari.ak0208@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-07-01 11:21:10 +02:00
FUJITA Tomonori
9b5cdd5f40 rust: fix typo in #[repr(transparent)] comments
Fix a typo in several comments where `#[repr(transparent)]` was
mistakenly written as `#[repr(transparent)` (missing closing
bracket).

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://lore.kernel.org/r/20250623225846.169805-1-fujita.tomonori@gmail.com
Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-07-01 11:21:04 +02:00
Tamir Duberstein
c9a7bcd2c0 Cast to the proper type
Use the ffi type rather than the resolved underlying type.

Acked-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Link: https://patch.msgid.link/20250625-correct-type-cast-v2-2-6f2c29729e69@gmail.com
Signed-off-by: Paolo Abeni <pabeni@redhat.com>
2025-07-01 09:49:18 +02:00
Tamir Duberstein
22955d942f Use unqualified references to ffi types
Remove unnecessary qualifications; `kernel::ffi::*` is included in
`kernel::prelude`.

Signed-off-by: Tamir Duberstein <tamird@gmail.com>
Reviewed-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://patch.msgid.link/20250625-correct-type-cast-v2-1-6f2c29729e69@gmail.com
Signed-off-by: Paolo Abeni <pabeni@redhat.com>
2025-07-01 09:49:18 +02:00
FUJITA Tomonori
d4b29ddf82 rust: time: Add wrapper for fsleep() function
Add a wrapper for fsleep(), flexible sleep functions in
include/linux/delay.h which typically deals with hardware delays.

The kernel supports several sleep functions to handle various lengths
of delay. This adds fsleep(), automatically chooses the best sleep
method based on a duration.

fsleep() can only be used in a nonatomic context. This requirement is
not checked by these abstractions, but it is intended that klint [1]
or a similar tool will be used to check it in the future.

Link: https://rust-for-linux.com/klint [1]
Reviewed-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Fiona Behrens <me@kloenk.dev>
Tested-by: Daniel Almeida <daniel.almeida@collabora.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://lore.kernel.org/r/20250617144155.3903431-3-fujita.tomonori@gmail.com
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-06-30 13:22:05 +02:00
FUJITA Tomonori
fc38b7ff87 rust: time: Seal the HrTimerMode trait
Prevent downstream crates or drivers from implementing `HrTimerMode`
for arbitrary types, which could otherwise leads to unsupported
behavior.

Introduce a `private::Sealed` trait and implement it for all types
that implement `HrTimerMode`.

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250617232806.3950141-1-fujita.tomonori@gmail.com
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-06-30 12:39:13 +02:00
Alice Ryhl
d6763e0abb rust: revocable: document why &T is not used in RevocableGuard
When a reference appears in a function argument, the reference is
assumed to be valid for the entire duration of that function call; this
is called a stack protector [1]. Because of that, custom pointer types
whose destructor may invalidate the pointee (i.e. they are more similar
to Box<T> than &T) cannot internally use a reference, and must instead
use a raw pointer.

This issue is something that is often missed during unsafe review. For
examples, see [2] and [3]. To ensure that people don't try to simplify
RevocableGuard by changing the raw pointer to a reference, add a comment
to that effect.

Link: https://perso.crans.org/vanille/treebor/protectors.html [1]
Link: https://users.rust-lang.org/t/unsafe-code-review-semi-owning-weak-rwlock-t-guard/95706 [2]
Link: https://lore.kernel.org/all/aEqdur4JTFa1V20U@google.com/ [3]
Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250612-revocable-ptr-comment-v1-1-db36785877f6@google.com
[ Adjusted title. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-29 18:54:54 +02:00
Alice Ryhl
fbcd4b7bf5 rust: rbtree: add RBTree::is_empty
In Rust Binder I need to be able to determine whether a red/black tree
is empty. Thus, add a method for that operation to replace

	rbtree.iter().next().is_none()

This is terrible, so add a method for this purpose. We do not add a
RBTree::len method because computing the number of elements requires
iterating the entire tree, but checking whether it is empty can be done
cheaply.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250616-rbtree-is-empty-v1-1-61f7cfb012e3@google.com
[ Adjusted title. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-29 18:52:41 +02:00
Janne Grunau
fe49aae0fc rust: init: Fix generics in *_init! macros
The match pattern for a optional trailing comma in the list of generics
is erroneously repeated in the code block resulting in following error:

| error: attempted to repeat an expression containing no syntax variables matched as repeating at this depth
|    --> rust/kernel/init.rs:301:73
|     |
| 301 |         ::pin_init::try_pin_init!($(&$this in)? $t $(::<$($generics),* $(,)?>)? {
|     |                                                                         ^^^

Remove "$(,)?" from all code blocks in the try_init! and try_pin_init!
definitions.

Cc: stable@vger.kernel.org
Fixes: 578eb8b6db ("rust: pin-init: move the default error behavior of `try_[pin_]init`")
Signed-off-by: Janne Grunau <j@jannau.net>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250628-rust_init_trailing_comma-v1-1-2d162ae1a757@jannau.net
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-29 18:30:45 +02:00
Danilo Krummrich
f5d3ef25d2 rust: devres: get rid of Devres' inner Arc
So far Devres uses an inner memory allocation and reference count, i.e.
an inner Arc, in order to ensure that the devres callback can't run into
a use-after-free in case where the Devres object is dropped while the
devres callback runs concurrently.

Instead, use a completion in order to avoid a potential UAF: In
Devres::drop(), if we detect that we can't remove the devres action
anymore, we wait for the completion that is completed from the devres
callback. If, in turn, we were able to successfully remove the devres
action, we can just go ahead.

This, again, allows us to get rid of the internal Arc, and instead let
Devres consume an `impl PinInit<T, E>` in order to return an
`impl PinInit<Devres<T>, E>`, which enables us to get away with less
memory allocations.

Additionally, having the resulting explicit synchronization in
Devres::drop() prevents potential subtle undesired side effects of the
devres callback dropping the final Arc reference asynchronously within
the devres callback.

Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250626200054.243480-4-dakr@kernel.org
[ Move '# Invariants' below '# Examples'. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-28 18:08:50 +02:00
Danilo Krummrich
46ae8fd738 rust: devres: replace Devres::new_foreign_owned()
Replace Devres::new_foreign_owned() with devres::register().

The current implementation of Devres::new_foreign_owned() creates a full
Devres container instance, including the internal Revocable and
completion.

However, none of that is necessary for the intended use of giving full
ownership of an object to devres and getting it dropped once the given
device is unbound.

Hence, implement devres::register(), which is limited to consume the
given data, wrap it in a KBox and drop the KBox once the given device is
unbound, without any other synchronization.

Cc: Dave Airlie <airlied@redhat.com>
Cc: Simona Vetter <simona.vetter@ffwll.ch>
Cc: Viresh Kumar <viresh.kumar@linaro.org>
Acked-by: Viresh Kumar <viresh.kumar@linaro.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Link: https://lore.kernel.org/r/20250626200054.243480-3-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-28 18:06:53 +02:00
Danilo Krummrich
ce7c22b2e1 rust: revocable: support fallible PinInit types
Currently, Revocable::new() only supports infallible PinInit
implementations, i.e. impl PinInit<T, Infallible>.

This has been sufficient so far, since users such as Devres do not
support fallibility.

Since this is about to change, make Revocable::new() generic over the
error type E.

Reviewed-by: Benno Lossin <lossin@kernel.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://lore.kernel.org/r/20250626200054.243480-2-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-28 18:06:52 +02:00
Danilo Krummrich
14648fc30e pin-init blanket implementation changes for v6.17
Remove the error from the blanket implementations for `[Pin]Init` and
 add implementations for `Result`.
 -----BEGIN PGP SIGNATURE-----
 
 iIgEABYKADAWIQQjEG/HT3UeYLJybLTomd21rZaLygUCaF8ANBIcbG9zc2luQGtl
 cm5lbC5vcmcACgkQ6Jndta2Wi8q/eAEAm2yX0VLvVjNssIfQNxrEqW2cMcZnxe0L
 wuj95ZU5zX0BAIPvcE+3WEVDKmZwp1tLFeZBQEw4tNZXXREC3K6QDsUM
 =KSE3
 -----END PGP SIGNATURE-----

Merge tag 'pin-init-v6.17-result-blanket' of https://github.com/Rust-for-Linux/linux.git

pin-init blanket implementation changes for v6.17

Remove the error from the blanket implementations for `[Pin]Init` and
add implementations for `Result`.

(Subsequent Devres improvements depend on those pin-init features.)
2025-06-28 17:28:06 +02:00
Christian Schrefl
64888dfdfa rust: implement Wrapper<T> for Opaque<T>
Moves the implementation for `pin-init` from an associated function
to the trait function of the `Wrapper` trait and extends the
implementation to support pin-initializers with error types.

Adds a use for the `Wrapper` trait in `revocable.rs`, to use the new
`pin-init` function. This is currently the only usage in the kernel.

Reviewed-by: Gerald Wisböck <gerald.wisboeck@feather.ink>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
Signed-off-by: Christian Schrefl <chrisi.schrefl@gmail.com>
Link: https://lore.kernel.org/r/20250610-b4-rust_miscdevice_registrationdata-v6-1-b03f5dfce998@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-28 14:58:08 +02:00
Danilo Krummrich
0dab138d0f rust: devres: require T: Send for Devres
Due to calling Revocable::revoke() from Devres::devres_callback() T may
be dropped from Devres::devres_callback() and hence must be Send.

Fix this by adding the corresponding bound to Devres and DevresInner.

Reported-by: Boqun Feng <boqun.feng@gmail.com>
Closes: https://lore.kernel.org/lkml/aFzI5L__OcB9hqdG@Mac.home/
Fixes: 76c01ded72 ("rust: add devres abstraction")
Reviewed-by: Boqun Feng <boqun.fenng@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250626132544.72866-1-dakr@kernel.org
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-28 14:55:22 +02:00
Igor Korotin
8411e6f06a rust: platform: Add ACPI match table support to Driver trait
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-26 23:26:15 +02:00
Igor Korotin
ec3ef2175e rust: platform: Set OF_ID_TABLE default to None in Driver trait
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-26 23:26:15 +02:00
Igor Korotin
7a5cb145a9 rust: driver: Add ACPI id table support to Adapter trait
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-26 23:26:10 +02:00
Igor Korotin
0f549d2585 rust: driver: Consolidate Adapter::of_id_info methods using #[cfg]
Refactor the `of_id_info` methods in the `Adapter` trait to reduce
duplication. Previously, the method had two versions selected
via `#[cfg(...)]` and `#[cfg(not(...))]`. This change merges them into a
single method by using `#[cfg]` blocks within the method body.

Suggested-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com>
Link: https://lore.kernel.org/r/20250620153656.294468-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-26 23:25:07 +02:00
Igor Korotin
a74931eb59 rust: acpi: add acpi::DeviceId abstraction
`acpi::DeviceId` is an abstraction around `struct acpi_device_id`.

Enable drivers to build ACPI device ID tables, to be consumed by the
corresponding bus abstractions, such as platform or I2C.

Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com>
Acked-by: Rafael J. Wysocki <rafael@kernel.org>
Link: https://lore.kernel.org/r/20250620152425.285683-1-igor.korotin.linux@gmail.com
[ Always inline DeviceId::new() and use &'static CStr; slightly reword
  commit message. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-26 23:22:17 +02:00
Danilo Krummrich
56a789f776 rust: device: implement FwNode::is_of_node()
Implement FwNode::is_of_node() in order to check whether a FwNode
instance is embedded in a struct device_node.

Reviewed-by: Rob Herring (Arm) <robh@kernel.org>
Signed-off-by: Igor Korotin <igor.korotin.linux@gmail.com>
Link: https://lore.kernel.org/r/20250620151504.278766-1-igor.korotin.linux@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-25 18:10:12 +02:00
Remo Senekowitsch
c3e05bd15e rust: device: Add property_get_reference_args
Allow Rust code to read reference args from device properties. The
wrapper type `FwNodeReferenceArgs` allows callers to access the buffer
of read args safely.

Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
Link: https://lore.kernel.org/r/20250616154511.1862909-3-remo@buenzli.dev
[ Move up NArgs; refer to FwNodeReferenceArgs in NArgs doc-comment.
  - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-25 17:47:13 +02:00
Remo Senekowitsch
c942dba380 rust: device: Add child accessor and iterator
Allow Rust drivers to access children of a fwnode either by name or by
iterating over all of them.

In C, there is the function `fwnode_get_next_child_node` for iteration
and the macro `fwnode_for_each_child_node` that helps with handling the
pointers. Instead of a macro, a native iterator is used in Rust such
that regular for-loops can be used.

Tested-by: Dirk Behme <dirk.behme@de.bosch.com>
Signed-off-by: Remo Senekowitsch <remo@buenzli.dev>
Link: https://lore.kernel.org/r/20250616154511.1862909-2-remo@buenzli.dev
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-25 17:18:07 +02:00
FUJITA Tomonori
7e611710ac rust: task: Add Rust version of might_sleep()
Add a helper function equivalent to the C's might_sleep(), which
serves as a debugging aid and a potential scheduling point.

Note that this function can only be used in a nonatomic context.

This will be used by Rust version of read_poll_timeout().

[boqun: Use file_from_location() to get a C string instead of changing
__might_sleep()]

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250619151007.61767-3-boqun.feng@gmail.com
2025-06-24 15:53:50 -07:00
Boqun Feng
0aa2b78ce5 rust: Introduce file_from_location()
Most of kernel debugging facilities take a nul-terminated string for
file names for a callsite (generated from __FILE__), however the Rust
courterpart, Location, would return a Rust string (not nul-terminated)
from method .file(). And such a string cannot be passed to C debugging
function directly.

There is ongoing work to support a Location::file_with_nul() [1], which
returns a nul-terminated string from a Location. Since it's still
working in progress, and it will take some time before the feature
finally gets stabilized and the kernel's minimal rustc version might
also take a while to bump to a version that at least has that feature,
introduce a file_from_location() function, which returns a warning
string if Location::file_with_nul() is not available.

This should work in most cases because as for now the known usage of
Location::file_with_nul() is only in debugging code (e.g. might_sleep())
and there might be other information reported by the debugging code that
could help locate the problematic function, so missing the file name is
fine at the moment.

Link: https://github.com/rust-lang/rust/issues/141727 [1]
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250619151007.61767-2-boqun.feng@gmail.com
2025-06-24 15:53:46 -07:00
FUJITA Tomonori
69f66cf458 rust: time: Remove Ktime in hrtimer
Remove the use of `Ktime` from the hrtimer code, which was originally
introduced as a temporary workaround. The hrtimer has now been fully
converted to use the `Instant` and `Delta` types instead.

Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://lore.kernel.org/r/20250610132823.3457263-6-fujita.tomonori@gmail.com
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-06-24 19:52:47 +02:00
FUJITA Tomonori
e0c0ab04f6 rust: time: Make HasHrTimer generic over HrTimerMode
Add a `TimerMode` associated type to the `HasHrTimer` trait to
represent the operational mode of the timer, such as absolute or
relative expiration. This new type must implement the `HrTimerMode`
trait, which defines how expiration values are interpreted.

Update the `start()` method to accept an `expires` parameter of type
`<Self::TimerMode as HrTimerMode>::Expires` instead of the fixed `Ktime`.
This enables different timer modes to provide strongly typed expiration
values, such as `Instant<C>` or `Delta`.

The `impl_has_hr_timer` macro is also extended to allow specifying the
`HrTimerMode`. In the following example, it guarantees that the
`start()` method for `Foo` only accepts `Instant<Monotonic>`. Using a
`Delta` or an `Instant` with a different clock source will result in a
compile-time error:

struct Foo {
    #[pin]
    timer: HrTimer<Self>,
}

impl_has_hr_timer! {
    impl HasHrTimer<Self> for Foo {
        mode : AbsoluteMode<Monotonic>,
        field : self.timer
    }
}

This design eliminates runtime mismatches between expires types and
clock sources, and enables stronger type-level guarantees throughout
hrtimer.

Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Link: https://lore.kernel.org/r/20250610132823.3457263-5-fujita.tomonori@gmail.com
[ changed conversion method names to `as_*` - Andreas ]
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-06-24 19:52:47 +02:00
FUJITA Tomonori
d9fc00dc73 rust: time: Add HrTimerExpires trait
Introduce the `HrTimerExpires` trait to represent types that can be
used as expiration values for high-resolution timers. Define a
required method, `into_nanos()`, which returns the expiration time as a
raw nanosecond value suitable for use with C's hrtimer APIs.

Also extend the `HrTimerMode` to use the `HrTimerExpires` trait.

This refactoring is a preparation for enabling hrtimer code to work
uniformly with both absolute and relative expiration modes.

Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://lore.kernel.org/r/20250610132823.3457263-4-fujita.tomonori@gmail.com
[ changed conversion method names to `as_*` - Andreas ]
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-06-24 19:52:47 +02:00
Panagiotis Foliadis
0a41f5af19 rust: task: Mark Task methods inline
When building the kernel using the llvm-18.1.3-rust-1.85.0-x86_64
toolchain provided by kernel.org, the following symbols are generated:

$ nm vmlinux | grep ' _R'.*Task | rustfilt
... T <kernel::task::Task>::get_pid_ns
... T <kernel::task::Task>::tgid_nr_ns
... T <kernel::task::Task>::current_pid_ns
... T <kernel::task::Task>::signal_pending
... T <kernel::task::Task>::uid
... T <kernel::task::Task>::euid
... T <kernel::task::Task>::current
... T <kernel::task::Task>::wake_up
... T <kernel::task::Task as kernel::types::AlwaysRefCounted>::dec_ref
... T <kernel::task::Task as kernel::types::AlwaysRefCounted>::inc_ref

These Rust symbols are trivial wrappers around the C functions. It
doesn't make sense to go through a trivial wrapper for these functions,
so mark them inline.

[boqun: Capitalize the title, reword a bit to avoid listing all the C
functions as the code already shows them and remove the addresses of the
symbols in the commit log as they are different from build to build.]

Link: https://github.com/Rust-for-Linux/linux/issues/1145
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Christian Schrefl <chrisi.schrefl@gmail.com>
Reviewed-by: Charalampos Mitrodimas <charmitro@posteo.net>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Panagiotis Foliadis <pfoliadis@posteo.net>
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250315-inline-c-wrappers-v3-1-048e43fcef7d@posteo.net
2025-06-24 10:23:48 -07:00
Kunwu Chan
11867144ff rust: sync: Mark PollCondVar::drop() inline
When building 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'.*PollCondVar  | rustfilt
... T <kernel::sync::poll::PollCondVar as kernel::init::PinnedDrop>::drop
...

This Rust symbol is trivial wrappers around the C functions
__wake_up_pollfree() and synchronize_rcu(). It doesn't make sense to go
through a trivial wrapper for its functions, so mark it inline.

[boqun: Reword the commit title and re-format the commit log per tip
tree's requirement, remove unnecessary information from "nm vmlinux"
result.]

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>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250317025205.2366518-1-kunwu.chan@linux.dev
2025-06-24 10:23:48 -07:00
Kunwu Chan
3f9ebeba98 rust: sync: Mark CondVar::notify_*() inline
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'.*CondVar | rustfilt
... T <kernel::sync::condvar::CondVar>::notify_all
... T <kernel::sync::condvar::CondVar>::notify_one
... T <kernel::sync::condvar::CondVar>::notify_sync
...

These notify_*() symbols are trivial wrappers around the C functions
__wake_up() and __wake_up_sync(). It doesn't make sense to go through
a trivial wrapper for these functions, so mark them inline.

[boqun: Reword the commit title for consistency and reformat the commit
log.]

Suggested-by: Alice Ryhl <aliceryhl@google.com>
Link: https://github.com/Rust-for-Linux/linux/issues/1145
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: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Boqun Feng <boqun.feng@gmail.com>
Link: https://lore.kernel.org/r/20250324061835.1693125-1-kunwu.chan@linux.dev
2025-06-24 10:23:48 -07:00
FUJITA Tomonori
ced9ccd21f rust: time: Replace HrTimerMode enum with trait-based mode types
Replace the `HrTimerMode` enum with a trait-based approach that uses
zero-sized types to represent each mode of operation. Each mode now
implements the `HrTimerMode` trait.

This refactoring is a preparation for replacing raw `Ktime` in HrTimer
with the `Instant` and `Delta` types, and for making `HrTimer` generic
over a `ClockSource`.

Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: FUJITA Tomonori <fujita.tomonori@gmail.com>
Link: https://lore.kernel.org/r/20250610132823.3457263-3-fujita.tomonori@gmail.com
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
2025-06-24 15:12:19 +02:00
Sai Vishnu M
0303584766 rust: io: avoid mentioning private fields in IoMem
Removed reference to internal variables in the comment of `IoMem`
This avoids using private variable names in public documentation.

Suggested-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://github.com/Rust-for-Linux/linux/issues/1167
Signed-off-by: Sai Vishnu M <saivishnu725@gmail.com>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://lore.kernel.org/r/20250602164923.48893-2-saivishnu725@gmail.com
[ Reworded title and adjusted tags. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-24 01:02:30 +02:00
Viresh Kumar
b6985083be rust: Use consistent "# Examples" heading style in rustdoc
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-24 01:02:30 +02:00
Guilherme Giacomo Simoes
bfb9e46b5b rust: macros: remove module!'s deprecated author key
Commit 38559da6af ("rust: module: introduce `authors` key") introduced
a new `authors` key to support multiple module authors, while keeping
the old `author` key for backward compatibility.

Now that most in-tree modules have migrated to `authors`, remove:
1. The deprecated `author` key support from the module macro
2. Legacy `author` entries from remaining modules

Signed-off-by: Guilherme Giacomo Simoes <trintaeoitogc@gmail.com>
Acked-by: Andreas Hindborg <a.hindborg@kernel.org>
Reviewed-by: Benno Lossin <lossin@kernel.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Acked-by: Viresh Kumar <viresh.kumar@linaro.org>
Acked-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Link: https://lore.kernel.org/r/20250609122200.179307-1-trintaeoitogc@gmail.com
[ Reworded slightly. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-24 01:01:13 +02:00
Albin Babu Varghese
b61b0092ea rust: list: replace unwrap() with ? in doctest examples
Using `unwrap()` in kernel doctests can cause panics on error and may
give newcomers the mistaken impression that panicking is acceptable
in kernel code.

Replace all `.unwrap()` calls in `kernel::list`
examples with `.ok_or(EINVAL)?` so that errors are properly propagated.

Suggested-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://github.com/Rust-for-Linux/linux/issues/1164
Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Albin Babu Varghese <albinbabuvarghese20@gmail.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250527204928.5117-1-albinbabuvarghese20@gmail.com
[ Reworded slightly. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-24 01:01:12 +02:00
Jesung Yang
5d4ffc531a rust: kunit: use crate-level mapping for c_void
Remove `use core::ffi::c_void`, which shadows `kernel::ffi::c_void`
brought in via `use crate::prelude::*`, to maintain consistency and
centralize the abstraction.

Since `kernel::ffi::c_void` is a straightforward re-export of
`core::ffi::c_void`, both are functionally equivalent. However, using
`kernel::ffi::c_void` improves consistency across the kernel's Rust code
and provides a unified reference point in case the definition ever needs
to change, even if such a change is unlikely.

Reviewed-by: Benno Lossin <lossin@kernel.org>
Link: https://rust-for-linux.zulipchat.com/#narrow/channel/288089/topic/x/near/520452733
Signed-off-by: Jesung Yang <y.j3ms.n@gmail.com>
Link: https://lore.kernel.org/r/20250528174953.2948570-1-y.j3ms.n@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-24 00:55:22 +02:00
Alexandre Courbot
06a93197e2 rust: sizes: add constants up to SZ_2G
nova-core will need to use SZ_1M, so make the remaining constants
available.

Reviewed-by: Boqun Feng <boqun.feng@gmail.com>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://lore.kernel.org/r/20250619-nova-frts-v6-5-ecf41ef99252@nvidia.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 18:12:30 +02:00
Alexandre Courbot
69ba00fed9 rust: make ETIMEDOUT error available
We will use this error in the nova-core driver.

Reviewed-by: Benno Lossin <lossin@kernel.org>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Acked-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://lore.kernel.org/r/20250619-nova-frts-v6-4-ecf41ef99252@nvidia.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 18:12:30 +02:00
Danilo Krummrich
a002488de6 DMA features for v6.17
- Clarify wording and be consistent in 'coherent' nomenclature.
 
 - Convert the read!() / write!() macros to return a Result.
 
 - Add as_slice() / write() methods in CoherentAllocation.
 
 - Fix doc-comment of dma_handle().
 
 - Expose count() and size() in CoherentAllocation and add the
   corresponding type invariants.
 
 - Implement CoherentAllocation::dma_handle_with_offset().
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaFlvFQAKCRBFlHeO1qrK
 LpXYAP4xXaXFU8lp7mk77ipsXudywidktEINLwnkkpu9ktFM9gD/aXmgnWN5hFvX
 6AYX6v+UTbymqqpIW9uylTteAfQ98ws=
 =bO4B
 -----END PGP SIGNATURE-----

Merge tag 'topic/dma-features-2025-06-23' of https://github.com/Rust-for-Linux/linux.git

DMA features for v6.17

- Clarify wording and be consistent in 'coherent' nomenclature.

- Convert the read!() / write!() macros to return a Result.

- Add as_slice() / write() methods in CoherentAllocation.

- Fix doc-comment of dma_handle().

- Expose count() and size() in CoherentAllocation and add the
  corresponding type invariants.

- Implement CoherentAllocation::dma_handle_with_offset().
2025-06-23 17:53:17 +02:00
Danilo Krummrich
c7e03c5cf0 DMA features for v6.17
- Clarify wording and be consistent in 'coherent' nomenclature.
 
 - Convert the read!() / write!() macros to return a Result.
 
 - Add as_slice() / write() methods in CoherentAllocation.
 
 - Fix doc-comment of dma_handle().
 
 - Expose count() and size() in CoherentAllocation and add the
   corresponding type invariants.
 
 - Implement CoherentAllocation::dma_handle_with_offset().
 -----BEGIN PGP SIGNATURE-----
 
 iHUEABYKAB0WIQS2q/xV6QjXAdC7k+1FlHeO1qrKLgUCaFlvFQAKCRBFlHeO1qrK
 LpXYAP4xXaXFU8lp7mk77ipsXudywidktEINLwnkkpu9ktFM9gD/aXmgnWN5hFvX
 6AYX6v+UTbymqqpIW9uylTteAfQ98ws=
 =bO4B
 -----END PGP SIGNATURE-----

Merge tag 'topic/dma-features-2025-06-23' into alloc-next

DMA features for v6.17

- Clarify wording and be consistent in 'coherent' nomenclature.

- Convert the read!() / write!() macros to return a Result.

- Add as_slice() / write() methods in CoherentAllocation.

- Fix doc-comment of dma_handle().

- Expose count() and size() in CoherentAllocation and add the
  corresponding type invariants.

- Implement CoherentAllocation::dma_handle_with_offset().
2025-06-23 17:38:52 +02:00
Alexandre Courbot
26af856539 rust: dma: add dma_handle_with_offset method to CoherentAllocation
Sometimes one may want to obtain a DMA handle starting at a given
offset. This can be done by adding said offset to the result of
`dma_handle()`, but doing so on the client side carries the risk that
the operation will go outside the bounds of the allocation.

Thus, add a `dma_handle_with_offset` method that adds the desired offset
after checking that it is still valid.

Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250619-nova-frts-v6-3-ecf41ef99252@nvidia.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 17:11:07 +02:00
Alexandre Courbot
c0a3065d5d rust: dma: expose the count and size of CoherentAllocation
These properties are very useful to have (and to be used by nova-core)
and should be accessible, hence add them.

Additionally, add type invariants for the size of an allocation.

Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250619-nova-frts-v6-2-ecf41ef99252@nvidia.com
[ Slightly extend the commit message. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 17:11:07 +02:00
Alexandre Courbot
14371e58cb rust: dma: fix doc-comment of dma_handle()
A word was apparently missing in this sentence, hence fix it.

Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250619-nova-frts-v6-1-ecf41ef99252@nvidia.com
Fixes: ad2907b4e3 ("rust: add dma coherent allocator abstraction")
[ Slightly expand commit subject and add 'Fixes:' tag. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 17:10:44 +02:00
Abdiel Janulgue
d37a39f607 rust: dma: add as_slice/write functions for CoherentAllocation
Add unsafe accessors for the region for reading or writing large
blocks of data.

Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: Abdiel Janulgue <abdiel.janulgue@gmail.com>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Link: https://lore.kernel.org/r/20250602085444.1925053-4-abdiel.janulgue@gmail.com
[ Fix line length and slightly reword safety comment in doc-test of
  CoherentAllocation::write(); fix formatting issue. - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 15:44:30 +02:00
Abdiel Janulgue
fe58465905 rust: dma: convert the read/write macros to return Result
We could do better here by having the macros return `Result`,
so that we don't have to wrap these calls in a closure for
validation which is confusing.

Co-developed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: Andreas Hindborg <a.hindborg@kernel.org>
Link: https://lore.kernel.org/rust-for-linux/87h63qhz4q.fsf@kernel.org/
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Signed-off-by: Abdiel Janulgue <abdiel.janulgue@gmail.com>
Link: https://lore.kernel.org/r/20250602085444.1925053-3-abdiel.janulgue@gmail.com
[ Fix line length in dma_read!(). - Danilo ]
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 15:34:13 +02:00
Abdiel Janulgue
9863f77433 rust: dma: clarify wording and be consistent in coherent nomenclature
In the kernel, `consistent` and `coherent` are used interchangeably for the
region described in this api. Stick with `coherent` nomenclature
to show that dma_alloc_coherent() is being used, in addition to improving
the clarity in the DMA mapping attributes documentation.

Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Signed-off-by: Abdiel Janulgue <abdiel.janulgue@gmail.com>
Reviewed-by: Andreas Hindborg <a.hindborg@kernel.org>
Link: https://lore.kernel.org/r/20250602085444.1925053-2-abdiel.janulgue@gmail.com
Signed-off-by: Danilo Krummrich <dakr@kernel.org>
2025-06-23 15:25:18 +02:00
Greg Kroah-Hartman
63dafeb392 Merge 6.16-rc3 into driver-core-next
We need the driver-core fixes that are in 6.16-rc3 into here as well
to build on top of.

Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
2025-06-23 07:53:36 +02:00
Abhinav Ananthu
22679d807d rust: opp: use c_* types via kernel prelude
Update OPP FFI callback signatures to use `c_int` from the `kernel::prelude`,
instead of accessing it via `kernel::ffi::c_int`.

Although these types are defined in a crate named `ffi`, they are re-exported
via the `kernel::prelude` and should be used from there. This aligns with the
Rust-for-Linux coding guidelines and ensures ABI correctness when interfacing
with C code.

Suggested-by: Viresh Kumar <viresh.kumar@linaro.org>
Signed-off-by: Abhinav Ananthu <abhinav.ogl@gmail.com>
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-06-23 09:52:45 +05:30
Abhinav Ananthu
b0a86fb0b2 rust: cpufreq: use c_ types from kernel prelude
Update cpufreq FFI callback signatures to use `c_int` from the `kernel::prelude`,
rather than accessing it explicitly through `kernel::ffi::c_int`.

Although these types are defined in the `ffi` crate, they are re-exported
via `kernel::prelude`. This aligns with the Rust-for-Linux coding
guidelines and ensures proper C ABI compatibility across platforms.

Signed-off-by: Abhinav Ananthu <abhinav.ogl@gmail.com>
Suggested-by: Viresh Kumar <viresh.kumar@linaro.org>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
[ Viresh: Fixed rustfmtcheck errors ]
Signed-off-by: Viresh Kumar <viresh.kumar@linaro.org>
2025-06-23 09:45:45 +05:30
Tamir Duberstein
dc35ddcf97 rust: enable clippy::ref_as_ptr lint
In Rust 1.78.0, Clippy introduced the `ref_as_ptr` lint [1]:

> Using `as` casts may result in silently changing mutability or type.

While this doesn't eliminate unchecked `as` conversions, it makes such
conversions easier to scrutinize.  It also has the slight benefit of
removing a degree of freedom on which to bikeshed. Thus apply the
changes and enable the lint -- no functional change intended.

Link: https://rust-lang.github.io/rust-clippy/master/index.html#ref_as_ptr [1]
Suggested-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/all/D8PGG7NTWB6U.3SS3A5LN4XWMN@proton.me/
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: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-6-f43b024581e8@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22 23:09:32 +02:00
Tamir Duberstein
b7c8d7a8d2 rust: enable clippy::cast_lossless lint
Before Rust 1.29.0, Clippy introduced the `cast_lossless` lint [1]:

> Rust’s `as` keyword will perform many kinds of conversions, including
> silently lossy conversions. Conversion functions such as `i32::from`
> will only perform lossless conversions. Using the conversion functions
> prevents conversions from becoming silently lossy if the input types
> ever change, and makes it clear for people reading the code that the
> conversion is lossless.

While this doesn't eliminate unchecked `as` conversions, it makes such
conversions easier to scrutinize.  It also has the slight benefit of
removing a degree of freedom on which to bikeshed. Thus apply the
changes and enable the lint -- no functional change intended.

Link: https://rust-lang.github.io/rust-clippy/master/index.html#cast_lossless [1]
Suggested-by: Benno Lossin <benno.lossin@proton.me>
Link: https://lore.kernel.org/all/D8ORTXSUTKGL.1KOJAGBM8F8TN@proton.me/
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: FUJITA Tomonori <fujita.tomonori@gmail.com>
Acked-by: Jocelyn Falempe <jfalempe@redhat.com>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-5-f43b024581e8@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22 23:09:25 +02:00
Tamir Duberstein
5e30550558 rust: enable clippy::as_underscore lint
In Rust 1.63.0, Clippy introduced the `as_underscore` lint [1]:

> The conversion might include lossy conversion or a dangerous cast that
> might go undetected due to the type being inferred.
>
> The lint is allowed by default as using `_` is less wordy than always
> specifying the type.

Always specifying the type is especially helpful in function call
contexts where the inferred type may change at a distance. Specifying
the type also allows Clippy to spot more cases of `useless_conversion`.

The primary downside is the need to specify the type in trivial getters.
There are 4 such functions: 3 have become slightly less ergonomic, 1 was
revealed to be a `useless_conversion`.

While this doesn't eliminate unchecked `as` conversions, it makes such
conversions easier to scrutinize.  It also has the slight benefit of
removing a degree of freedom on which to bikeshed. Thus apply the
changes and enable the lint -- no functional change intended.

Link: https://rust-lang.github.io/rust-clippy/master/index.html#as_underscore [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: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-4-f43b024581e8@gmail.com
[ Changed `isize` to `c_long`. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22 23:09:17 +02:00
Tamir Duberstein
23773bd8da rust: enable clippy::as_ptr_cast_mut lint
In Rust 1.66.0, Clippy introduced the `as_ptr_cast_mut` lint [1]:

> Since `as_ptr` takes a `&self`, the pointer won’t have write
> permissions unless interior mutability is used, making it unlikely
> that having it as a mutable pointer is correct.

There is only one affected callsite, and the change amounts to replacing
`as _` with `.cast_mut().cast()`. This doesn't change the semantics, but
is more descriptive of what's going on.

Apply this change and enable the lint -- no functional change intended.

Link: https://rust-lang.github.io/rust-clippy/master/index.html#as_ptr_cast_mut [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: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
Acked-by: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-3-f43b024581e8@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22 23:09:09 +02:00
Tamir Duberstein
d8c9e735f1 rust: enable clippy::ptr_cast_constness lint
In Rust 1.72.0, Clippy introduced the `ptr_cast_constness` lint [1]:

> Though `as` casts between raw pointers are not terrible,
> `pointer::cast_mut` and `pointer::cast_const` are safer because they
> cannot accidentally cast the pointer to another type.

There are only 3 affected sites:
- `*mut T as *const U as *mut U` becomes `(*mut T).cast()`.
- `&self as *const Self as *mut Self` becomes
  `core::ptr::from_ref(self).cast_mut()`.
- `*const T as *mut _` becommes `(*const T).cast_mut()`.

Apply these changes and enable the lint -- no functional change
intended.

Link: https://rust-lang.github.io/rust-clippy/master/index.html#ptr_cast_constness [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: Danilo Krummrich <dakr@kernel.org>
Link: https://lore.kernel.org/r/20250615-ptr-as-ptr-v12-2-f43b024581e8@gmail.com
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
2025-06-22 23:08:50 +02:00
Tamir Duberstein
fcad9bbf9e rust: enable clippy::ptr_as_ptr lint
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-22 23:08:42 +02:00