linux-kernel.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v4 0/2] rust: alloc: kvec doc example and allocator unit tests
@ 2025-07-24  9:25 Hui Zhu
  2025-07-24  9:25 ` [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc Hui Zhu
  2025-07-24  9:25 ` [PATCH v4 2/2] rust: alloc: kvec: add doc example for as_slice method Hui Zhu
  0 siblings, 2 replies; 5+ messages in thread
From: Hui Zhu @ 2025-07-24  9:25 UTC (permalink / raw)
  To: Danilo Krummrich, Lorenzo Stoakes, Vlastimil Babka,
	Liam R . Howlett, Uladzislau Rezki, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, bjorn3_gh, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, rust-for-linux, linux-kernel
  Cc: Hui Zhu

From: Hui Zhu <zhuhui@kylinos.cn>

This series includes two Rust patches:

Patch 1 adds KUnit tests for Rust allocation wrappers (kmalloc, vmalloc,
kvmalloc). It covers basic allocations, large alignments, and checks for
expected failures. Each test verifies content integrity through byte
pattern checks.

Patch 2 improves the documentation for KVec::as_slice() by adding a
code example. This shows how to use the method with push operations and
assertions.

Both patches are co-developed with Geliang Tang. Tested on x86_64 using
KUnit.

Changelog:
v4:
According to the comments of, add the error check for push.
v3:
According to the comments of Danilo and Boqun, move KVec test to doc
example and move VBox to allocator unit tests.
v2:
According to the comments of Danilo, updated the commit to samples the
usage of VBox and KVec.

Hui Zhu (2):
  rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc
  rust: alloc: kvec: add doc example for as_slice method

 rust/kernel/alloc/allocator.rs | 57 ++++++++++++++++++++++++++++++++++
 rust/kernel/alloc/kvec.rs      | 10 ++++++
 2 files changed, 67 insertions(+)

-- 
2.43.0


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

* [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc
  2025-07-24  9:25 [PATCH v4 0/2] rust: alloc: kvec doc example and allocator unit tests Hui Zhu
@ 2025-07-24  9:25 ` Hui Zhu
  2025-07-24 15:59   ` Danilo Krummrich
  2025-07-24  9:25 ` [PATCH v4 2/2] rust: alloc: kvec: add doc example for as_slice method Hui Zhu
  1 sibling, 1 reply; 5+ messages in thread
From: Hui Zhu @ 2025-07-24  9:25 UTC (permalink / raw)
  To: Danilo Krummrich, Lorenzo Stoakes, Vlastimil Babka,
	Liam R . Howlett, Uladzislau Rezki, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, bjorn3_gh, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, rust-for-linux, linux-kernel
  Cc: Hui Zhu, Geliang Tang

From: Hui Zhu <zhuhui@kylinos.cn>

Add KUnit test cases to validate the functionality of Rust allocation
wrappers (kmalloc, vmalloc, kvmalloc).

The tests include:
Basic allocation tests for each allocator using a 1024-byte Blob
structure initialized with a 0xfe pattern.
Large alignment (> PAGE_SIZE) allocation testing using an 8192-byte
aligned LargeAlignBlob structure.
Verification of allocation constraints:
- kmalloc successfully handles large alignments.
- vmalloc and kvmalloc correctly fail for unsupported large alignments.
Content verification through byte-by-byte pattern checking.

Co-developed-by: Geliang Tang <geliang@kernel.org>
Signed-off-by: Geliang Tang <geliang@kernel.org>
Signed-off-by: Hui Zhu <zhuhui@kylinos.cn>
---
 rust/kernel/alloc/allocator.rs | 57 ++++++++++++++++++++++++++++++++++
 1 file changed, 57 insertions(+)

diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
index aa2dfa9dca4c..430d1f664fdf 100644
--- a/rust/kernel/alloc/allocator.rs
+++ b/rust/kernel/alloc/allocator.rs
@@ -187,3 +187,60 @@ unsafe fn realloc(
         unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) }
     }
 }
+
+#[macros::kunit_tests(rust_allocator_kunit)]
+mod tests {
+    use super::*;
+    use kernel::prelude::*;
+
+    const TEST_SIZE: usize = 1024;
+    const LARGE_ALIGN_TEST_SIZE: usize = kernel::page::PAGE_SIZE * 4;
+    #[repr(align(128))]
+    struct Blob([u8; TEST_SIZE]);
+    // This structure is used to test the allocation of alignments larger
+    // than PAGE_SIZE.
+    // Since this is not yet supported, avoid accessing the contents of
+    // the structure for now.
+    #[allow(dead_code)]
+    #[repr(align(8192))]
+    struct LargeAlignBlob([u8; LARGE_ALIGN_TEST_SIZE]);
+
+    #[test]
+    fn test_kmalloc() -> Result<(), AllocError> {
+        let blob = KBox::new(Blob([0xfeu8; TEST_SIZE]), GFP_KERNEL)?;
+        for b in blob.0.as_slice().iter() {
+            assert_eq!(*b, 0xfeu8);
+        }
+
+        let blob = KBox::new(LargeAlignBlob([0xfdu8; LARGE_ALIGN_TEST_SIZE]), GFP_KERNEL)?;
+        for b in blob.0.as_slice().iter() {
+            assert_eq!(*b, 0xfdu8);
+        }
+
+        Ok(())
+    }
+
+    #[test]
+    fn test_vmalloc() -> Result<(), AllocError> {
+        let blob = VBox::new(Blob([0xfeu8; TEST_SIZE]), GFP_KERNEL)?;
+        for b in blob.0.as_slice().iter() {
+            assert_eq!(*b, 0xfeu8);
+        }
+
+        assert!(VBox::<LargeAlignBlob>::new_uninit(GFP_KERNEL).is_err());
+
+        Ok(())
+    }
+
+    #[test]
+    fn test_kvmalloc() -> Result<(), AllocError> {
+        let blob = KVBox::new(Blob([0xfeu8; TEST_SIZE]), GFP_KERNEL)?;
+        for b in blob.0.as_slice().iter() {
+            assert_eq!(*b, 0xfeu8);
+        }
+
+        assert!(KVBox::<LargeAlignBlob>::new_uninit(GFP_KERNEL).is_err());
+
+        Ok(())
+    }
+}
-- 
2.43.0


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

* [PATCH v4 2/2] rust: alloc: kvec: add doc example for as_slice method
  2025-07-24  9:25 [PATCH v4 0/2] rust: alloc: kvec doc example and allocator unit tests Hui Zhu
  2025-07-24  9:25 ` [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc Hui Zhu
@ 2025-07-24  9:25 ` Hui Zhu
  1 sibling, 0 replies; 5+ messages in thread
From: Hui Zhu @ 2025-07-24  9:25 UTC (permalink / raw)
  To: Danilo Krummrich, Lorenzo Stoakes, Vlastimil Babka,
	Liam R . Howlett, Uladzislau Rezki, Miguel Ojeda, Alex Gaynor,
	Boqun Feng, Gary Guo, bjorn3_gh, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, rust-for-linux, linux-kernel
  Cc: Hui Zhu, Geliang Tang

From: Hui Zhu <zhuhui@kylinos.cn>

Add a practical usage example to the documentation of KVec::as_slice()
showing how to:
Create a new KVec.
Push elements into it.
Convert to a slice via as_slice().

Co-developed-by: Geliang Tang <geliang@kernel.org>
Signed-off-by: Geliang Tang <geliang@kernel.org>
Signed-off-by: Hui Zhu <zhuhui@kylinos.cn>
---
 rust/kernel/alloc/kvec.rs | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index 3c72e0bdddb8..fa04cc0987d6 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -224,6 +224,16 @@ unsafe fn dec_len(&mut self, count: usize) -> &mut [T] {
     }
 
     /// Returns a slice of the entire vector.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// let mut v = KVec::new();
+    /// v.push(1, GFP_KERNEL)?;
+    /// v.push(2, GFP_KERNEL)?;
+    /// assert_eq!(v.as_slice(), &[1, 2]);
+    /// # Ok::<(), Error>(())
+    /// ```
     #[inline]
     pub fn as_slice(&self) -> &[T] {
         self
-- 
2.43.0


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

* Re: [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc
  2025-07-24  9:25 ` [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc Hui Zhu
@ 2025-07-24 15:59   ` Danilo Krummrich
  2025-07-25  7:05     ` Hui Zhu
  0 siblings, 1 reply; 5+ messages in thread
From: Danilo Krummrich @ 2025-07-24 15:59 UTC (permalink / raw)
  To: Hui Zhu
  Cc: Lorenzo Stoakes, Vlastimil Babka, Liam R . Howlett,
	Uladzislau Rezki, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, rust-for-linux, linux-kernel, Hui Zhu, Geliang Tang

On Thu Jul 24, 2025 at 11:25 AM CEST, Hui Zhu wrote:
> From: Hui Zhu <zhuhui@kylinos.cn>
>
> Add KUnit test cases to validate the functionality of Rust allocation
> wrappers (kmalloc, vmalloc, kvmalloc).
>
> The tests include:
> Basic allocation tests for each allocator using a 1024-byte Blob
> structure initialized with a 0xfe pattern.
> Large alignment (> PAGE_SIZE) allocation testing using an 8192-byte
> aligned LargeAlignBlob structure.
> Verification of allocation constraints:
> - kmalloc successfully handles large alignments.
> - vmalloc and kvmalloc correctly fail for unsupported large alignments.
> Content verification through byte-by-byte pattern checking.
>
> Co-developed-by: Geliang Tang <geliang@kernel.org>
> Signed-off-by: Geliang Tang <geliang@kernel.org>
> Signed-off-by: Hui Zhu <zhuhui@kylinos.cn>

Thanks for the patch, additional test are always welcome! :)

> ---
>  rust/kernel/alloc/allocator.rs | 57 ++++++++++++++++++++++++++++++++++
>  1 file changed, 57 insertions(+)
>
> diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
> index aa2dfa9dca4c..430d1f664fdf 100644
> --- a/rust/kernel/alloc/allocator.rs
> +++ b/rust/kernel/alloc/allocator.rs
> @@ -187,3 +187,60 @@ unsafe fn realloc(
>          unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) }
>      }
>  }
> +
> +#[macros::kunit_tests(rust_allocator_kunit)]
> +mod tests {
> +    use super::*;
> +    use kernel::prelude::*;
> +
> +    const TEST_SIZE: usize = 1024;
> +    const LARGE_ALIGN_TEST_SIZE: usize = kernel::page::PAGE_SIZE * 4;
> +    #[repr(align(128))]
> +    struct Blob([u8; TEST_SIZE]);
> +    // This structure is used to test the allocation of alignments larger
> +    // than PAGE_SIZE.
> +    // Since this is not yet supported, avoid accessing the contents of
> +    // the structure for now.
> +    #[allow(dead_code)]
> +    #[repr(align(8192))]
> +    struct LargeAlignBlob([u8; LARGE_ALIGN_TEST_SIZE]);
> +
> +    #[test]
> +    fn test_kmalloc() -> Result<(), AllocError> {
> +        let blob = KBox::new(Blob([0xfeu8; TEST_SIZE]), GFP_KERNEL)?;

Since those are now actual unit tests on the Allocator implementations, it would
be fine to use them directly. However, for the case you are testing here, i.e.
alignment using Box is perfectly fine.

Having that said, I wouldn't call those tests test_*malloc(), since they're not
really testing all aspects of a certain allocator, but only the success to
allocate with certain alignment arguments.

Instead, I propose to write just a single test, test_alignment(), with a few
helper functions.

For instance, your Blob test structure could have a constructor that is generic
over A: Allocator.

However, given that you really only want to check alignment, you probably want a
structure like this instead.

	struct TestAlign<A: Allocator>(Box<MaybeUninit<[u8; TEST_SIZE]>, A>);

	impl<A: Allocator> TestAlign<A> {
	   fn new() -> Result<Self> {
	      Box::<_, A>::new_uninit(GFP_KERNEL)
	   }

	   fn alignment_valid(&self) -> bool {
	      ...
	   }
	}

and then test_alignment() can just do

	let test = TestAlign::<Kmalloc>::new()?;
	assert!(test.alignment_valid());

	...

Given that this is now a unit test I also think that actually validating the
alignment of the pointer Box wraps makes sense, similar to what you had in v2.

> +        for b in blob.0.as_slice().iter() {
> +            assert_eq!(*b, 0xfeu8);
> +        }

I don't think that this has any valid in the context of testing alignment.

> +        let blob = KBox::new(LargeAlignBlob([0xfdu8; LARGE_ALIGN_TEST_SIZE]), GFP_KERNEL)?;

For the large alignment case, you can consider to let TestAlign take a const
generic, additional to A: Allocator, e.g.

	struct TestAlign<A: Allocator, const SIZE: usize>(Box<MaybeUninit<[u8; SIZE]>, A>);

This way you can keep test_alignment() function very compact.

- Danilo

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

* Re: [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc
  2025-07-24 15:59   ` Danilo Krummrich
@ 2025-07-25  7:05     ` Hui Zhu
  0 siblings, 0 replies; 5+ messages in thread
From: Hui Zhu @ 2025-07-25  7:05 UTC (permalink / raw)
  To: Danilo Krummrich
  Cc: Lorenzo Stoakes, Vlastimil Babka, Liam R . Howlett,
	Uladzislau Rezki, Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	bjorn3_gh, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, rust-for-linux, linux-kernel, Hui Zhu, Geliang Tang

Hi Danilo,

On Thu, Jul 24, 2025 at 05:59:39PM +0200, Danilo Krummrich wrote:
> On Thu Jul 24, 2025 at 11:25 AM CEST, Hui Zhu wrote:
> > From: Hui Zhu <zhuhui@kylinos.cn>
> >
> > Add KUnit test cases to validate the functionality of Rust allocation
> > wrappers (kmalloc, vmalloc, kvmalloc).
> >
> > The tests include:
> > Basic allocation tests for each allocator using a 1024-byte Blob
> > structure initialized with a 0xfe pattern.
> > Large alignment (> PAGE_SIZE) allocation testing using an 8192-byte
> > aligned LargeAlignBlob structure.
> > Verification of allocation constraints:
> > - kmalloc successfully handles large alignments.
> > - vmalloc and kvmalloc correctly fail for unsupported large alignments.
> > Content verification through byte-by-byte pattern checking.
> >
> > Co-developed-by: Geliang Tang <geliang@kernel.org>
> > Signed-off-by: Geliang Tang <geliang@kernel.org>
> > Signed-off-by: Hui Zhu <zhuhui@kylinos.cn>
> 
> Thanks for the patch, additional test are always welcome! :)

Great!

> 
> > ---
> >  rust/kernel/alloc/allocator.rs | 57 ++++++++++++++++++++++++++++++++++
> >  1 file changed, 57 insertions(+)
> >
> > diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
> > index aa2dfa9dca4c..430d1f664fdf 100644
> > --- a/rust/kernel/alloc/allocator.rs
> > +++ b/rust/kernel/alloc/allocator.rs
> > @@ -187,3 +187,60 @@ unsafe fn realloc(
> >          unsafe { ReallocFunc::KVREALLOC.call(ptr, layout, old_layout, flags) }
> >      }
> >  }
> > +
> > +#[macros::kunit_tests(rust_allocator_kunit)]
> > +mod tests {
> > +    use super::*;
> > +    use kernel::prelude::*;
> > +
> > +    const TEST_SIZE: usize = 1024;
> > +    const LARGE_ALIGN_TEST_SIZE: usize = kernel::page::PAGE_SIZE * 4;
> > +    #[repr(align(128))]
> > +    struct Blob([u8; TEST_SIZE]);
> > +    // This structure is used to test the allocation of alignments larger
> > +    // than PAGE_SIZE.
> > +    // Since this is not yet supported, avoid accessing the contents of
> > +    // the structure for now.
> > +    #[allow(dead_code)]
> > +    #[repr(align(8192))]
> > +    struct LargeAlignBlob([u8; LARGE_ALIGN_TEST_SIZE]);
> > +
> > +    #[test]
> > +    fn test_kmalloc() -> Result<(), AllocError> {
> > +        let blob = KBox::new(Blob([0xfeu8; TEST_SIZE]), GFP_KERNEL)?;
> 
> Since those are now actual unit tests on the Allocator implementations, it would
> be fine to use them directly. However, for the case you are testing here, i.e.
> alignment using Box is perfectly fine.
> 
> Having that said, I wouldn't call those tests test_*malloc(), since they're not
> really testing all aspects of a certain allocator, but only the success to
> allocate with certain alignment arguments.
> 
> Instead, I propose to write just a single test, test_alignment(), with a few
> helper functions.
> 
> For instance, your Blob test structure could have a constructor that is generic
> over A: Allocator.
> 
> However, given that you really only want to check alignment, you probably want a
> structure like this instead.
> 
> 	struct TestAlign<A: Allocator>(Box<MaybeUninit<[u8; TEST_SIZE]>, A>);
> 
> 	impl<A: Allocator> TestAlign<A> {
> 	   fn new() -> Result<Self> {
> 	      Box::<_, A>::new_uninit(GFP_KERNEL)
> 	   }
> 
> 	   fn alignment_valid(&self) -> bool {
> 	      ...
> 	   }
> 	}
> 
> and then test_alignment() can just do
> 
> 	let test = TestAlign::<Kmalloc>::new()?;
> 	assert!(test.alignment_valid());
> 
> 	...
> 
> Given that this is now a unit test I also think that actually validating the
> alignment of the pointer Box wraps makes sense, similar to what you had in v2.
> 
> > +        for b in blob.0.as_slice().iter() {
> > +            assert_eq!(*b, 0xfeu8);
> > +        }
> 
> I don't think that this has any valid in the context of testing alignment.
> 
> > +        let blob = KBox::new(LargeAlignBlob([0xfdu8; LARGE_ALIGN_TEST_SIZE]), GFP_KERNEL)?;
> 
> For the large alignment case, you can consider to let TestAlign take a const
> generic, additional to A: Allocator, e.g.
> 
> 	struct TestAlign<A: Allocator, const SIZE: usize>(Box<MaybeUninit<[u8; SIZE]>, A>);
> 
> This way you can keep test_alignment() function very compact.
>

I sent new patches according to your comments.
 
> - Danilo

Best,
Hui

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

end of thread, other threads:[~2025-07-25  7:05 UTC | newest]

Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-07-24  9:25 [PATCH v4 0/2] rust: alloc: kvec doc example and allocator unit tests Hui Zhu
2025-07-24  9:25 ` [PATCH v4 1/2] rust: allocator: add unit tests of kmalloc, vmalloc and kvmalloc Hui Zhu
2025-07-24 15:59   ` Danilo Krummrich
2025-07-25  7:05     ` Hui Zhu
2025-07-24  9:25 ` [PATCH v4 2/2] rust: alloc: kvec: add doc example for as_slice method Hui Zhu

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).