rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v3] rust: alloc: implement Box::pin_slice()
@ 2025-08-11 10:14 Vitaly Wool
  2025-08-20  8:07 ` Vitaly Wool
  2025-08-21 14:47 ` Danilo Krummrich
  0 siblings, 2 replies; 4+ messages in thread
From: Vitaly Wool @ 2025-08-11 10:14 UTC (permalink / raw)
  To: rust-for-linux
  Cc: linux-kernel, Uladzislau Rezki, Danilo Krummrich, Alice Ryhl,
	Vlastimil Babka, Lorenzo Stoakes, Liam R . Howlett, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Bjorn Roy Baron, Benno Lossin,
	Andreas Hindborg, Trevor Gross, Vitaly Wool

From: Alice Ryhl <aliceryhl@google.com>

Add a new constructor to Box to facilitate Box creation from a pinned
slice of elements. This allows to efficiently allocate memory for e.g.
slices of structrures containing spinlocks or mutexes. Such slices may
be used in kmemcache like or zpool API implementations.

Signed-off-by: Alice Ryhl <aliceryhl@google.com>
Signed-off-by: Vitaly Wool <vitaly.wool@konsulko.se>
---
 rust/kernel/alloc/kbox.rs | 72 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 72 insertions(+)

diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
index 1fef9beb57c8..ea9b08e3f8ea 100644
--- a/rust/kernel/alloc/kbox.rs
+++ b/rust/kernel/alloc/kbox.rs
@@ -290,6 +290,78 @@ pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
         Ok(Self::new(x, flags)?.into())
     }
 
+    /// Construct a pinned slice of elements `Pin<Box<[T], A>>`.
+    ///
+    /// This is a convenient means for creation of e.g. slices of structrures containing spinlocks
+    /// or mutexes.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::sync::{new_spinlock, SpinLock};
+    ///
+    /// struct Inner {
+    ///     a: u32,
+    ///     b: u32,
+    /// }
+    /// #[pin_data]
+    /// struct Example {
+    ///     c: u32,
+    ///     #[pin]
+    ///     d: SpinLock<Inner>,
+    /// }
+    ///
+    /// impl Example {
+    ///     fn new() -> impl PinInit<Self, Error> {
+    ///         try_pin_init!(Self {
+    ///             c: 10,
+    ///             d <- new_spinlock!(Inner { a: 20, b: 30 }),
+    ///         })
+    ///     }
+    /// }
+    /// // Allocate a boxed slice of 10 `Example`s.
+    /// let s = KBox::pin_slice(
+    ///     | _i | Example::new(),
+    ///     10,
+    ///     GFP_KERNEL
+    /// )?;
+    /// assert_eq!(s[5].c, 10);
+    /// assert_eq!(s[3].d.lock().a, 20);
+    /// # Ok::<(), Error>(())
+    /// ```
+    pub fn pin_slice<Func, Item, E>(
+        mut init: Func,
+        len: usize,
+        flags: Flags,
+    ) -> Result<Pin<Box<[T], A>>, E>
+    where
+        Func: FnMut(usize) -> Item,
+        Item: PinInit<T, E>,
+        E: From<AllocError>,
+    {
+        let mut buffer = super::Vec::<T, A>::with_capacity(len, flags)?;
+        for i in 0..len {
+            let ptr = buffer.spare_capacity_mut().as_mut_ptr().cast();
+            // SAFETY:
+            // - `ptr` is a valid pointer to uninitialized memory.
+            // - `ptr` is not used if an error is returned.
+            // - `ptr` won't be moved until it is dropped, i.e. it is pinned.
+            unsafe { init(i).__pinned_init(ptr)? };
+
+            // SAFETY:
+            // - `i + 1 <= len`, hence we don't exceed the capacity, due to the call to
+            // `with_capacity()` above
+            // - the new value at index buffer.len() + 1 is the only element being added here, and
+            // it has been initialized above by `init(i).__pinned_init(ptr)`
+            unsafe { buffer.inc_len(1) };
+        }
+        let (ptr, _, _) = buffer.into_raw_parts();
+        let slice = core::ptr::slice_from_raw_parts_mut(ptr, len);
+        // SAFETY: `slice` points to an allocation allocated with `A` (`buffer`) and holds a valid
+        // `[T]`
+        Ok(Pin::from(unsafe { Box::from_raw(slice) }))
+    }
+
     /// Convert a [`Box<T,A>`] to a [`Pin<Box<T,A>>`]. If `T` does not implement
     /// [`Unpin`], then `x` will be pinned in memory and can't be moved.
     pub fn into_pin(this: Self) -> Pin<Self> {
-- 
2.39.2


^ permalink raw reply related	[flat|nested] 4+ messages in thread

* Re: [PATCH v3] rust: alloc: implement Box::pin_slice()
  2025-08-11 10:14 [PATCH v3] rust: alloc: implement Box::pin_slice() Vitaly Wool
@ 2025-08-20  8:07 ` Vitaly Wool
  2025-08-20 12:56   ` Danilo Krummrich
  2025-08-21 14:47 ` Danilo Krummrich
  1 sibling, 1 reply; 4+ messages in thread
From: Vitaly Wool @ 2025-08-20  8:07 UTC (permalink / raw)
  To: rust-for-linux, Danilo Krummrich
  Cc: linux-kernel, Uladzislau Rezki, Alice Ryhl, Vlastimil Babka,
	Lorenzo Stoakes, Liam R . Howlett, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, Bjorn Roy Baron, Benno Lossin,
	Andreas Hindborg, Trevor Gross



On 8/11/25 12:14, Vitaly Wool wrote:
> From: Alice Ryhl <aliceryhl@google.com>
> 
> Add a new constructor to Box to facilitate Box creation from a pinned
> slice of elements. This allows to efficiently allocate memory for e.g.
> slices of structrures containing spinlocks or mutexes. Such slices may
> be used in kmemcache like or zpool API implementations.
> 
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Vitaly Wool <vitaly.wool@konsulko.se>

 From what I could see, there were no objections to this one. Danilo, 
would you be up for picking it or is there something missing about it still?

Thanks,
Vitaly

> ---
>   rust/kernel/alloc/kbox.rs | 72 +++++++++++++++++++++++++++++++++++++++
>   1 file changed, 72 insertions(+)
> 
> diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
> index 1fef9beb57c8..ea9b08e3f8ea 100644
> --- a/rust/kernel/alloc/kbox.rs
> +++ b/rust/kernel/alloc/kbox.rs
> @@ -290,6 +290,78 @@ pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
>           Ok(Self::new(x, flags)?.into())
>       }
>   
> +    /// Construct a pinned slice of elements `Pin<Box<[T], A>>`.
> +    ///
> +    /// This is a convenient means for creation of e.g. slices of structrures containing spinlocks
> +    /// or mutexes.
> +    ///
> +    /// # Examples
> +    ///
> +    /// ```
> +    /// use kernel::sync::{new_spinlock, SpinLock};
> +    ///
> +    /// struct Inner {
> +    ///     a: u32,
> +    ///     b: u32,
> +    /// }
> +    /// #[pin_data]
> +    /// struct Example {
> +    ///     c: u32,
> +    ///     #[pin]
> +    ///     d: SpinLock<Inner>,
> +    /// }
> +    ///
> +    /// impl Example {
> +    ///     fn new() -> impl PinInit<Self, Error> {
> +    ///         try_pin_init!(Self {
> +    ///             c: 10,
> +    ///             d <- new_spinlock!(Inner { a: 20, b: 30 }),
> +    ///         })
> +    ///     }
> +    /// }
> +    /// // Allocate a boxed slice of 10 `Example`s.
> +    /// let s = KBox::pin_slice(
> +    ///     | _i | Example::new(),
> +    ///     10,
> +    ///     GFP_KERNEL
> +    /// )?;
> +    /// assert_eq!(s[5].c, 10);
> +    /// assert_eq!(s[3].d.lock().a, 20);
> +    /// # Ok::<(), Error>(())
> +    /// ```
> +    pub fn pin_slice<Func, Item, E>(
> +        mut init: Func,
> +        len: usize,
> +        flags: Flags,
> +    ) -> Result<Pin<Box<[T], A>>, E>
> +    where
> +        Func: FnMut(usize) -> Item,
> +        Item: PinInit<T, E>,
> +        E: From<AllocError>,
> +    {
> +        let mut buffer = super::Vec::<T, A>::with_capacity(len, flags)?;
> +        for i in 0..len {
> +            let ptr = buffer.spare_capacity_mut().as_mut_ptr().cast();
> +            // SAFETY:
> +            // - `ptr` is a valid pointer to uninitialized memory.
> +            // - `ptr` is not used if an error is returned.
> +            // - `ptr` won't be moved until it is dropped, i.e. it is pinned.
> +            unsafe { init(i).__pinned_init(ptr)? };
> +
> +            // SAFETY:
> +            // - `i + 1 <= len`, hence we don't exceed the capacity, due to the call to
> +            // `with_capacity()` above
> +            // - the new value at index buffer.len() + 1 is the only element being added here, and
> +            // it has been initialized above by `init(i).__pinned_init(ptr)`
> +            unsafe { buffer.inc_len(1) };
> +        }
> +        let (ptr, _, _) = buffer.into_raw_parts();
> +        let slice = core::ptr::slice_from_raw_parts_mut(ptr, len);
> +        // SAFETY: `slice` points to an allocation allocated with `A` (`buffer`) and holds a valid
> +        // `[T]`
> +        Ok(Pin::from(unsafe { Box::from_raw(slice) }))
> +    }
> +
>       /// Convert a [`Box<T,A>`] to a [`Pin<Box<T,A>>`]. If `T` does not implement
>       /// [`Unpin`], then `x` will be pinned in memory and can't be moved.
>       pub fn into_pin(this: Self) -> Pin<Self> {


^ permalink raw reply	[flat|nested] 4+ messages in thread

* Re: [PATCH v3] rust: alloc: implement Box::pin_slice()
  2025-08-20  8:07 ` Vitaly Wool
@ 2025-08-20 12:56   ` Danilo Krummrich
  0 siblings, 0 replies; 4+ messages in thread
From: Danilo Krummrich @ 2025-08-20 12:56 UTC (permalink / raw)
  To: Vitaly Wool
  Cc: rust-for-linux, linux-kernel, Uladzislau Rezki, Alice Ryhl,
	Vlastimil Babka, Lorenzo Stoakes, Liam R . Howlett, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Bjorn Roy Baron, Benno Lossin,
	Andreas Hindborg, Trevor Gross

On Wed Aug 20, 2025 at 10:07 AM CEST, Vitaly Wool wrote:
> On 8/11/25 12:14, Vitaly Wool wrote:
>> From: Alice Ryhl <aliceryhl@google.com>
>> 
>> Add a new constructor to Box to facilitate Box creation from a pinned
>> slice of elements. This allows to efficiently allocate memory for e.g.
>> slices of structrures containing spinlocks or mutexes. Such slices may
>> be used in kmemcache like or zpool API implementations.
>> 
>> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
>> Signed-off-by: Vitaly Wool <vitaly.wool@konsulko.se>
>
>  From what I could see, there were no objections to this one. Danilo, 
> would you be up for picking it or is there something missing about it still?

This looks good now.

There's a few minor nits, e.g. it'd be nice to have an  empty line between
struct definitions in the example and sentences ending with a period. But I can
fix those up on apply.

^ permalink raw reply	[flat|nested] 4+ messages in thread

* Re: [PATCH v3] rust: alloc: implement Box::pin_slice()
  2025-08-11 10:14 [PATCH v3] rust: alloc: implement Box::pin_slice() Vitaly Wool
  2025-08-20  8:07 ` Vitaly Wool
@ 2025-08-21 14:47 ` Danilo Krummrich
  1 sibling, 0 replies; 4+ messages in thread
From: Danilo Krummrich @ 2025-08-21 14:47 UTC (permalink / raw)
  To: Vitaly Wool
  Cc: rust-for-linux, linux-kernel, Uladzislau Rezki, Alice Ryhl,
	Vlastimil Babka, Lorenzo Stoakes, Liam R . Howlett, Miguel Ojeda,
	Alex Gaynor, Boqun Feng, Gary Guo, Bjorn Roy Baron, Benno Lossin,
	Andreas Hindborg, Trevor Gross

On Mon Aug 11, 2025 at 12:14 PM CEST, Vitaly Wool wrote:
> From: Alice Ryhl <aliceryhl@google.com>
>
> Add a new constructor to Box to facilitate Box creation from a pinned
> slice of elements. This allows to efficiently allocate memory for e.g.
> slices of structrures containing spinlocks or mutexes. Such slices may
> be used in kmemcache like or zpool API implementations.
>
> Signed-off-by: Alice Ryhl <aliceryhl@google.com>
> Signed-off-by: Vitaly Wool <vitaly.wool@konsulko.se>

Applied to alloc-next, thanks!

    [ Add empty lines after struct definitions in the example; end sentences
      with a period. - Danilo ]

^ permalink raw reply	[flat|nested] 4+ messages in thread

end of thread, other threads:[~2025-08-21 14:48 UTC | newest]

Thread overview: 4+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-08-11 10:14 [PATCH v3] rust: alloc: implement Box::pin_slice() Vitaly Wool
2025-08-20  8:07 ` Vitaly Wool
2025-08-20 12:56   ` Danilo Krummrich
2025-08-21 14:47 ` Danilo Krummrich

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).