mirror of
https://github.com/torvalds/linux.git
synced 2025-11-01 17:18:25 +02:00
Toolchain and infrastructure:
- Enable a set of Clippy lints: 'ptr_as_ptr', 'ptr_cast_constness',
'as_ptr_cast_mut', 'as_underscore', 'cast_lossless' and 'ref_as_ptr'.
These are intended to avoid type casts with the 'as' operator, which
are quite powerful, into restricted variants that are less powerful
and thus should help to avoid mistakes.
- Remove the 'author' key now that most instances were moved to the
plural one in the previous cycle.
'kernel' crate:
- New 'bug' module: add 'warn_on!' macro which reuses the existing
'BUG'/'WARN' infrastructure, i.e. it respects the usual sysctls and
kernel parameters:
warn_on!(value == 42);
To avoid duplicating the assembly code, the same strategy is followed
as for the static branch code in order to share the assembly between
both C and Rust. This required a few rearrangements on C arch headers
-- the existing C macros should still generate the same outputs, thus
no functional change expected there.
- 'workqueue' module: add delayed work items, including a 'DelayedWork'
struct, a 'impl_has_delayed_work!' macro and an 'enqueue_delayed'
method, e.g.:
/// Enqueue the struct for execution on the system workqueue,
/// where its value will be printed 42 jiffies later.
fn print_later(value: Arc<MyStruct>) {
let _ = workqueue::system().enqueue_delayed(value, 42);
}
- New 'bits' module: add support for 'bit' and 'genmask' functions,
with runtime- and compile-time variants, e.g.:
static_assert!(0b00010000 == bit_u8(4));
static_assert!(0b00011110 == genmask_u8(1..=4));
assert!(checked_bit_u32(u32::BITS).is_none());
- 'uaccess' module: add 'UserSliceReader::strcpy_into_buf', which reads
NUL-terminated strings from userspace into a '&CStr'.
Introduce 'UserPtr' newtype, similar in purpose to '__user' in C, to
minimize mistakes handling userspace pointers, including mixing them
up with integers and leaking them via the 'Debug' trait. Add it to
the prelude, too.
- Start preparations for the replacement of our custom 'CStr' type
with the analogous type in the 'core' standard library. This will
take place across several cycles to make it easier. For this one,
it includes a new 'fmt' module, using upstream method names and some
other cleanups.
Replace 'fmt!' with a re-export, which helps Clippy lint properly,
and clean up the found 'uninlined-format-args' instances.
- 'dma' module:
- Clarify wording and be consistent in 'coherent' nomenclature.
- Convert the 'read!()' and 'write!()' macros to return a 'Result'.
- Add 'as_slice()', 'write()' methods in 'CoherentAllocation'.
- Expose 'count()' and 'size()' in 'CoherentAllocation' and add the
corresponding type invariants.
- Implement 'CoherentAllocation::dma_handle_with_offset()'.
- 'time' module:
- Make 'Instant' generic over clock source. This allows the compiler
to assert that arithmetic expressions involving the 'Instant' use
'Instants' based on the same clock source.
- Make 'HrTimer' generic over the timer mode. 'HrTimer' timers take a
'Duration' or an 'Instant' when setting the expiry time, depending
on the timer mode. With this change, the compiler can check the
type matches the timer mode.
- Add an abstraction for 'fsleep'. 'fsleep' is a flexible sleep
function that will select an appropriate sleep method depending on
the requested sleep time.
- Avoid 64-bit divisions on 32-bit hardware when calculating
timestamps.
- Seal the 'HrTimerMode' trait. This prevents users of the
'HrTimerMode' from implementing the trait on their own types.
- Pass the correct timer mode ID to 'hrtimer_start_range_ns()'.
- 'list' module: remove 'OFFSET' constants, allowing to remove pointer
arithmetic; now 'impl_list_item!' invokes 'impl_has_list_links!' or
'impl_has_list_links_self_ptr!'. Other simplifications too.
- 'types' module: remove 'ForeignOwnable::PointedTo' in favor of a
constant, which avoids exposing the type of the opaque pointer, and
require 'into_foreign' to return non-null.
Remove the 'Either<L, R>' type as well. It is unused, and we want to
encourage the use of custom enums for concrete use cases.
- 'sync' module: implement 'Borrow' and 'BorrowMut' for 'Arc' types
to allow them to be used in generic APIs.
- 'alloc' module: implement 'Borrow' and 'BorrowMut' for 'Box<T, A>';
and 'Borrow', 'BorrowMut' and 'Default' for 'Vec<T, A>'.
- 'Opaque' type: add 'cast_from' method to perform a restricted cast
that cannot change the inner type and use it in callers of
'container_of!'. Rename 'raw_get' to 'cast_into' to match it.
- 'rbtree' module: add 'is_empty' method.
- 'sync' module: new 'aref' submodule to hold 'AlwaysRefCounted' and
'ARef', which are moved from the too general 'types' module which we
want to reduce or eventually remove. Also fix a safety comment in
'static_lock_class'.
'pin-init' crate:
- Add 'impl<T, E> [Pin]Init<T, E> for Result<T, E>', so results are now
(pin-)initializers.
- Add 'Zeroable::init_zeroed()' that delegates to 'init_zeroed()'.
- New 'zeroed()', a safe version of 'mem::zeroed()' and also provide
it via 'Zeroable::zeroed()'.
- Implement 'Zeroable' for 'Option<&T>', 'Option<&mut T>' and for
'Option<[unsafe] [extern "abi"] fn(...args...) -> ret>' for '"Rust"'
and '"C"' ABIs and up to 20 arguments.
- Changed blanket impls of 'Init' and 'PinInit' from 'impl<T, E>
[Pin]Init<T, E> for T' to 'impl<T> [Pin]Init<T> for T'.
- Renamed 'zeroed()' to 'init_zeroed()'.
- Upstream dev news: improve CI more to deny warnings, use
'--all-targets'. Check the synchronization status of the two '-next'
branches in upstream and the kernel.
MAINTAINERS:
- Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo
Stoakes as reviewers (thanks everyone).
And a few other cleanups and improvements.
-----BEGIN PGP SIGNATURE-----
iQIzBAABCgAdFiEEPjU5OPd5QIZ9jqqOGXyLc2htIW0FAmiOWREACgkQGXyLc2ht
IW39Ig/9E0ExSiBgNKdkCOaULMq31wAxnu3iWoVVisFndlh/Inv+JlaLrmA57BCi
xXgBwVZ1GoMsG8Fzt6gT+gyhGYi8waNd+5KXr/WJZVTaJ9v1KpdvxuCnSz0DjCbk
GaKfAfxvJ5GAOEwiIIX8X0TFu6kx911DCJY387/VrqZQ7Msh1QSM3tcZeir/EV4w
lPjUdlOh1FnLJLI9CGuW20d1IhQUP7K3pdoywgJPpCZV0I8QCyMlMqCEael8Tw2S
r/PzRaQtiIzk5HTx06V8paK+nEn0K2vQXqW2kV56Y6TNm1Zcv6dES/8hCITsISs2
nwney3vXEwvoZX+YkQRffZddY4i6YenWMrtLgVxZzdshBL3bn6eHqBL04Nfix+p7
pQe3qMH3G8UBtX1lugBE7RrWGWcz9ARN8sK12ClmpAUnKJOwTpo97kpqXP7pDme8
Buh/oV3voAMsqwooSbVBzuUUWnbGaQ5Oj6CiiosSadfNh6AxJLYLKHtRLKJHZEw3
0Ob/1HhoWS6JSvYKVjMyD19qcH7O8ThZE+83CfMAkI4KphXJarWhpSmN4cHkFn/v
0clQ7Y5m+up9v1XWTaEq0Biqa6CaxLQwm/qW5WU0Y/TiovmvxAFdCwsQqDkRoJNx
9kNfMJRvNl78KQxrjEDz9gl7/ajgqX1KkqP8CQbGjv29cGzFlVE=
=5Wt9
-----END PGP SIGNATURE-----
Merge tag 'rust-6.17' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux
Pull Rust updates from Miguel Ojeda:
"Toolchain and infrastructure:
- Enable a set of Clippy lints: 'ptr_as_ptr', 'ptr_cast_constness',
'as_ptr_cast_mut', 'as_underscore', 'cast_lossless' and
'ref_as_ptr'
These are intended to avoid type casts with the 'as' operator,
which are quite powerful, into restricted variants that are less
powerful and thus should help to avoid mistakes
- Remove the 'author' key now that most instances were moved to the
plural one in the previous cycle
'kernel' crate:
- New 'bug' module: add 'warn_on!' macro which reuses the existing
'BUG'/'WARN' infrastructure, i.e. it respects the usual sysctls and
kernel parameters:
warn_on!(value == 42);
To avoid duplicating the assembly code, the same strategy is
followed as for the static branch code in order to share the
assembly between both C and Rust
This required a few rearrangements on C arch headers -- the
existing C macros should still generate the same outputs, thus no
functional change expected there
- 'workqueue' module: add delayed work items, including a
'DelayedWork' struct, a 'impl_has_delayed_work!' macro and an
'enqueue_delayed' method, e.g.:
/// Enqueue the struct for execution on the system workqueue,
/// where its value will be printed 42 jiffies later.
fn print_later(value: Arc<MyStruct>) {
let _ = workqueue::system().enqueue_delayed(value, 42);
}
- New 'bits' module: add support for 'bit' and 'genmask' functions,
with runtime- and compile-time variants, e.g.:
static_assert!(0b00010000 == bit_u8(4));
static_assert!(0b00011110 == genmask_u8(1..=4));
assert!(checked_bit_u32(u32::BITS).is_none());
- 'uaccess' module: add 'UserSliceReader::strcpy_into_buf', which
reads NUL-terminated strings from userspace into a '&CStr'
Introduce 'UserPtr' newtype, similar in purpose to '__user' in C,
to minimize mistakes handling userspace pointers, including mixing
them up with integers and leaking them via the 'Debug' trait. Add
it to the prelude, too
- Start preparations for the replacement of our custom 'CStr' type
with the analogous type in the 'core' standard library. This will
take place across several cycles to make it easier. For this one,
it includes a new 'fmt' module, using upstream method names and
some other cleanups
Replace 'fmt!' with a re-export, which helps Clippy lint properly,
and clean up the found 'uninlined-format-args' instances
- 'dma' module:
- Clarify wording and be consistent in 'coherent' nomenclature
- Convert the 'read!()' and 'write!()' macros to return a 'Result'
- Add 'as_slice()', 'write()' methods in 'CoherentAllocation'
- Expose 'count()' and 'size()' in 'CoherentAllocation' and add
the corresponding type invariants
- Implement 'CoherentAllocation::dma_handle_with_offset()'
- 'time' module:
- Make 'Instant' generic over clock source. This allows the
compiler to assert that arithmetic expressions involving the
'Instant' use 'Instants' based on the same clock source
- Make 'HrTimer' generic over the timer mode. 'HrTimer' timers
take a 'Duration' or an 'Instant' when setting the expiry time,
depending on the timer mode. With this change, the compiler can
check the type matches the timer mode
- Add an abstraction for 'fsleep'. 'fsleep' is a flexible sleep
function that will select an appropriate sleep method depending
on the requested sleep time
- Avoid 64-bit divisions on 32-bit hardware when calculating
timestamps
- Seal the 'HrTimerMode' trait. This prevents users of the
'HrTimerMode' from implementing the trait on their own types
- Pass the correct timer mode ID to 'hrtimer_start_range_ns()'
- 'list' module: remove 'OFFSET' constants, allowing to remove
pointer arithmetic; now 'impl_list_item!' invokes
'impl_has_list_links!' or 'impl_has_list_links_self_ptr!'. Other
simplifications too
- 'types' module: remove 'ForeignOwnable::PointedTo' in favor of a
constant, which avoids exposing the type of the opaque pointer, and
require 'into_foreign' to return non-null
Remove the 'Either<L, R>' type as well. It is unused, and we want
to encourage the use of custom enums for concrete use cases
- 'sync' module: implement 'Borrow' and 'BorrowMut' for 'Arc' types
to allow them to be used in generic APIs
- 'alloc' module: implement 'Borrow' and 'BorrowMut' for 'Box<T, A>';
and 'Borrow', 'BorrowMut' and 'Default' for 'Vec<T, A>'
- 'Opaque' type: add 'cast_from' method to perform a restricted cast
that cannot change the inner type and use it in callers of
'container_of!'. Rename 'raw_get' to 'cast_into' to match it
- 'rbtree' module: add 'is_empty' method
- 'sync' module: new 'aref' submodule to hold 'AlwaysRefCounted' and
'ARef', which are moved from the too general 'types' module which
we want to reduce or eventually remove. Also fix a safety comment
in 'static_lock_class'
'pin-init' crate:
- Add 'impl<T, E> [Pin]Init<T, E> for Result<T, E>', so results are
now (pin-)initializers
- Add 'Zeroable::init_zeroed()' that delegates to 'init_zeroed()'
- New 'zeroed()', a safe version of 'mem::zeroed()' and also provide
it via 'Zeroable::zeroed()'
- Implement 'Zeroable' for 'Option<&T>', 'Option<&mut T>' and for
'Option<[unsafe] [extern "abi"] fn(...args...) -> ret>' for
'"Rust"' and '"C"' ABIs and up to 20 arguments
- Changed blanket impls of 'Init' and 'PinInit' from 'impl<T, E>
[Pin]Init<T, E> for T' to 'impl<T> [Pin]Init<T> for T'
- Renamed 'zeroed()' to 'init_zeroed()'
- Upstream dev news: improve CI more to deny warnings, use
'--all-targets'. Check the synchronization status of the two
'-next' branches in upstream and the kernel
MAINTAINERS:
- Add Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki and Lorenzo
Stoakes as reviewers (thanks everyone)
And a few other cleanups and improvements"
* tag 'rust-6.17' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux: (76 commits)
rust: Add warn_on macro
arm64/bug: Add ARCH_WARN_ASM macro for BUG/WARN asm code sharing with Rust
riscv/bug: Add ARCH_WARN_ASM macro for BUG/WARN asm code sharing with Rust
x86/bug: Add ARCH_WARN_ASM macro for BUG/WARN asm code sharing with Rust
rust: kernel: move ARef and AlwaysRefCounted to sync::aref
rust: sync: fix safety comment for `static_lock_class`
rust: types: remove `Either<L, R>`
rust: kernel: use `core::ffi::CStr` method names
rust: str: add `CStr` methods matching `core::ffi::CStr`
rust: str: remove unnecessary qualification
rust: use `kernel::{fmt,prelude::fmt!}`
rust: kernel: add `fmt` module
rust: kernel: remove `fmt!`, fix clippy::uninlined-format-args
scripts: rust: emit path candidates in panic message
scripts: rust: replace length checks with match
rust: list: remove nonexistent generic parameter in link
rust: bits: add support for bits/genmask macros
rust: list: remove OFFSET constants
rust: list: add `impl_list_item!` examples
rust: list: use fully qualified path
...
360 lines
13 KiB
Rust
360 lines
13 KiB
Rust
// SPDX-License-Identifier: GPL-2.0
|
|
|
|
//! Devres abstraction
|
|
//!
|
|
//! [`Devres`] represents an abstraction for the kernel devres (device resource management)
|
|
//! implementation.
|
|
|
|
use crate::{
|
|
alloc::Flags,
|
|
bindings,
|
|
device::{Bound, Device},
|
|
error::{to_result, Error, Result},
|
|
ffi::c_void,
|
|
prelude::*,
|
|
revocable::{Revocable, RevocableGuard},
|
|
sync::{rcu, Completion},
|
|
types::{ARef, ForeignOwnable, Opaque, ScopeGuard},
|
|
};
|
|
|
|
use pin_init::Wrapper;
|
|
|
|
/// [`Devres`] inner data accessed from [`Devres::callback`].
|
|
#[pin_data]
|
|
struct Inner<T: Send> {
|
|
#[pin]
|
|
data: Revocable<T>,
|
|
/// Tracks whether [`Devres::callback`] has been completed.
|
|
#[pin]
|
|
devm: Completion,
|
|
/// Tracks whether revoking [`Self::data`] has been completed.
|
|
#[pin]
|
|
revoke: Completion,
|
|
}
|
|
|
|
/// This abstraction is meant to be used by subsystems to containerize [`Device`] bound resources to
|
|
/// manage their lifetime.
|
|
///
|
|
/// [`Device`] bound resources should be freed when either the resource goes out of scope or the
|
|
/// [`Device`] is unbound respectively, depending on what happens first. In any case, it is always
|
|
/// guaranteed that revoking the device resource is completed before the corresponding [`Device`]
|
|
/// is unbound.
|
|
///
|
|
/// To achieve that [`Devres`] registers a devres callback on creation, which is called once the
|
|
/// [`Device`] is unbound, revoking access to the encapsulated resource (see also [`Revocable`]).
|
|
///
|
|
/// After the [`Devres`] has been unbound it is not possible to access the encapsulated resource
|
|
/// anymore.
|
|
///
|
|
/// [`Devres`] users should make sure to simply free the corresponding backing resource in `T`'s
|
|
/// [`Drop`] implementation.
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// ```no_run
|
|
/// # use kernel::{bindings, device::{Bound, Device}, devres::Devres, io::{Io, IoRaw}};
|
|
/// # use core::ops::Deref;
|
|
///
|
|
/// // See also [`pci::Bar`] for a real example.
|
|
/// struct IoMem<const SIZE: usize>(IoRaw<SIZE>);
|
|
///
|
|
/// impl<const SIZE: usize> IoMem<SIZE> {
|
|
/// /// # Safety
|
|
/// ///
|
|
/// /// [`paddr`, `paddr` + `SIZE`) must be a valid MMIO region that is mappable into the CPUs
|
|
/// /// virtual address space.
|
|
/// unsafe fn new(paddr: usize) -> Result<Self>{
|
|
/// // SAFETY: By the safety requirements of this function [`paddr`, `paddr` + `SIZE`) is
|
|
/// // valid for `ioremap`.
|
|
/// let addr = unsafe { bindings::ioremap(paddr as bindings::phys_addr_t, SIZE) };
|
|
/// if addr.is_null() {
|
|
/// return Err(ENOMEM);
|
|
/// }
|
|
///
|
|
/// Ok(IoMem(IoRaw::new(addr as usize, SIZE)?))
|
|
/// }
|
|
/// }
|
|
///
|
|
/// impl<const SIZE: usize> Drop for IoMem<SIZE> {
|
|
/// fn drop(&mut self) {
|
|
/// // SAFETY: `self.0.addr()` is guaranteed to be properly mapped by `Self::new`.
|
|
/// unsafe { bindings::iounmap(self.0.addr() as *mut c_void); };
|
|
/// }
|
|
/// }
|
|
///
|
|
/// impl<const SIZE: usize> Deref for IoMem<SIZE> {
|
|
/// type Target = Io<SIZE>;
|
|
///
|
|
/// fn deref(&self) -> &Self::Target {
|
|
/// // SAFETY: The memory range stored in `self` has been properly mapped in `Self::new`.
|
|
/// unsafe { Io::from_raw(&self.0) }
|
|
/// }
|
|
/// }
|
|
/// # fn no_run(dev: &Device<Bound>) -> Result<(), Error> {
|
|
/// // SAFETY: Invalid usage for example purposes.
|
|
/// let iomem = unsafe { IoMem::<{ core::mem::size_of::<u32>() }>::new(0xBAAAAAAD)? };
|
|
/// let devres = KBox::pin_init(Devres::new(dev, iomem), GFP_KERNEL)?;
|
|
///
|
|
/// let res = devres.try_access().ok_or(ENXIO)?;
|
|
/// res.write8(0x42, 0x0);
|
|
/// # Ok(())
|
|
/// # }
|
|
/// ```
|
|
///
|
|
/// # Invariants
|
|
///
|
|
/// [`Self::inner`] is guaranteed to be initialized and is always accessed read-only.
|
|
#[pin_data(PinnedDrop)]
|
|
pub struct Devres<T: Send> {
|
|
dev: ARef<Device>,
|
|
/// Pointer to [`Self::devres_callback`].
|
|
///
|
|
/// Has to be stored, since Rust does not guarantee to always return the same address for a
|
|
/// function. However, the C API uses the address as a key.
|
|
callback: unsafe extern "C" fn(*mut c_void),
|
|
/// Contains all the fields shared with [`Self::callback`].
|
|
// TODO: Replace with `UnsafePinned`, once available.
|
|
//
|
|
// Subsequently, the `drop_in_place()` in `Devres::drop` and the explicit `Send` and `Sync'
|
|
// impls can be removed.
|
|
#[pin]
|
|
inner: Opaque<Inner<T>>,
|
|
}
|
|
|
|
impl<T: Send> Devres<T> {
|
|
/// Creates a new [`Devres`] instance of the given `data`.
|
|
///
|
|
/// The `data` encapsulated within the returned `Devres` instance' `data` will be
|
|
/// (revoked)[`Revocable`] once the device is detached.
|
|
pub fn new<'a, E>(
|
|
dev: &'a Device<Bound>,
|
|
data: impl PinInit<T, E> + 'a,
|
|
) -> impl PinInit<Self, Error> + 'a
|
|
where
|
|
T: 'a,
|
|
Error: From<E>,
|
|
{
|
|
let callback = Self::devres_callback;
|
|
|
|
try_pin_init!(&this in Self {
|
|
dev: dev.into(),
|
|
callback,
|
|
// INVARIANT: `inner` is properly initialized.
|
|
inner <- {
|
|
// SAFETY: `this` is a valid pointer to uninitialized memory.
|
|
let inner = unsafe { &raw mut (*this.as_ptr()).inner };
|
|
|
|
// SAFETY:
|
|
// - `dev.as_raw()` is a pointer to a valid bound device.
|
|
// - `inner` is guaranteed to be a valid for the duration of the lifetime of `Self`.
|
|
// - `devm_add_action()` is guaranteed not to call `callback` until `this` has been
|
|
// properly initialized, because we require `dev` (i.e. the *bound* device) to
|
|
// live at least as long as the returned `impl PinInit<Self, Error>`.
|
|
to_result(unsafe {
|
|
bindings::devm_add_action(dev.as_raw(), Some(callback), inner.cast())
|
|
})?;
|
|
|
|
Opaque::pin_init(try_pin_init!(Inner {
|
|
devm <- Completion::new(),
|
|
revoke <- Completion::new(),
|
|
data <- Revocable::new(data),
|
|
}))
|
|
},
|
|
})
|
|
}
|
|
|
|
fn inner(&self) -> &Inner<T> {
|
|
// SAFETY: By the type invairants of `Self`, `inner` is properly initialized and always
|
|
// accessed read-only.
|
|
unsafe { &*self.inner.get() }
|
|
}
|
|
|
|
fn data(&self) -> &Revocable<T> {
|
|
&self.inner().data
|
|
}
|
|
|
|
#[allow(clippy::missing_safety_doc)]
|
|
unsafe extern "C" fn devres_callback(ptr: *mut kernel::ffi::c_void) {
|
|
// SAFETY: In `Self::new` we've passed a valid pointer to `Inner` to `devm_add_action()`,
|
|
// hence `ptr` must be a valid pointer to `Inner`.
|
|
let inner = unsafe { &*ptr.cast::<Inner<T>>() };
|
|
|
|
// Ensure that `inner` can't be used anymore after we signal completion of this callback.
|
|
let inner = ScopeGuard::new_with_data(inner, |inner| inner.devm.complete_all());
|
|
|
|
if !inner.data.revoke() {
|
|
// If `revoke()` returns false, it means that `Devres::drop` already started revoking
|
|
// `data` for us. Hence we have to wait until `Devres::drop` signals that it
|
|
// completed revoking `data`.
|
|
inner.revoke.wait_for_completion();
|
|
}
|
|
}
|
|
|
|
fn remove_action(&self) -> bool {
|
|
// SAFETY:
|
|
// - `self.dev` is a valid `Device`,
|
|
// - the `action` and `data` pointers are the exact same ones as given to
|
|
// `devm_add_action()` previously,
|
|
(unsafe {
|
|
bindings::devm_remove_action_nowarn(
|
|
self.dev.as_raw(),
|
|
Some(self.callback),
|
|
core::ptr::from_ref(self.inner()).cast_mut().cast(),
|
|
)
|
|
} == 0)
|
|
}
|
|
|
|
/// Return a reference of the [`Device`] this [`Devres`] instance has been created with.
|
|
pub fn device(&self) -> &Device {
|
|
&self.dev
|
|
}
|
|
|
|
/// Obtain `&'a T`, bypassing the [`Revocable`].
|
|
///
|
|
/// This method allows to directly obtain a `&'a T`, bypassing the [`Revocable`], by presenting
|
|
/// a `&'a Device<Bound>` of the same [`Device`] this [`Devres`] instance has been created with.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// An error is returned if `dev` does not match the same [`Device`] this [`Devres`] instance
|
|
/// has been created with.
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// ```no_run
|
|
/// # #![cfg(CONFIG_PCI)]
|
|
/// # use kernel::{device::Core, devres::Devres, pci};
|
|
///
|
|
/// fn from_core(dev: &pci::Device<Core>, devres: Devres<pci::Bar<0x4>>) -> Result {
|
|
/// let bar = devres.access(dev.as_ref())?;
|
|
///
|
|
/// let _ = bar.read32(0x0);
|
|
///
|
|
/// // might_sleep()
|
|
///
|
|
/// bar.write32(0x42, 0x0);
|
|
///
|
|
/// Ok(())
|
|
/// }
|
|
/// ```
|
|
pub fn access<'a>(&'a self, dev: &'a Device<Bound>) -> Result<&'a T> {
|
|
if self.dev.as_raw() != dev.as_raw() {
|
|
return Err(EINVAL);
|
|
}
|
|
|
|
// SAFETY: `dev` being the same device as the device this `Devres` has been created for
|
|
// proves that `self.data` hasn't been revoked and is guaranteed to not be revoked as long
|
|
// as `dev` lives; `dev` lives at least as long as `self`.
|
|
Ok(unsafe { self.data().access() })
|
|
}
|
|
|
|
/// [`Devres`] accessor for [`Revocable::try_access`].
|
|
pub fn try_access(&self) -> Option<RevocableGuard<'_, T>> {
|
|
self.data().try_access()
|
|
}
|
|
|
|
/// [`Devres`] accessor for [`Revocable::try_access_with`].
|
|
pub fn try_access_with<R, F: FnOnce(&T) -> R>(&self, f: F) -> Option<R> {
|
|
self.data().try_access_with(f)
|
|
}
|
|
|
|
/// [`Devres`] accessor for [`Revocable::try_access_with_guard`].
|
|
pub fn try_access_with_guard<'a>(&'a self, guard: &'a rcu::Guard) -> Option<&'a T> {
|
|
self.data().try_access_with_guard(guard)
|
|
}
|
|
}
|
|
|
|
// SAFETY: `Devres` can be send to any task, if `T: Send`.
|
|
unsafe impl<T: Send> Send for Devres<T> {}
|
|
|
|
// SAFETY: `Devres` can be shared with any task, if `T: Sync`.
|
|
unsafe impl<T: Send + Sync> Sync for Devres<T> {}
|
|
|
|
#[pinned_drop]
|
|
impl<T: Send> PinnedDrop for Devres<T> {
|
|
fn drop(self: Pin<&mut Self>) {
|
|
// SAFETY: When `drop` runs, it is guaranteed that nobody is accessing the revocable data
|
|
// anymore, hence it is safe not to wait for the grace period to finish.
|
|
if unsafe { self.data().revoke_nosync() } {
|
|
// We revoked `self.data` before the devres action did, hence try to remove it.
|
|
if !self.remove_action() {
|
|
// We could not remove the devres action, which means that it now runs concurrently,
|
|
// hence signal that `self.data` has been revoked by us successfully.
|
|
self.inner().revoke.complete_all();
|
|
|
|
// Wait for `Self::devres_callback` to be done using this object.
|
|
self.inner().devm.wait_for_completion();
|
|
}
|
|
} else {
|
|
// `Self::devres_callback` revokes `self.data` for us, hence wait for it to be done
|
|
// using this object.
|
|
self.inner().devm.wait_for_completion();
|
|
}
|
|
|
|
// INVARIANT: At this point it is guaranteed that `inner` can't be accessed any more.
|
|
//
|
|
// SAFETY: `inner` is valid for dropping.
|
|
unsafe { core::ptr::drop_in_place(self.inner.get()) };
|
|
}
|
|
}
|
|
|
|
/// Consume `data` and [`Drop::drop`] `data` once `dev` is unbound.
|
|
fn register_foreign<P>(dev: &Device<Bound>, data: P) -> Result
|
|
where
|
|
P: ForeignOwnable + Send + 'static,
|
|
{
|
|
let ptr = data.into_foreign();
|
|
|
|
#[allow(clippy::missing_safety_doc)]
|
|
unsafe extern "C" fn callback<P: ForeignOwnable>(ptr: *mut kernel::ffi::c_void) {
|
|
// SAFETY: `ptr` is the pointer to the `ForeignOwnable` leaked above and hence valid.
|
|
drop(unsafe { P::from_foreign(ptr.cast()) });
|
|
}
|
|
|
|
// SAFETY:
|
|
// - `dev.as_raw()` is a pointer to a valid and bound device.
|
|
// - `ptr` is a valid pointer the `ForeignOwnable` devres takes ownership of.
|
|
to_result(unsafe {
|
|
// `devm_add_action_or_reset()` also calls `callback` on failure, such that the
|
|
// `ForeignOwnable` is released eventually.
|
|
bindings::devm_add_action_or_reset(dev.as_raw(), Some(callback::<P>), ptr.cast())
|
|
})
|
|
}
|
|
|
|
/// Encapsulate `data` in a [`KBox`] and [`Drop::drop`] `data` once `dev` is unbound.
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// ```no_run
|
|
/// use kernel::{device::{Bound, Device}, devres};
|
|
///
|
|
/// /// Registration of e.g. a class device, IRQ, etc.
|
|
/// struct Registration;
|
|
///
|
|
/// impl Registration {
|
|
/// fn new() -> Self {
|
|
/// // register
|
|
///
|
|
/// Self
|
|
/// }
|
|
/// }
|
|
///
|
|
/// impl Drop for Registration {
|
|
/// fn drop(&mut self) {
|
|
/// // unregister
|
|
/// }
|
|
/// }
|
|
///
|
|
/// fn from_bound_context(dev: &Device<Bound>) -> Result {
|
|
/// devres::register(dev, Registration::new(), GFP_KERNEL)
|
|
/// }
|
|
/// ```
|
|
pub fn register<T, E>(dev: &Device<Bound>, data: impl PinInit<T, E>, flags: Flags) -> Result
|
|
where
|
|
T: Send + 'static,
|
|
Error: From<E>,
|
|
{
|
|
let data = KBox::pin_init(data, flags)?;
|
|
|
|
register_foreign(dev, data)
|
|
}
|