rust: leds: add led classdev abstractions
Subsystems (3)
v4 cover rust: leds: add led classdev abstractions
This patch series has previously been contained in
https://lore.kernel.org/rust-for-linux/[email protected]/T/#t
which added a rust written led driver for a microcontroller via i2c.
As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
The following changes were made:
* add basic Pin<Vec<T, A>> abstractions, that allow to initialize PinInit items with the guarantee that these will never be moved.
* add basic led classdev abstractions to register and unregister leds
Changes since v3:
* fixed kunit tests failing because of example in documentation
Changes since v2:
* return Devres on led::Device creation
* replace KBox<T> with T in struct definition
* increment and decrement reference-count of fwnode
* make a device parent mandatory for led classdev creation
* rename led::Handler to led::LedOps
* add optional brightness_get function to led::LedOps
* use #[vtable] instead of const BLINK: bool
* use Opaque::cast_from instead of casting a pointer
* improve documentation
* improve support for older rust versions
* use &Device<Bound> for parent
Changes since v1:
* fixed typos noticed by Onur Özkan
Markus Probst (2):
rust: add basic Pin<Vec<T, A>> abstractions
rust: leds: add basic led classdev abstractions
rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 86 ++++++++++ rust/kernel/led.rs | 333 ++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + rust/kernel/prelude.rs | 2 +- 5 files changed, 422 insertions(+), 1 deletion(-) create mode 100644 rust/kernel/led.rs
Signature · 1 line
2.49.1
PATCH v4 1/2 rust: add basic Pin<Vec<T, A>> abstractions
Implement core Pin<Vec<T, A>> abstractions, including
* Vec::pin and Vec::into_pin for constructing a Pin<Vec<T, A>>. If T does not implement Unpin, its values will never be moved.
* an extension for Pin<Vec<T, A>> allowing PinInit to be initialied on a Pin<Vec>, as well as truncating and popping values from the Vec
--- rust/kernel/alloc.rs | 1 + rust/kernel/alloc/kvec.rs | 86 +++++++++++++++++++++++++++++++++++++++ rust/kernel/prelude.rs | 2 +- 3 files changed, 88 insertions(+), 1 deletion(-)
rust/kernel/alloc.rs +1 -0
@@ -22,6 +22,7 @@pub use self::kvec::IntoIter ;pub use self::kvec::KVVec ;pub use self::kvec::KVec ; +pub use self::kvec::PinnedVecExt ;pub use self::kvec::VVec ;pub use self::kvec::Vec ;
rust/kernel/alloc/kvec.rs +86 -0
115 lines not on this page · raw message
rust/kernel/prelude.rs +1 -1
@@ -19,7 +19,7 @@ c_ushort, c_void, }; -pub use crate ::alloc::{flags::*,Box ,KBox ,KVBox ,KVVec ,KVec ,VBox ,VVec ,Vec }; +pub use crate ::alloc::{flags::*,Box ,KBox ,KVBox ,KVVec ,KVec ,PinnedVecExt ,VBox ,VVec ,Vec };#[doc(no_inline)] pub use macros::{export, kunit_tests, module, vtable};
Signature · 1 line
2.49.1
Benno Lossin
reviewerRe: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
rust/kernel/alloc/kvec.rs pub struct Vec<T, A: Allocator> { · line 115
Quoted 6 lines · Markus Probst
rust/kernel/alloc/kvec.rs +2
-0@@ -109,6 +111,21 @@ pub struct Vec<T, A: Allocator> { _p: PhantomData<A>, } +/// Extension for Pin<Vec<T, A>> +pub trait PinnedVecExt <T > {
Why is this an extension trait? Couldn't we directly implement this on Vec<T> with self: Pin<&mut Self>?
---
Cheers,
Benno
Quoted 16 lines
rust/kernel/alloc/kvec.rs +13
-0+/// Pin-initializes P and appends it to the back of the [`Vec`] instance without reallocating. +fn push_pin_init <E :From <PushError <P >>,P :PinInit <T ,E >>(&mut self, init:P ) ->Result <(),E >; + +/// Shortens the vector, setting the length to `len` and drops the removed values. +/// If `len` is greater than or equal to the current length, this does nothing. +/// +/// This has no effect on the capacity and will not allocate. +fn truncate (&mut self, len:usize ); + +/// Removes the last element from a vector and drops it returning true, or false if it is empty. +fn pop (&mut self) ->bool ; +} +/// Type alias for [`Vec`] with a [`Kmalloc`] allocator. /// /// # Examples
Re: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
From what I can tell, there is no way to get a Pin<&mut Vec<T, A>> from a &mut Pin<Vec<T, A>>. We can only get Pin<&mut [T]> which is not usable in our case.
If there is way, without the extension trait or an extra struct, I would be happy to implement it.
Thanks
- Markus Probst
Quoted 434 lines · Benno Lossin
rust/kernel/alloc/kvec.rs pub struct Vec<T, A: Allocator> { · line 115
Quoted 6 lines · Markus Probst
rust/kernel/alloc/kvec.rs +0
-0@@ -109,6 +111,21 @@ pub struct Vec<T, A: Allocator> { _p: PhantomData<A>, }rust/kernel/alloc/kvec.rs +2
-0+/// Extension for Pin<Vec<T, A>> +pub trait PinnedVecExt <T > {Why is this an extension trait? Couldn't we directly implement this on
Vec<T>withself: Pin<&mut Self>?---
Cheers,
BennoQuoted 418 lines
+ /// Pin-initializes P and appends it to the back of the [
Vec] instance without reallocating.
+ fn push_pin_init<E: From<PushError<P>>, P: PinInit<T, E>>(&mut self, init: P) -> Result<(), E>;
+
+ /// Shortens the vector, setting the length tolenand drops the removed values.
+ /// Iflenis greater than or equal to the current length, this does nothing.
+ ///
+ /// This has no effect on the capacity and will not allocate. + fntruncate(&mut self, len: usize);
+
+ /// Removes the last element from a vector and drops it returning true, or false if it is empty.
+ fnpop(&mut self)-> bool;(quoted diff) +2
-0+} +/// Type alias for [
Vec] with a [Kmalloc] allocator. ///
/// # ExamplesQuoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Quoted 397 lines
Benno Lossin
reviewerRe: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 3 lines · Markus Probst
From what I can tell, there is no way to get a
Pin<&mut Vec<T, A>>from a&mut Pin<Vec<T, A>>. We can only getPin<&mut [T]>which is not usable in our case.
Hmm yeah that's true.
Quoted 2 lines
If there is way, without the extension trait or an extra struct, I would be happy to implement it.
So I tried to look for the usage site of this and I found this usage in your v1:
+ let mut leds = KPinnedVec::with_capacity(
+ Atmega1608LedAddress::VALUES.len() * Atmega1608LedId::VALUES.len(),
+ GFP_KERNEL,
+ )?;
+
+ let mut i = 0;
+ for addr in Atmega1608LedAddress::VALUES {
+ let mode_lock = Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
+
+ for id in Atmega1608LedId::VALUES {
+ let Some(child) =
+ fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))?)
+ else {
+ continue;
+ };
+
+ let client = ARef::clone(&client);
+ let mode_lock = Arc::clone(&mode_lock);
+
+ leds.push_pin_init(LedClassDev::new(
+ Some(idev),
+ None,
+ LedInitData::new().fwnode(&child),
+ Atmega1608Led {
+ addr,
+ id,
+ client,
+
+ mode_lock,
+ },
+ ))?;
+ i += 1;
+ }
+ }
+ Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())
And I think using Vec for this is just wrong. Vec is a data structure that supports growing and shrinking the allocation. But you just need a fixed size buffer that holds all your data. Do you think that Pin<Box<[LedClassDev]>> would suffice if it had proper support from pin-init?
Also, please don't top-post [1] and take a look at your mail client configuration, it puts lots of extra > at the end which looks pretty strange [2].
[1]: https://docs.kernel.org/process/submitting-patches.html#use-trimmed-interleaved-replies-in-email-discussions
[2]: https://lore.kernel.org/all/[email protected]
---
Cheers,
Benno
Quoted 41 lines
Thanks
- Markus ProbstQuoted 37 lines · Benno Lossin
rust/kernel/alloc/kvec.rs pub struct Vec<T, A: Allocator> { · line 115
Quoted 6 lines · Markus Probst
rust/kernel/alloc/kvec.rs +0
-0@@ -109,6 +111,21 @@ pub struct Vec<T, A: Allocator> { _p: PhantomData<A>, }rust/kernel/alloc/kvec.rs +2
-0+/// Extension for Pin<Vec<T, A>> +pub trait PinnedVecExt <T > {Why is this an extension trait? Couldn't we directly implement this on
Vec<T>withself: Pin<&mut Self>?---
Cheers,
BennoQuoted 21 lines
+ /// Pin-initializes P and appends it to the back of the [
Vec] instance without reallocating.
+ fn push_pin_init<E: From<PushError<P>>, P: PinInit<T, E>>(&mut self, init: P) -> Result<(), E>;
+
+ /// Shortens the vector, setting the length tolenand drops the removed values.
+ /// Iflenis greater than or equal to the current length, this does nothing.
+ ///
+ /// This has no effect on the capacity and will not allocate. + fntruncate(&mut self, len: usize);
+
+ /// Removes the last element from a vector and drops it returning true, or false if it is empty.
+ fnpop(&mut self)-> bool;(quoted diff) +2
-0+} +/// Type alias for [
Vec] with a [Kmalloc] allocator. ///
/// # Examples
Re: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 55 lines · Benno Lossin
Quoted 5 lines · Markus Probst
From what I can tell, there is no way to get a
Pin<&mut Vec<T, A>>
from a&mut Pin<Vec<T, A>>. We can only getPin<&mut [T]>which is
not usable in our case.Hmm yeah that's true.
Quoted 2 lines
If there is way, without the extension trait or an extra struct, I would be happy to implement it.
So I tried to look for the usage site of this and I found this usage in
your v1:+ let mut leds = KPinnedVec::with_capacity(
+Atmega1608LedAddress::VALUES.len()*Atmega1608LedId::VALUES.len(),
+GFP_KERNEL,
+ )?;
+
+ let mut i = 0;
+ for addr inAtmega1608LedAddress::VALUES{
+ letmode_lock=Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
+
+ for id inAtmega1608LedId::VALUES{
+ let Some(child) =
+ fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))?) + else {
+ continue;
+ };
+
+ let client =ARef::clone(&client);
+ letmode_lock=Arc::clone(&mode_lock); +
+ leds.push_pin_init(LedClassDev::new( + Some(idev),
+ None,
+ LedInitData::new().fwnode(&child), + Atmega1608Led {
+ addr,
+ id,
+ client,
+
+mode_lock,
+ },
+ ))?;
+ i += 1;
+ }
+ }
+Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())
Quoted 5 lines
And I think using
Vecfor this is just wrong.Vecis a data structure that supports growing and shrinking the allocation. But you just need a fixed size buffer that holds all your data. Do you think thatPin<Box<[LedClassDev]>>would suffice if it had proper support from pin-init?
As you can see in v1, the number of leds (or vec entries) depends on the fwnode (see the continue statement there). I don't think that counts as fixed size. Pin<KBox<[Option<LedClassDev>]>> could potentially be used instead of Pin<KVec<LedClassDev>> in my scenario, but that would require an extra byte of allocation for the max leds of 24 each and the code would look more ugly. At the point I use Option in the slice, its basically an unoptimized Vec (instead of storing the length, it stores if an item in the buffer is present or not).
Quoted 5 lines
Also, please don't top-post [1] and take a look at your mail client configuration, it puts lots of extra
>at the end which looks pretty
strange [2].
Yes, I did notice that. It is not present when writing a reply, but after it got sent for some reason (most replies, not all). It is GNOME Evolution in its default settings basically. My distro ships a 4 months outdated version (3.56.2), which shouldn't be too old, but I will investiage.
Thanks
- Markus Probst
Quoted 56 lines
[1]:
https://docs.kernel.org/process/submitting-patches.html#use-trimmed-interleaved-replies-in-email-discussions
[2]:
https://lore.kernel.org/all/[email protected]---
Cheers,
BennoQuoted 46 lines
Thanks
- Markus ProbstQuoted 42 lines · Benno Lossin
rust/kernel/alloc/kvec.rs pub struct Vec<T, A: Allocator> { · line 115
Quoted 6 lines · Markus Probst
rust/kernel/alloc/kvec.rs +0
-0@@ -109,6 +111,21 @@ pub struct Vec<T, A: Allocator> { _p: PhantomData<A>, }rust/kernel/alloc/kvec.rs +2
-0+/// Extension for Pin<Vec<T, A>> +pub trait PinnedVecExt <T > {Why is this an extension trait? Couldn't we directly implement this
onVec<T>withself: Pin<&mut Self>?---
Cheers,
BennoQuoted 25 lines
+ /// Pin-initializes P and appends it to the back of the [
Vec] instance without reallocating.
+ fn push_pin_init<E: From<PushError<P>>, P: PinInit<T, E>>(&mut
self, init: P) -> Result<(), E>;
+
+ /// Shortens the vector, setting the length tolenand drops
the removed values.
+ /// Iflenis greater than or equal to the current length,
this does nothing.
+ ///
+ /// This has no effect on the capacity and will not allocate.
+ fntruncate(&mut self, len: usize);
+
+ /// Removes the last element from a vector and drops it returning true, or false if it is empty.
+ fnpop(&mut self)-> bool;(quoted diff) +2
-0+} +/// Type alias for [
Vec] with a [Kmalloc] allocator. ///
/// # Examples
Benno Lossin
reviewerRe: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 61 lines · Markus Probst
Quoted 55 lines · Benno Lossin
Quoted 5 lines · Markus Probst
From what I can tell, there is no way to get a
Pin<&mut Vec<T, A>>
from a&mut Pin<Vec<T, A>>. We can only getPin<&mut [T]>which is
not usable in our case.Hmm yeah that's true.
Quoted 2 lines
If there is way, without the extension trait or an extra struct, I would be happy to implement it.
So I tried to look for the usage site of this and I found this usage in
your v1:+ let mut leds = KPinnedVec::with_capacity(
+Atmega1608LedAddress::VALUES.len()*Atmega1608LedId::VALUES.len(),
+GFP_KERNEL,
+ )?;
+
+ let mut i = 0;
+ for addr inAtmega1608LedAddress::VALUES{
+ letmode_lock=Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
+
+ for id inAtmega1608LedId::VALUES{
+ let Some(child) =
+ fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))?) + else {
+ continue;
+ };
+
+ let client =ARef::clone(&client);
+ letmode_lock=Arc::clone(&mode_lock); +
+ leds.push_pin_init(LedClassDev::new( + Some(idev),
+ None,
+ LedInitData::new().fwnode(&child), + Atmega1608Led {
+ addr,
+ id,
+ client,
+
+mode_lock,
+ },
+ ))?;
+ i += 1;
+ }
+ }
+Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())Quoted 5 lines
And I think using
Vecfor this is just wrong.Vecis a data structure that supports growing and shrinking the allocation. But you just need a fixed size buffer that holds all your data. Do you think thatPin<Box<[LedClassDev]>>would suffice if it had proper support from pin-init?
Quoted 8 lines
As you can see in v1, the number of leds (or vec entries) depends on the fwnode (see the continue statement there). I don't think that counts as fixed size.
Pin<KBox<[Option<LedClassDev>]>>could potentially be used instead ofPin<KVec<LedClassDev>>in my scenario, but that would require an extra byte of allocation for the max leds of 24 each and the code would look more ugly. At the point I use Option in the slice, its basically an unoptimized Vec (instead of storing the length, it stores if an item in the buffer is present or not).
You can just make the length of the slice be the desired length? (also, i is never incremented in the continue case, so it will act like a break?)
One option that we have would be storing the initializers in a vec:
fn probe(
pdev: &I2cClient<kernel::device::Core>,
_id_info: Option<&Self::IdInfo>,
) -> Result<Pin<KBox<Self>>> {
let idev = pdev.as_ref();
let Some(fwnode) = idev.fwnode() else {
return Err(EINVAL);
};
let client: ARef<I2cClient> = pdev.into();
client
.write_byte_data(1, 0)
.inspect_err(|err| dev_err!(idev, "unable to remove led mask: {err:?}\n"))?;
let mut led_init = KVec::new();
let mut i = 0;
for addr in Atmega1608LedAddress::VALUES {
let mode_lock = Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
for id in Atmega1608LedId::VALUES {
let Some(child) =
fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))?)
else {
continue;
};
let client = ARef::clone(&client);
let mode_lock = Arc::clone(&mode_lock);
led_init.push(LedClassDev::new(
Some(idev),
None,
LedInitData::new().fwnode(&child),
Atmega1608Led {
addr,
id,
client,
mode_lock,
},
))?;
i += 1;
}
}
let leds = Vec::pin_init_slice(led_init, GFP_KERNEL)?;
Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())
}And Vec::pin_init_slice would have the following signature:
fn pin_init_slice<T, I, E>(this: Vec<I>, flags: alloc::Flags) -> Result<Pin<Box<[T]>>>
where
I: PinInit<T, E>,
Error: From<E>;---
Cheers,
Benno
Quoted 23 lines
Quoted 6 lines
Also, please don't top-post [1] and take a look at your mail client configuration, it puts lots of extra
>at the end which looks pretty
strange [2].Yes, I did notice that. It is not present when writing a reply, but after it got sent for some reason (most replies, not all). It is GNOME Evolution in its default settings basically. My distro ships a 4 months outdated version (3.56.2), which shouldn't be too old, but I will investiage.
Thanks
- Markus Probst
Alice Ryhl
maintainerRe: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 6 lines · Benno Lossin
And
Vec::pin_init_slicewould have the following signature:fn pin_init_slice<T, I, E>(this: Vec<I>, flags: alloc::Flags) -> Result<Pin<Box<[T]>>> where I: PinInit<T, E>, Error: From<E>;
We already have Box::pin_slice().
Alice
Benno Lossin
reviewerRe: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 9 lines · Alice Ryhl
Quoted 6 lines · Benno Lossin
And
Vec::pin_init_slicewould have the following signature:fn pin_init_slice<T, I, E>(this: Vec<I>, flags: alloc::Flags) -> Result<Pin<Box<[T]>>> where I: PinInit<T, E>, Error: From<E>;We already have
Box::pin_slice().
Oh that's perfect :) I still think that the helper vec function above would be useful, if we want to use this pattern (collecting initializers in a vec) more broadly.
---
Cheers,
Benno
Re: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
In reply to Benno LossinQuoted 83 lines · Benno Lossin
Quoted 69 lines · Markus Probst
Quoted 60 lines · Benno Lossin
Quoted 6 lines · Markus Probst
From what I can tell, there is no way to get a
Pin<&mut Vec<T, A>>
from a&mut Pin<Vec<T, A>>. We can only getPin<&mut [T]>which
is
not usable in our case.Hmm yeah that's true.
Quoted 3 lines
If there is way, without the extension trait or an extra struct, I
would be happy to implement it.So I tried to look for the usage site of this and I found this usage
in
your v1:+ let mut leds = KPinnedVec::with_capacity( +
Atmega1608LedAddress::VALUES.len()*Atmega1608LedId::VALUES.len(),
+GFP_KERNEL,
+ )?;
+
+ let mut i = 0;
+ for addr inAtmega1608LedAddress::VALUES{ + letmode_lock=Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
+
+ for id inAtmega1608LedId::VALUES{
+ let Some(child) =
+fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))? )
+ else {
+ continue;
+ };
+
+ let client =ARef::clone(&client); + letmode_lock=Arc::clone(&mode_lock); +
+ leds.push_pin_init(LedClassDev::new( + Some(idev),
+ None,
+ LedInitData::new().fwnode(&child), + Atmega1608Led {
+ addr,
+ id,
+ client,
+
+mode_lock,
+ },
+ ))?;
+ i += 1;
+ }
+ }
+Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())Quoted 8 lines
And I think using
Vecfor this is just wrong.Vecis a data structure that supports growing and shrinking the allocation. But you
just need a fixed size buffer that holds all your data. Do you think
thatPin<Box<[LedClassDev]>>would suffice if it had proper support
from pin-init?Quoted 12 lines
As you can see in v1, the number of leds (or vec entries) depends on
the fwnode (see the continue statement there). I don't think that counts as fixed size.Pin<KBox<[Option<LedClassDev>]>>could potentially be used instead ofPin<KVec<LedClassDev>>in my scenario,
but that would require an extra byte of allocation for the max leds of
24 each and the code would look more ugly. At the point I use Option in
the slice, its basically an unoptimized Vec (instead of storing the length, it stores if an item in the buffer is present or not).
Quoted 1 line
You can just make the length of the slice be the desired length?
That would work, but creates another allocation on the heap (Vec<I>) that could have been avoided. I don't think it would make Pin<Vec<T, A>> obsolete.
Or would you rather say, such allocations don't matter?
Quoted 4 lines
(also,
iis never incremented in thecontinuecase, so it will act like abreak?)
You just found a bug in v1.
Thanks
- Markus Probst
[1] https://docs.rs/arrayvec/latest/arrayvec/struct.ArrayString.html
Quoted 94 lines
One option that we have would be storing the initializers in a vec:
fn probe(
pdev: &I2cClient<kernel::device::Core>,_id_info: Option<&Self::IdInfo>,
) -> Result<Pin<KBox<Self>>> {
let idev =pdev.as_ref();
let Some(fwnode) =idev.fwnode()else {
return Err(EINVAL);
};
let client: ARef<I2cClient> =pdev.into();
client
.write_byte_data(1, 0)
.inspect_err(|err| dev_err!(idev, "unable to remove led
mask: {err:?}\n"))?;
let mutled_init=KVec::new();
let mut i = 0;
for addr inAtmega1608LedAddress::VALUES{
letmode_lock=Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
for id inAtmega1608LedId::VALUES{
let Some(child) =
fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))?) else {
continue;
};
let client =ARef::clone(&client);
letmode_lock=Arc::clone(&mode_lock);
led_init.push(LedClassDev::new( Some(idev),
None, LedInitData::new().fwnode(&child), Atmega1608Led {
addr,
id,
client,
mode_lock,
},
))?;
i += 1;
}
}
let leds =Vec::pin_init_slice(led_init, GFP_KERNEL)?;Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())}And
Vec::pin_init_slicewould have the following signature:fn pin_init_slice<T, I, E>(this: Vec<I>, flags:
alloc::Flags) -> Result<Pin<Box<[T]>>>
where
I: PinInit<T, E>,
Error: From<E>;---
Cheers,
BennoQuoted 26 lines
Quoted 7 lines
Also, please don't top-post [1] and take a look at your mail client
configuration, it puts lots of extra>at the end which looks pretty
strange [2].Yes, I did notice that. It is not present when writing a reply, but after it got sent for some reason (most replies, not all). It is GNOME
Evolution in its default settings basically. My distro ships a 4 months
outdated version (3.56.2), which shouldn't be too old, but I will investiage.Thanks
- Markus Probst
Benno Lossin
reviewerRe: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 84 lines · Markus Probst
Quoted 83 lines · Benno Lossin
Quoted 81 lines · Markus Probst
Quoted 60 lines · Benno Lossin
Quoted 6 lines · Markus Probst
From what I can tell, there is no way to get a
Pin<&mut Vec<T, A>>
from a&mut Pin<Vec<T, A>>. We can only getPin<&mut [T]>which
is
not usable in our case.Hmm yeah that's true.
Quoted 3 lines
If there is way, without the extension trait or an extra struct, I
would be happy to implement it.So I tried to look for the usage site of this and I found this usage
in
your v1:+ let mut leds = KPinnedVec::with_capacity( +
Atmega1608LedAddress::VALUES.len()*Atmega1608LedId::VALUES.len(),
+GFP_KERNEL,
+ )?;
+
+ let mut i = 0;
+ for addr inAtmega1608LedAddress::VALUES{ + letmode_lock=Arc::pin_init(new_mutex!(()), GFP_KERNEL)?;
+
+ for id inAtmega1608LedId::VALUES{
+ let Some(child) =
+fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i}"))? )
+ else {
+ continue;
+ };
+
+ let client =ARef::clone(&client); + letmode_lock=Arc::clone(&mode_lock); +
+ leds.push_pin_init(LedClassDev::new( + Some(idev),
+ None,
+ LedInitData::new().fwnode(&child), + Atmega1608Led {
+ addr,
+ id,
+ client,
+
+mode_lock,
+ },
+ ))?;
+ i += 1;
+ }
+ }
+Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())Quoted 8 lines
And I think using
Vecfor this is just wrong.Vecis a data structure that supports growing and shrinking the allocation. But you
just need a fixed size buffer that holds all your data. Do you think
thatPin<Box<[LedClassDev]>>would suffice if it had proper support
from pin-init?As you can see in v1, the number of leds (or vec entries) depends on
the fwnode (see the continue statement there). I don't think that counts as fixed size.Pin<KBox<[Option<LedClassDev>]>>could potentially be used instead ofPin<KVec<LedClassDev>>in my scenario,
but that would require an extra byte of allocation for the max leds of
24 each and the code would look more ugly. At the point I use Option in
the slice, its basically an unoptimized Vec (instead of storing the length, it stores if an item in the buffer is present or not).
Quoted 6 lines
Quoted 1 line
You can just make the length of the slice be the desired length?
That would work, but creates another allocation on the heap (Vec<I>) that could have been avoided. I don't think it would make
Pin<Vec<T, A>>obsolete.Or would you rather say, such allocations don't matter?
No, but you're already allocating once per inner loop invocation, the CString::try_from_fmt function allocates :)
I don't know the kind of application that you're writing, does performance matter? If yes, then just run your benchmark suite on both versions and look at the difference. If you don't have a benchmark suite, then perf probably isn't important enough.
Also if you really want to avoid the allocation, then you probably could first query the length and store only that in a local var and then create the initializers on-demand. But then again to query that you're creating a string every loop iteration, which allocates :)
Quoted 5 lines
Quoted 4 lines
(also,
iis never incremented in thecontinuecase, so it will act like abreak?)You just found a bug in v1.
:)
Quoted 4 lines
Thanks
- Markus Probst[1] https://docs.rs/arrayvec/latest/arrayvec/struct.ArrayString.html
Did you forget to put a reference to this?
---
Cheers,
Benno
Re: [PATCH v4 1/2] rust: add basic Pin<Vec<T, A>> abstractions
Quoted 106 lines · Benno Lossin
Quoted 96 lines · Markus Probst
Quoted 95 lines · Benno Lossin
Quoted 93 lines · Markus Probst
Quoted 65 lines · Benno Lossin
Quoted 8 lines · Markus Probst
From what I can tell, there is no way to get a `Pin<&mut Vec<T,
A>>`
from a&mut Pin<Vec<T, A>>. We can only getPin<&mut [T]>
which
is
not usable in our case.Hmm yeah that's true.
Quoted 3 lines
If there is way, without the extension trait or an extra struct, I
would be happy to implement it.So I tried to look for the usage site of this and I found this
usage
in
your v1:+ let mut leds = KPinnedVec::with_capacity( +
Atmega1608LedAddress::VALUES.len()*Atmega1608LedId::VALUES.len(),
+GFP_KERNEL,
+ )?;
+
+ let mut i = 0;
+ for addr inAtmega1608LedAddress::VALUES{ + letmode_lock= Arc::pin_init(new_mutex!(()),GFP_KERNEL)?;
+
+ for id inAtmega1608LedId::VALUES{ + let Some(child) =
+ fwnode.get_child_by_name(&CString::try_from_fmt(fmt!("led@{i} "))?
)
+ else {
+ continue;
+ };
+
+ let client =ARef::clone(&client); + letmode_lock=Arc::clone(&mode_lock); +
+ leds.push_pin_init(LedClassDev::new( + Some(idev),
+ None,
+ LedInitData::new().fwnode(&child), + Atmega1608Led {
+ addr,
+ id,
+ client,
+
+mode_lock,
+ },
+ ))?;
+ i += 1;
+ }
+ }
+Ok(KBox::new(Self { client, leds }, GFP_KERNEL)?.into())Quoted 11 lines
And I think using
Vecfor this is just wrong.Vecis a data
structure that supports growing and shrinking the allocation. But
you
just need a fixed size buffer that holds all your data. Do you
think
thatPin<Box<[LedClassDev]>>would suffice if it had proper support
from pin-init?As you can see in v1, the number of leds (or vec entries) depends
on
the fwnode (see the continue statement there). I don't think that
counts as fixed size.Pin<KBox<[Option<LedClassDev>]>>could potentially be used instead ofPin<KVec<LedClassDev>>in my scenario,
but that would require an extra byte of allocation for the max leds
of
24 each and the code would look more ugly. At the point I use Option in
the slice, its basically an unoptimized Vec (instead of storing the
length, it stores if an item in the buffer is present or not).Quoted 8 lines
Quoted 1 line
You can just make the length of the slice be the desired length?
That would work, but creates another allocation on the heap (Vec<I>)
that could have been avoided. I don't think it would make `Pin<Vec<T,
A>>` obsolete.Or would you rather say, such allocations don't matter?
Quoted 8 lines
No, but you're already allocating once per inner loop invocation, the
CString::try_from_fmtfunction allocates :)I don't know the kind of application that you're writing, does performance matter? If yes, then just run your benchmark suite on both
versions and look at the difference. If you don't have a benchmark suite, then perf probably isn't important enough.
There is no model that would be able to make use of this driver under 4 GB of RAM, but I assumed code should be as optimized as possible in the linux kernel. Its only run once at driver initialization, so it doesn't matter for me at least.
Quoted 17 lines
Also if you really want to avoid the allocation, then you probably could
first query the length and store only that in a local var and then create the initializers on-demand. But then again to query that you're
creating a string every loop iteration, which allocates :)Quoted 6 lines
Quoted 5 lines
(also,
iis never incremented in thecontinuecase, so it will act like
abreak?)You just found a bug in v1.
:)
Quoted 7 lines
Quoted 5 lines
Thanks
- Markus Probst[1]
https://docs.rs/arrayvec/latest/arrayvec/struct.ArrayString.htmlDid you forget to put a reference to this?
I did also notice the CString::try_from_fmt while writing the email. There was once a part in the email which I removed (I would have dealt with it later), in which I would have asked if it would also make sense to add an abstraction for fixed-allocated c strings on the stack (as it currently would also have been an unnecessary allocation). The link was meant as reference to an existing implementation (which I forgot to remove).
Thanks
- Markus Probst
Quoted 4 lines
---
Cheers,
Benno
PATCH v4 2/2 rust: leds: add basic led classdev abstractions
In reply to Markus ProbstImplement the core abstractions needed for led class devices, including:
* led::LedOps - the trait for handling leds, including brightness_set, brightness_get and blink_set
* led::InitData - data set for the led class device
* led::Device - a safe wrapper around led_classdev
--- rust/kernel/led.rs | 333 +++++++++++++++++++++++++++++++++++++++++++++ rust/kernel/lib.rs | 1 + 2 files changed, 334 insertions(+) create mode 100644 rust/kernel/led.rs
rust/kernel/led.rs new file +333 -0
@@ -0,0 +1,333 @@ +// SPDX-License-Identifier: GPL-2.0 + +//! Abstractions for the leds driver model. +//! +//! C header: [`include/linux/leds.h`](srctree/include/linux/leds.h) + +use core::{marker::PhantomData , pin::Pin , ptr::NonNull }; + +use pin_init::{pin_data, pinned_drop,PinInit }; + +use crate ::{ + build_error, container_of, + device::{self, property::FwNode ,Bound }, + devres::Devres , + error::{from_result, to_result,Error ,Result ,VTABLE_DEFAULT_ERROR }, + macros::vtable, + str::CStr , + try_pin_init, + types::{ARef ,Opaque }, +}; + +/// The led class device representation. +/// +/// This structure represents the Rust abstraction for a C `struct led_classdev`. +#[pin_data( PinnedDrop )] +pub struct Device <T :LedOps > { + ops:T , +#[pin] + classdev:Opaque <bindings::led_classdev >, +} + +/// The led init data representation. +/// +/// This structure represents the Rust abstraction for a C `struct led_init_data`. +#[derive( Default )] +pub struct InitData <'a> { + fwnode:Option <&'aFwNode >, + default_label:Option <&'aCStr >, + devicename:Option <&'aCStr >, + devname_mandatory:bool , +} + +impl InitData <'static> { +/// Creates a new [`InitData`] +pub fn new () ->Self { +Self ::default () + } +} + +impl <'a>InitData <'a> { +/// Sets the firmware node +pub fn fwnode <'b, 'c>(self, fwnode: &'bFwNode ) ->InitData <'c> +where + 'a: 'c, + 'b: 'c, + { +InitData { + fwnode:Some (fwnode), + ..self + } + } + +/// Sets a default label +pub fn default_label <'b, 'c>(self, label: &'bCStr ) ->InitData <'c> +where + 'a: 'c, + 'b: 'c, + { +InitData { + default_label:Some (label), + ..self + } + } + +/// Sets the device name +pub fn devicename <'b, 'c>(self, devicename: &'bCStr ) ->InitData <'c> +where + 'a: 'c, + 'b: 'c, + { +InitData { + devicename:Some (devicename), + ..self + } + } + +/// Sets if a device name is mandatory +pub fn devicename_mandatory (self, mandatory:bool ) ->Self { +Self { + devname_mandatory: mandatory, + + ..self + } + } +} + +/// Trait defining the operations for a LED driver. +/// +/// # Examples +/// +///``` +/// # use kernel::{c_str, led, device, devres::Devres, prelude::*, error::Result, macros::vtable}; +/// # use core::pin::Pin; +/// +/// struct MyLedOps; +/// +/// +/// #[vtable] +/// impl led::LedOps for MyLedOps { +/// const BLOCKING: bool = false; +/// const MAX_BRIGHTNESS: u32 = 255; +/// +/// fn brightness_set(&self, _brightness: u32) -> Result<()> { +/// // Set the brightness for the led here +/// Ok(()) +/// } +/// } +/// +/// fn register_my_led( +/// parent: &device::Device<device::Bound>, +/// ) -> Result<Pin<KBox<Devres<led::Device<MyLedOps>>>>> { +/// KBox::pin_init(led::Device::new( +/// parent, +/// led::InitData::new() +/// .default_label(c_str!("my_led")), +/// MyLedOps, +/// ), GFP_KERNEL) +/// } +///``` +/// Led drivers must implement this trait in order to register and handle a [`Device`]. +#[vtable] +pub trait LedOps :Send + 'static +Sized { +/// If set true, [`LedOps::brightness_set`] and [`LedOps::blink_set`] must not sleep +/// and perform the operation immediately. +const BLOCKING :bool ; +/// The max brightness level +const MAX_BRIGHTNESS :u32 ; + +/// Sets the brightness level. +/// +/// See also [`LedOps::BLOCKING`] +fn brightness_set (&self, brightness:u32 ) ->Result <()>; + +/// Gets the current brightness level. +fn brightness_get (&self) ->u32 { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Activates hardware accelerated blinking. +/// +/// delays are in milliseconds. If both are zero, a sensible default should be chosen. +/// The caller should adjust the timings in that case and if it can't match the values +/// specified exactly. Setting the brightness to 0 will disable the hardware accelerated +/// blinking. +/// +/// See also [`LedOps::BLOCKING`] +fn blink_set (&self, _delay_on: &mut usize , _delay_off: &mut usize ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + } +} + +// SAFETY: A `led::Device` can be unregistered from any thread. +unsafe impl <T :LedOps +Send >Send for Device <T > {} + +// SAFETY: `led::Device` can be shared among threads because all methods of `led::Device` +// are thread safe. +unsafe impl <T :LedOps +Sync >Sync for Device <T > {} + +impl <T :LedOps >Device <T > { +/// Registers a new led classdev. +/// +/// The [`Device`] will be unregistered on drop. +pub fn new <'a>( + parent: &'a device::Device <Bound >, + init_data:InitData <'a>, + ops:T , + ) ->impl PinInit <Devres <Self >,Error > + 'a { +Devres ::new ( + parent, +try_pin_init! (Self { + ops, + classdev <-Opaque ::try_ffi_init (|ptr: *mut bindings::led_classdev | { +// SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write. +// `led_classdev` gets fully initialized in-place by +// `led_classdev_register_ext` including `mutex` and `list_head`. +unsafe { ptr.write (bindings::led_classdev { + max_brightness:T ::MAX_BRIGHTNESS , + brightness_set:T ::BLOCKING + .then_some (Adapter ::<T >::brightness_set_callback), + brightness_set_blocking: (!T ::BLOCKING ) + .then_some (Adapter ::<T >::brightness_set_blocking_callback), + brightness_get:T ::HAS_BRIGHTNESS_GET + .then_some (Adapter ::<T >::brightness_get_callback), + blink_set:T ::HAS_BLINK_SET + .then_some (Adapter ::<T >::blink_set_callback), + .. bindings::led_classdev::default () + }) }; + +let fwnode = init_data.fwnode.map (ARef ::from); + +let mut init_data = bindings::led_init_data { + fwnode: fwnode.as_ref () + .map_or (core::ptr::null_mut (), |fwnode| fwnode.as_raw ()), + default_label: init_data.default_label + .map_or (core::ptr::null (),CStr ::as_char_ptr), + devicename: init_data.devicename + .map_or (core::ptr::null (),CStr ::as_char_ptr), + devname_mandatory: init_data.devname_mandatory, + }; + +// SAFETY: +// - `parent.as_raw()` is guaranteed to be a pointer to a valid `device` +// or a null pointer. +// - `ptr` is guaranteed to be a pointer to an initialized `led_classdev`. +to_result (unsafe { + bindings::led_classdev_register_ext (parent.as_raw (), ptr, &mut init_data) + })?; + + core::mem::forget (fwnode);// keep the reference count incremented + +Ok ::<_ ,Error >(()) + }), + }), + ) + } + +/// # Safety +/// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a +/// `led::Device`. +unsafe fn from_raw <'a>(led_cdev: *mut bindings::led_classdev ) -> &'aSelf { +// SAFETY: The function's contract guarantees that `led_cdev` points to a `led_classdev` +// field embedded within a valid `led::Device`. `container_of!` can therefore +// safely calculate the address of the containing struct. +unsafe { &*container_of! (Opaque ::cast_from (led_cdev),Self , classdev) } + } +} + +struct Adapter <T :LedOps > { + _p:PhantomData <T >, +} + +impl <T :LedOps >Adapter <T > { +/// # Safety +/// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a +/// `led::Device`. +/// This function is called on setting the brightness of a led. +unsafe extern "C" fn brightness_set_callback ( + led_cdev: *mut bindings::led_classdev , + brightness:u32 , + ) { +// SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a +// `led_classdev` embedded within a `led::Device`. +let _ =unsafe {Device ::<T >::from_raw (led_cdev) } + .ops + .brightness_set (brightness); + } + +/// # Safety +/// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a +/// `led::Device`. +/// This function is called on setting the brightness of a led immediately. +unsafe extern "C" fn brightness_set_blocking_callback ( + led_cdev: *mut bindings::led_classdev , + brightness:u32 , + ) ->i32 { +from_result (|| { +// SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a +// `led_classdev` embedded within a `led::Device`. +unsafe {Device ::<T >::from_raw (led_cdev) } + .ops + .brightness_set (brightness)?; +Ok (0 ) + }) + } + +/// # Safety +/// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a +/// `led::Device`. +/// This function is called on getting the brightness of a led. +unsafe extern "C" fn brightness_get_callback (led_cdev: *mut bindings::led_classdev ) ->u32 { +// SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a +// `led_classdev` embedded within a `led::Device`. +unsafe {Device ::<T >::from_raw (led_cdev) } + .ops + .brightness_get () + } + +/// # Safety +/// `led_cdev` must be a valid pointer to a `led_classdev` embedded within a +/// `led::Device`. +/// `delay_on` and `delay_off` must be valid pointers to `usize` and have +/// exclusive access for the period of this function. +/// This function is called on enabling hardware accelerated blinking. +unsafe extern "C" fn blink_set_callback ( + led_cdev: *mut bindings::led_classdev , + delay_on: *mut usize , + delay_off: *mut usize , + ) ->i32 { +from_result (|| { +// SAFETY: The function's contract guarantees that `led_cdev` is a valid pointer to a +// `led_classdev` embedded within a `led::Device`. +unsafe {Device ::<T >::from_raw (led_cdev) }.ops.blink_set ( +// SAFETY: The function's contract guarantees that `delay_on` points to a `usize` +// and is exclusive for the period of this function. +unsafe { &mut *delay_on }, +// SAFETY: The function's contract guarantees that `delay_off` points to a `usize` +// and is exclusive for the period of this function. +unsafe { &mut *delay_off }, + )?; +Ok (0 ) + }) + } +} + +#[pinned_drop] +impl <T :LedOps >PinnedDrop for Device <T > { +fn drop (self:Pin <&mut Self >) { +let raw = self.classdev.get (); +// SAFETY: The existence of `self` guarantees that `self.classdev.get()` is a pointer to a +// valid `struct led_classdev`. +let dev: &device::Device =unsafe { device::Device ::from_raw ((*raw).dev) }; + +let _fwnode = dev + .fwnode () +// SAFETY: the reference count of `fwnode` has previously been +// incremented in `led::Device::new`. + .map (|fwnode|unsafe {ARef ::from_raw (NonNull ::from (fwnode)) }); + +// SAFETY: The existence of `self` guarantees that `self.classdev` has previously been +// successfully registered with `led_classdev_register_ext`. +unsafe { bindings::led_classdev_unregister (self.classdev.get ()) }; + } +}
rust/kernel/lib.rs +1 -0
@@ -97,6 +97,7 @@pub mod jump_label;#[cfg( CONFIG_KUNIT )] pub mod kunit; +pub mod led;pub mod list;pub mod miscdevice;pub mod mm;
Signature · 1 line
2.49.1
Alice Ryhl
maintainerRe: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
Quoted 29 lines · Markus Probst
Implement the core abstractions needed for led class devices, including:
*
led::LedOps- the trait for handling leds, includingbrightness_set,brightness_getandblink_set*
led::InitData- data set for the led class device*
led::Device- a safe wrapper aroundled_classdevSigned-off-by Markus Probst <[email protected]>rust/kernel/led.rs new file +18
-0+pub trait LedOps :Send + 'static +Sized { +/// If set true, [`LedOps::brightness_set`] and [`LedOps::blink_set`] must not sleep +/// and perform the operation immediately. +const BLOCKING :bool ; +/// The max brightness level +const MAX_BRIGHTNESS :u32 ; + +/// Sets the brightness level. +/// +/// See also [`LedOps::BLOCKING`] +fn brightness_set (&self, brightness:u32 ) ->Result <()>; + +/// Gets the current brightness level. +fn brightness_get (&self) ->u32 { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Activates hardware accelerated blinking.
rust/kernel/led.rs line 159
Quoted 10 lines
rust/kernel/led.rs new file +10
-0+/// +/// delays are in milliseconds. If both are zero, a sensible default should be chosen. +/// The caller should adjust the timings in that case and if it can't match the values +/// specified exactly. Setting the brightness to 0 will disable the hardware accelerated +/// blinking. +/// +/// See also [`LedOps::BLOCKING`] +fn blink_set (&self, _delay_on: &mut usize , _delay_off: &mut usize ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + }
These functions should probably take a &Device<Bound> argument so that they can use methods that require a bound device (such as IO).
Quoted 19 lines
rust/kernel/led.rs new file +19
-0+impl<T: LedOps> Device<T> { + /// Registers a new led classdev. + /// + /// The [`Device`] will be unregistered on drop. + pub fn new<'a>( + parent: &'a device::Device<Bound>, + init_data: InitData<'a>, + ops: T, + ) -> impl PinInit<Devres<Self>, Error> + 'a { + Devres::new( + parent, + try_pin_init!(Self { + ops, + classdev <- Opaque::try_ffi_init(|ptr: *mut bindings::led_classdev| { + // SAFETY: `try_ffi_init` guarantees that `ptr` is valid for write. + // `led_classdev` gets fully initialized in-place by + // `led_classdev_register_ext` including `mutex` and `list_head`. + unsafe { ptr.write(bindings::led_classdev { + max_brightness: T::MAX_BRIGHTNESS,
rust/kernel/led.rs line 197
Quoted 10 lines
rust/kernel/led.rs new file +10
-0+ brightness_set: T::BLOCKING + .then_some(Adapter::<T>::brightness_set_callback), + brightness_set_blocking: (!T::BLOCKING) + .then_some(Adapter::<T>::brightness_set_blocking_callback), + brightness_get: T::HAS_BRIGHTNESS_GET + .then_some(Adapter::<T>::brightness_get_callback), + blink_set: T::HAS_BLINK_SET + .then_some(Adapter::<T>::blink_set_callback), + .. bindings::led_classdev::default () + }) };
This doesn't look like something rustfmt would output? Could you run rustfmt if you haven't already. If it doesn't do anything, then please format it outside of the macro and move it back in.
Alice
Danilo Krummrich
maintainerRe: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
Quoted 35 lines · Alice Ryhl
Quoted 34 lines · Markus Probst
Implement the core abstractions needed for led class devices, including:
*
led::LedOps- the trait for handling leds, includingbrightness_set,brightness_getandblink_set*
led::InitData- data set for the led class device*
led::Device- a safe wrapper aroundled_classdevSigned-off-by Markus Probst <[email protected]>rust/kernel/led.rs new file +23
-0+pub trait LedOps :Send + 'static +Sized { +/// If set true, [`LedOps::brightness_set`] and [`LedOps::blink_set`] must not sleep +/// and perform the operation immediately. +const BLOCKING :bool ; +/// The max brightness level +const MAX_BRIGHTNESS :u32 ; + +/// Sets the brightness level. +/// +/// See also [`LedOps::BLOCKING`] +fn brightness_set (&self, brightness:u32 ) ->Result <()>; + +/// Gets the current brightness level. +fn brightness_get (&self) ->u32 { +build_error! (VTABLE_DEFAULT_ERROR ) + } + +/// Activates hardware accelerated blinking. +/// +/// delays are in milliseconds. If both are zero, a sensible default should be chosen. +/// The caller should adjust the timings in that case and if it can't match the values +/// specified exactly. Setting the brightness to 0 will disable the hardware accelerated +/// blinking.
Quoted 8 lines
rust/kernel/led.rs line 159
Quoted 5 lines
rust/kernel/led.rs new file +5
-0+/// +/// See also [`LedOps::BLOCKING`] +fn blink_set (&self, _delay_on: &mut usize , _delay_off: &mut usize ) ->Result <()> { +build_error! (VTABLE_DEFAULT_ERROR ) + }These functions should probably take a &Device<Bound> argument so that they can use methods that require a bound device (such as IO).
Indeed!
@Markus: Note that this guarantee is given by the LED device registration being lifetime controlled by devres, while led_classdev_unregister() is synchronized against those callbacks.
For the latter, please double check that this is actually the case -- I'm not familiar with the LED subsystem, I'm reviewing from driver-core perspective. But from a quick look it should be the case. :)
Re: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
Quoted 60 lines · Danilo Krummrich
Quoted 42 lines · Alice Ryhl
Quoted 41 lines · Markus Probst
Implement the core abstractions needed for led class devices, including:
*
led::LedOps- the trait for handling leds, includingbrightness_set,brightness_getandblink_set*
led::InitData- data set for the led class device*
led::Device- a safe wrapper aroundled_classdevSigned-off-by Markus Probst <[email protected]>+pub trait LedOps: Send + 'static + Sized { + /// If set true, [
LedOps::brightness_set] and [LedOps::blink_set] must not sleep
+ /// and perform the operation immediately. + const BLOCKING: bool;
+ /// The max brightness level
+ constMAX_BRIGHTNESS: u32;rust/kernel/led.rs new file +14
-0+ + /// Sets the brightness level. + /// + /// See also [`LedOps::BLOCKING`] + fn brightness_set(&self, brightness: u32) -> Result<()>; + + /// Gets the current brightness level. + fn brightness_get(&self) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Activates hardware accelerated blinking. + /// + /// delays are in milliseconds. If both are zero, a sensibledefault should be chosen.
+ /// The caller should adjust the timings in that case and if it can't match the values
+ /// specified exactly. Setting the brightness to 0 will disable the hardware accelerated
+ /// blinking.
+ ///
+ /// See also [LedOps::BLOCKING]Quoted 8 lines
Quoted 4 lines
+ fn
blink_set(&self, _delay_on: &mut usize, _delay_off: &mut usize)-> Result<()> {
+ build_error!(VTABLE_DEFAULT_ERROR)
+ }These functions should probably take a &Device<Bound> argument so that
they can use methods that require a bound device (such as IO).Indeed!
@Markus: Note that this guarantee is given by the LED device registration being
lifetime controlled by devres, whileled_classdev_unregister()is synchronized
against those callbacks.
Quoted 5 lines
For the latter, please double check that this is actually the case -- I'm not
familiar with the LED subsystem, I'm reviewing from driver-core perspective. But
from a quick look it should be the case. :)
There is also the led_classdev->dev device, but I assume you mean the parent of the led classdev (the one being passed on register)?
Thanks
- Markus Probst
Re: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
In reply to Alice RyhlQuoted 42 lines · Alice Ryhl
Quoted 41 lines · Markus Probst
Implement the core abstractions needed for led class devices, including:
*
led::LedOps- the trait for handling leds, includingbrightness_set,brightness_getandblink_set*
led::InitData- data set for the led class device*
led::Device- a safe wrapper aroundled_classdevSigned-off-by Markus Probst <[email protected]>+pub trait LedOps: Send + 'static + Sized { + /// If set true, [
LedOps::brightness_set] and [LedOps::blink_set] must not sleep
+ /// and perform the operation immediately. + const BLOCKING: bool;
+ /// The max brightness level
+ constMAX_BRIGHTNESS: u32;rust/kernel/led.rs new file +14
-0+ + /// Sets the brightness level. + /// + /// See also [`LedOps::BLOCKING`] + fn brightness_set(&self, brightness: u32) -> Result<()>; + + /// Gets the current brightness level. + fn brightness_get(&self) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Activates hardware accelerated blinking. + /// + /// delays are in milliseconds. If both are zero, a sensibledefault should be chosen.
+ /// The caller should adjust the timings in that case and if it can't match the values
+ /// specified exactly. Setting the brightness to 0 will disable the hardware accelerated
+ /// blinking.
+ ///
+ /// See also [LedOps::BLOCKING]
Quoted 8 lines
Quoted 4 lines
+ fn
blink_set(&self, _delay_on: &mut usize, _delay_off: &mut usize)-> Result<()> {
+ build_error!(VTABLE_DEFAULT_ERROR)
+ }These functions should probably take a &Device<Bound> argument so that
they can use methods that require a bound device (such as IO).
How about instead something like
mod device {
unsafe trait Container<Ctx: DeviceContext>: AsRef<Device<Ctx>> {
const Offset: usize; unsafe fn from_device(dev: &Device<Ctx>) -> &Self {
<implementation here>
}}
unsafe impl Device<Ctx> for Container<Ctx> {
const Offset: usize = 0;
}}
And instead of passing &Device<Bound> to the functions, we should add a type parameter to LedOps, e.g.:
trait LedOps<T: device::Container<device::Bound>> {
...
fn brightness_set(&self, dev: &T, brightness: u32) -> Result<()>;
...
}
impl<T: LedOps<E>, E: device::Container<device::Bound>> Device<T> {
pub fn new<'a>(
parent: &'a E,
init_data: InitData<'a>,
ops: T,
) -> impl PinInit<Devres<Self>, Error> + 'a {
...
}...
}
In the example of i2c (or any other container for struct device), we implement the device::Container trait:
mod i2c {
unsafe impl device::Container for I2cClient {
const Offset: usize = offset_of!(bindings::i2c_client, dev);
}}
This allows the LedOps function to use any functions from the I2cClient or any other device container which may be used (removing the need to store it inside the LedOps implementations struct). It still allows Device<Bound> to be used, as it also would implement device::Container.
Thanks
- Markus Probst
Quoted 45 lines
Quoted 30 lines
+impl<T: LedOps> Device<T> {
+ /// Registers a new led classdev.
+ ///
+ /// The [Device] will be unregistered on drop.
+ pub fn new<'a>(
+ parent: &'a device::Device<Bound>,
+init_data: InitData<'a>,
+ ops: T,
+ ) -> impl PinInit<Devres<Self>, Error> + 'a {
+ Devres::new(
+ parent,
+ try_pin_init!(Self {
+ ops,
+ classdev <- Opaque::try_ffi_init(|ptr: *mut bindings::led_classdev| {
+ // SAFETY:try_ffi_initguarantees thatptris valid for write.
+ //led_classdevgets fully initialized in- place by
+ //led_classdev_register_extincludingmutexandlist_head.
+ unsafe { ptr.write(bindings::led_classdev { +max_brightness:T::MAX_BRIGHTNESS, +brightness_set:T::BLOCKING
+
.then_some(Adapter::<T>::brightness_set_callback),
+brightness_set_blocking: (!T::BLOCKING) + .then_some(Adapter::<T>::brightness_set_blocking_callback),Quoted 8 lines
+
brightness_get:T::HAS_BRIGHTNESS_GET+
.then_some(Adapter::<T>::brightness_get_callback),
+blink_set:T::HAS_BLINK_SET+
.then_some(Adapter::<T>::blink_set_callback),
+ ..bindings::led_classdev::default()+ }) };This doesn't look like something rustfmt would output? Could you run rustfmt if you haven't already. If it doesn't do anything, then please
format it outside of the macro and move it back in.Alice
Danilo Krummrich
maintainerRe: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
Quoted 105 lines · Markus Probst
Quoted 42 lines · Alice RyhlV
Quoted 41 lines · Markus Probst
Implement the core abstractions needed for led class devices, including:
*
led::LedOps- the trait for handling leds, includingbrightness_set,brightness_getandblink_set*
led::InitData- data set for the led class device*
led::Device- a safe wrapper aroundled_classdevSigned-off-by Markus Probst <[email protected]>+pub trait LedOps: Send + 'static + Sized { + /// If set true, [
LedOps::brightness_set] and [LedOps::blink_set] must not sleep
+ /// and perform the operation immediately. + const BLOCKING: bool;
+ /// The max brightness level
+ constMAX_BRIGHTNESS: u32;rust/kernel/led.rs new file +14
-0+ + /// Sets the brightness level. + /// + /// See also [`LedOps::BLOCKING`] + fn brightness_set(&self, brightness: u32) -> Result<()>; + + /// Gets the current brightness level. + fn brightness_get(&self) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Activates hardware accelerated blinking. + /// + /// delays are in milliseconds. If both are zero, a sensibledefault should be chosen.
+ /// The caller should adjust the timings in that case and if it can't match the values
+ /// specified exactly. Setting the brightness to 0 will disable the hardware accelerated
+ /// blinking.
+ ///
+ /// See also [LedOps::BLOCKING]Quoted 8 lines
Quoted 4 lines
+ fn
blink_set(&self, _delay_on: &mut usize, _delay_off: &mut usize)-> Result<()> {
+ build_error!(VTABLE_DEFAULT_ERROR)
+ }These functions should probably take a &Device<Bound> argument so that
they can use methods that require a bound device (such as IO).How about instead something like
mod device {
unsafe trait Container<Ctx: DeviceContext>: AsRef<Device<Ctx>> { const Offset: usize;unsafe fn from_device(dev: &Device<Ctx>) -> &Self { <implementation here> }}
unsafe impl Device<Ctx> for Container<Ctx> { const Offset: usize = 0; }}
And instead of passing &Device<Bound> to the functions, we should add a type parameter to LedOps, e.g.:
trait LedOps<T: device::Container<device::Bound>> {
...
fn brightness_set(&self, dev: &T, brightness: u32) -> Result<()>;...
}
impl<T: LedOps<E>, E: device::Container<device::Bound>> Device<T> {
pub fn new<'a>( parent: &'a E, init_data: InitData<'a>, ops: T, ) -> impl PinInit<Devres<Self>, Error> + 'a { ... }...
}
In the example of i2c (or any other container for
struct device), we implement thedevice::Containertrait:mod i2c {
unsafe impl device::Container for I2cClient { const Offset: usize = offset_of!(bindings::i2c_client, dev); }
Quoted 5 lines
}
This allows the LedOps function to use any functions from the I2cClient or any other device container which may be used (removing the need to store it inside the LedOps implementations struct). It still allows Device<Bound> to be used, as it also would implementdevice::Container.
I had a similar idea in the past, but it has some disadvantages:
(1) You have to implement the upcast from a generic device to a bus device for every bus device.
(2) You have to store a Box<dyn T> in the Rust LED class device; the C struct device can't carry the fat pointer.
The alternative would be to provide a safe method for bus devices to upgrade to a bound device by presenting its corresponding &Device<Bound> base device, for instance:
impl I2cClient {
pub fn into_bound<'a>(&'a self, &'a Device<Bound>) -> Result<&'a I2cClient<Bound>> {
// Fails if the presented `&Device<Bound` is not the base device of `self`.
...
}
}The advantage is that this can easily be implemented with a macro for all bus devices.
There is a slight downside in ergonomics due to the into_bound() call though:
fn brightness_set(&self, parent: &Device<Bound>, brightness: u32) -> Result {
let i2c: &I2cClient<Bound> = self.i2c.into_bound(parent)?;
...
}Re: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
Quoted 120 lines · Danilo Krummrich
Quoted 110 lines · Markus Probst
Quoted 45 lines · Alice RyhlV
Quoted 44 lines · Markus Probst
Implement the core abstractions needed for led class devices, including:
*
led::LedOps- the trait for handling leds, includingbrightness_set,brightness_getandblink_set*
led::InitData- data set for the led class device*
led::Device- a safe wrapper aroundled_classdevSigned-off-by Markus Probst <[email protected]>+pub trait LedOps: Send + 'static + Sized { + /// If set true, [
LedOps::brightness_set] and [LedOps::blink_set] must not sleep
+ /// and perform the operation immediately. + const BLOCKING: bool;
+ /// The max brightness level
+ constMAX_BRIGHTNESS: u32;rust/kernel/led.rs new file +14
-0+ + /// Sets the brightness level. + /// + /// See also [`LedOps::BLOCKING`] + fn brightness_set(&self, brightness: u32) -> Result<()>; + + /// Gets the current brightness level. + fn brightness_get(&self) -> u32 { + build_error!(VTABLE_DEFAULT_ERROR) + } + + /// Activates hardware accelerated blinking. + /// + /// delays are in milliseconds. If both are zero, asensible
default should be chosen.
+ /// The caller should adjust the timings in that case and if
it can't match the values
+ /// specified exactly. Setting the brightness to 0 will disable the hardware accelerated
+ /// blinking.
+ ///
+ /// See also [LedOps::BLOCKING]
+ fn blink_set(&self,_delay_on: &mut usize,_delay_off:Quoted 8 lines
Quoted 4 lines
&mut
usize) -> Result<()> {
+ build_error!(VTABLE_DEFAULT_ERROR)
+ }These functions should probably take a &Device<Bound> argument so that
they can use methods that require a bound device (such as IO).How about instead something like
mod device {
unsafe trait Container<Ctx: DeviceContext>: AsRef<Device<Ctx>> { const Offset: usize;
unsafe fn
from_device(dev: &Device<Ctx>)-> &Self { <implementation here>
}
}unsafe impl Device<Ctx> for Container<Ctx> {
const Offset: usize = 0;
}}
And instead of passing &Device<Bound> to the functions, we should add a
type parameter to LedOps, e.g.:trait LedOps<T: device::Container<device::Bound>> {
...
fn
brightness_set(&self, dev: &T, brightness: u32)-> Result<()>;...
}
impl<T: LedOps<E>, E: device::Container<device::Bound>> Device<T> {
pub fn new<'a>(
parent: &'a E,
init_data: InitData<'a>,
ops: T,
) -> impl PinInit<Devres<Self>, Error> + 'a {
...
}...
}
In the example of i2c (or any other container for
struct device), we
implement thedevice::Containertrait:mod i2c {
unsafe impl
device::Containerfor I2cClient {
const Offset: usize = offset_of!(bindings::i2c_client, dev); }Quoted 8 lines
}
This allows the LedOps function to use any functions from the I2cClient
or any other device container which may be used (removing the need to
store it inside the LedOps implementations struct). It still allows Device<Bound> to be used, as it also would implementdevice::Container.
Quoted 5 lines
I had a similar idea in the past, but it has some disadvantages:
(1) You have to implement the upcast from a generic device to a bus device for
every bus device.
Not necessarily every, like I said container::Device itself also would implement device::Container (still allowing &Device<Bound>).
Quoted 4 lines
(2) You have to store a Box<dyn T> in the Rust LED class device; the C struct
device can't carry the fat pointer.
Why carry a fat pointer (assuming you mean pointers to unsized types)? We already know the address of it with the struct led_classdev-
Quoted 1 line
parentfield, we just need to substract the offset from `<T as
Container>::Offset, and we have the address of the device container (like struct i2c_client`). No Box needed.
Thanks
- Markus Probst
Quoted 30 lines
The alternative would be to provide a safe method for bus devices to upgrade to
a bound device by presenting its corresponding &Device<Bound> base device, for
instance:impl I2cClient { pub fn into_bound<'a>(&'a self, &'a Device<Bound>) -> Result<&'a I2cClient<Bound>> { // Fails if the presented `&Device<Bound` is not the base device of `self`. ... } }The advantage is that this can easily be implemented with a macro for all bus
devices.There is a slight downside in ergonomics due to the
into_bound()call though:fn brightness_set(&self, parent: &Device<Bound>, brightness:
u32) -> Result {
let i2c: &I2cClient<Bound> =self.i2c.into_bound(parent)?;... }
Danilo Krummrich
maintainerRe: [PATCH v4 2/2] rust: leds: add basic led classdev abstractions
Quoted 2 lines · Markus Probst
Not necessarily every, like I said
container::Deviceitself also would implementdevice::Container(still allowing &Device<Bound>).
Sure, but eventually we'll need all bus devices to implement it because you want to be able to use this class device on any bus.
Quoted 4 lines
We already know the address of it with the
struct led_classdev-parentfield, we just need to substract the offset from<T as Container>::Offset, and we have the address of the device container (likestruct i2c_client). No Box needed.
Yeah, that should work.
What I still don't like about it (and didn't like back then when I thought about something similar) is that this provides a publicly accessible unsafe way to upcast from a generic device to a bus device.
However, I do see the ergonomic advantage for drivers. Even though I'd say it's minor, it is indeed nice that the class device callbacks can already carry the actual parent bus device.
So, I'm fine giving this a shot. If go for an implementation, please name the trait something along the lines of device::IntoBusDevice, device::Container is too generic. Only bus devices have a DeviceContext.
Benno Lossin
reviewerQuoted 10 lines · Markus Probst
This patch series has previously been contained in
https://lore.kernel.org/rust-for-linux/[email protected]/T/#t
which added a rust written led driver for a microcontroller via i2c.As the reading and writing to the i2c client via the register! macro has not been implemented yet [1], the patch series will only contain the additional abstractions required.
[1] https://lore.kernel.org/rust-for-linux/[email protected]/
Quoted 8 lines
The following changes were made:
* add basic Pin<Vec<T, A>> abstractions, that allow to initialize PinInit items with the guarantee that these will never be moved.* add basic led classdev abstractions to register and unregister leds
Changes since v3:
* fixed kunit tests failing because of example in documentation
Please give time for more feedback before sending a new version.
---
Cheers,
Benno