Skip to contentSkip to conversation

Take ARCH_KMALLOC_MINALIGN into account for build-time XArray check

PATCH Superseded Alice Ryhl 3 participants 11 messages Jul 15, 2025 – Jul 16, 2025

Subsystems (4)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

cover Take ARCH_KMALLOC_MINALIGN into account for build-time XArray check

The Rust bindings for XArray include a build-time check to ensure that you can only use the XArray with pointers that are 4-byte aligned. Because of that, there is currently a build failure if you attempt to create an XArray<KBox<T>> where T is a 1-byte or 2-byte aligned type. However, this error is incorrect as KBox<_> is guaranteed to be a pointer that comes from kmalloc, and kmalloc always produces pointers that are at least 4-byte aligned.

To fix this, we augment the compile-time logic that computes the alignment of KBox<_> to take the minimum alignment of its allocator into account.

This series is based on top of rust-next.

---
Alice Ryhl (2):
rust: alloc: specify the minimum alignment of each allocator
rust: alloc: take the allocator into account for FOREIGN_ALIGN

 rust/kernel/alloc.rs           |  8 ++++++++
 rust/kernel/alloc/allocator.rs |  8 ++++++++
 rust/kernel/alloc/kbox.rs      | 15 +++++++++++----
 rust/kernel/sync/arc.rs        |  6 +++---
 4 files changed, 30 insertions(+), 7 deletions(-)

---
base-commit: a68a6bef0e75fb9e5aea1399d8538f4e3584dab1
change-id: 20250715-align-min-allocator-b31aee53cbda

Best regards,

Signature · 1 line
Alice Ryhl <[email protected]>
author maintainer
#1 lore raw

PATCH 1/2 rust: alloc: specify the minimum alignment of each allocator

The kernel's allocators sometimes provide a higher alignment than the end-user requested, so add a new constant on the Allocator trait to let the allocator specify what its minimum guaranteed alignment is.

This allows the ForeignOwnable trait to provide a more accurate value of FOREIGN_ALIGN when using a pointer type such as Box, which will be useful with certain collections such as XArray that store its own data in the low bits of pointers.

---
 rust/kernel/alloc.rs           | 8 ++++++++
 rust/kernel/alloc/allocator.rs | 8 ++++++++
 2 files changed, 16 insertions(+)
rust/kernel/alloc.rs +8 -0
index a2c49e5494d334bfde67328464dafcdb31052947..c12753a5fb1c7423a4063553674b537a775c860e 100644
@@ -137,6 +137,14 @@ pub mod flags {
 /// - Implementers must ensure that all trait functions abide by the guarantees documented in the
 ///   `# Guarantees` sections.
 pub unsafe trait Allocator {
+    /// The minimum alignment satisfied by all allocations from this allocator.
+    ///
+    /// # Guarantees
+    ///
+    /// Any pointer allocated by this allocator must be aligned to `MIN_ALIGN` even if the
+    /// requested layout has a smaller alignment.
+    const MIN_ALIGN: usize;
+
     /// Allocate memory based on `layout` and `flags`.
     ///
     /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout
rust/kernel/alloc/allocator.rs +8 -0
index aa2dfa9dca4c309e5a9eafc7da6a8a9bd7b54b11..25fc9f9ae3b4e471a08d77130b374bd1397f7384 100644
@@ -17,6 +17,8 @@
 use crate::bindings;
 use crate::pr_warn;
 
+const ARCH_KMALLOC_MINALIGN: usize = bindings::ARCH_KMALLOC_MINALIGN as usize;
+
 /// The contiguous kernel allocator.
 ///
 /// `Kmalloc` is typically used for physically contiguous allocations up to page size, but also
@@ -128,6 +130,8 @@ unsafe fn call(
 // - passing a pointer to a valid memory allocation is OK,
 // - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
 unsafe impl Allocator for Kmalloc {
+    const MIN_ALIGN: usize = ARCH_KMALLOC_MINALIGN;
+
     #[inline]
     unsafe fn realloc(
         ptr: Option<NonNull<u8>>,
@@ -145,6 +149,8 @@ unsafe fn realloc(
 // - passing a pointer to a valid memory allocation is OK,
 // - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
 unsafe impl Allocator for Vmalloc {
+    const MIN_ALIGN: usize = kernel::page::PAGE_SIZE;
+
     #[inline]
     unsafe fn realloc(
         ptr: Option<NonNull<u8>>,
@@ -169,6 +175,8 @@ unsafe fn realloc(
 // - passing a pointer to a valid memory allocation is OK,
 // - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
 unsafe impl Allocator for KVmalloc {
+    const MIN_ALIGN: usize = ARCH_KMALLOC_MINALIGN;
+
     #[inline]
     unsafe fn realloc(
         ptr: Option<NonNull<u8>>,
Signature · 1 line
2.50.0.727.gbf7dc18ff4-goog
maintainer
#2 lore raw

Re: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator

Quoted 5 lines · Alice Ryhl
rust/kernel/alloc.rs +0 -0
index a2c49e5494d334bfde67328464dafcdb31052947..c12753a5fb1c7423a4063553674b537a775c860e 100644

rust/kernel/alloc.rs pub mod flags { · line 145

Quoted 9 lines
rust/kernel/alloc.rs +6 -0
@@ -137,6 +137,14 @@ pub mod flags {
 /// - Implementers must ensure that all trait functions abide by the guarantees documented in the
 ///   `# Guarantees` sections.
 pub unsafe trait Allocator {
+    /// The minimum alignment satisfied by all allocations from this allocator.
+    ///
+    /// # Guarantees
+    ///
+    /// Any pointer allocated by this allocator must be aligned to `MIN_ALIGN` even if the
+    /// requested layout has a smaller alignment.

I'd say "is guaranteed to be aligned to" instead, "must be" reads like a requirement.

Speaking of which, I think this also needs to be expressed as a safety requirement of the Allocator trait itself, which the specific allocator implementations need to justify.

Quoted 45 lines
rust/kernel/alloc.rs +2 -0
+    const MIN_ALIGN: usize;
+
     /// Allocate memory based on `layout` and `flags`.
     ///
     /// On success, returns a buffer represented as `NonNull<[u8]>` that satisfies the layout
rust/kernel/alloc/allocator.rs +8 -0
index aa2dfa9dca4c309e5a9eafc7da6a8a9bd7b54b11..25fc9f9ae3b4e471a08d77130b374bd1397f7384 100644
@@ -17,6 +17,8 @@
 use crate::bindings;
 use crate::pr_warn;
 
+const ARCH_KMALLOC_MINALIGN: usize = bindings::ARCH_KMALLOC_MINALIGN as usize;
+
 /// The contiguous kernel allocator.
 ///
 /// `Kmalloc` is typically used for physically contiguous allocations up to page size, but also
@@ -128,6 +130,8 @@ unsafe fn call(
 // - passing a pointer to a valid memory allocation is OK,
 // - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
 unsafe impl Allocator for Kmalloc {
+    const MIN_ALIGN: usize = ARCH_KMALLOC_MINALIGN;
+
     #[inline]
     unsafe fn realloc(
         ptr: Option<NonNull<u8>>,
@@ -145,6 +149,8 @@ unsafe fn realloc(
 // - passing a pointer to a valid memory allocation is OK,
 // - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
 unsafe impl Allocator for Vmalloc {
+    const MIN_ALIGN: usize = kernel::page::PAGE_SIZE;
+
     #[inline]
     unsafe fn realloc(
         ptr: Option<NonNull<u8>>,
@@ -169,6 +175,8 @@ unsafe fn realloc(
 // - passing a pointer to a valid memory allocation is OK,
 // - `realloc` satisfies the guarantees, since `ReallocFunc::call` has the same.
 unsafe impl Allocator for KVmalloc {
+    const MIN_ALIGN: usize = ARCH_KMALLOC_MINALIGN;
+
     #[inline]
     unsafe fn realloc(
         ptr: Option<NonNull<u8>>,
author maintainer
#3 lore raw

Re: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator

Quoted 11 lines · Danilo Krummrich
Quoted 9 lines · Alice Ryhl
rust/kernel/alloc.rs +1 -0
index a2c49e5494d334bfde67328464dafcdb31052947..c12753a5fb1c7423a4063553674b537a775c860e 100644
@@ -137,6 +137,14 @@ pub mod flags {
 /// - Implementers must ensure that all trait functions abide by the guarantees documented in the
 ///   `# Guarantees` sections.
 pub unsafe trait Allocator {
+    /// The minimum alignment satisfied by all allocations from this allocator.
Quoted 8 lines

rust/kernel/alloc.rs pub mod flags { · line 145

Quoted 5 lines
rust/kernel/alloc.rs +5 -0
+    ///
+    /// # Guarantees
+    ///
+    /// Any pointer allocated by this allocator must be aligned to `MIN_ALIGN` even if the
+    /// requested layout has a smaller alignment.

I'd say "is guaranteed to be aligned to" instead, "must be" reads like a requirement.

Yes I agree that sounds better.

Quoted 3 lines

Speaking of which, I think this also needs to be expressed as a safety requirement of the Allocator trait itself, which the specific allocator implementations need to justify.

The trait safety requirements already says that the implementation must provide the guarantee listed on each item in the trait.

Alice

maintainer
#4 lore raw

Re: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator

Quoted 21 lines · Alice Ryhl
Quoted 11 lines · Danilo Krummrich
Quoted 9 lines · Alice Ryhl
rust/kernel/alloc.rs +1 -0
index a2c49e5494d334bfde67328464dafcdb31052947..c12753a5fb1c7423a4063553674b537a775c860e 100644
@@ -137,6 +137,14 @@ pub mod flags {
 /// - Implementers must ensure that all trait functions abide by the guarantees documented in the
 ///   `# Guarantees` sections.
 pub unsafe trait Allocator {
+    /// The minimum alignment satisfied by all allocations from this allocator.
Quoted 8 lines

rust/kernel/alloc.rs pub mod flags { · line 145

Quoted 5 lines
rust/kernel/alloc.rs +5 -0
+    ///
+    /// # Guarantees
+    ///
+    /// Any pointer allocated by this allocator must be aligned to `MIN_ALIGN` even if the
+    /// requested layout has a smaller alignment.

I'd say "is guaranteed to be aligned to" instead, "must be" reads like a requirement.

Quoted 8 lines

Yes I agree that sounds better.

Quoted 3 lines

Speaking of which, I think this also needs to be expressed as a safety requirement of the Allocator trait itself, which the specific allocator implementations need to justify.

The trait safety requirements already says that the implementation must provide the guarantee listed on each item in the trait.

Oh, indeed, that's fine then. :)

reviewer Reviewed-by on v1 1/2
#5 lore raw

Re: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator

In reply to Alice Ryhl
Quoted 10 lines · Alice Ryhl

The kernel's allocators sometimes provide a higher alignment than the end-user requested, so add a new constant on the Allocator trait to let the allocator specify what its minimum guaranteed alignment is.

This allows the ForeignOwnable trait to provide a more accurate value of FOREIGN_ALIGN when using a pointer type such as Box, which will be useful with certain collections such as XArray that store its own data in the low bits of pointers.

With the wording changed according to Danilo's suggestion:

---
Cheers,
Benno

Quoted 4 lines
---
 rust/kernel/alloc.rs           | 8 ++++++++
 rust/kernel/alloc/allocator.rs | 8 ++++++++
 2 files changed, 16 insertions(+)
author maintainer
#6 lore raw

PATCH 2/2 rust: alloc: take the allocator into account for FOREIGN_ALIGN

In reply to Alice Ryhl

When converting a Box<T> into a void pointer, the allocator might guarantee a higher alignment than the type itself does, and in that case it is guaranteed that the void pointer has that higher alignment.

This is quite useful when combined with the XArray, which you can only create using a ForeignOwnable whose FOREIGN_ALIGN is at least 4. This means that you can now always use a Box<T> with the XArray no matter the alignment of T.

---
 rust/kernel/alloc/kbox.rs | 15 +++++++++++----
 rust/kernel/sync/arc.rs   |  6 +++---
 2 files changed, 14 insertions(+), 7 deletions(-)
rust/kernel/alloc/kbox.rs +11 -4
index bffe72f44cb33a265018e67d92d9f0abe82f8e22..fd3f1e0b9c3b3437fb50d8f1b28c92bc7cefd565 100644
@@ -400,12 +400,19 @@ fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
 }
 
 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
-// pointer to `T`.
+// pointer to `T` allocated by `A`.
 unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
 where
     A: Allocator,
 {
-    const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+    const FOREIGN_ALIGN: usize = {
+        let mut align = core::mem::align_of::<T>();
+        if align < A::MIN_ALIGN {
+            align = A::MIN_ALIGN;
+        }
+        align
+    };
+
     type Borrowed<'a> = &'a T;
     type BorrowedMut<'a> = &'a mut T;
 
@@ -434,12 +441,12 @@ unsafe fn borrow_mut<'a>(ptr: *mut c_void) -> &'a mut T {
 }
 
 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
-// pointer to `T`.
+// pointer to `T` allocated by `A`.
 unsafe impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
 where
     A: Allocator,
 {
-    const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+    const FOREIGN_ALIGN: usize = <Box<T, A> as ForeignOwnable>::FOREIGN_ALIGN;
     type Borrowed<'a> = Pin<&'a T>;
     type BorrowedMut<'a> = Pin<&'a mut T>;
 
rust/kernel/sync/arc.rs +3 -3
index 63a66761d0c7d752e09ce7372bc230661b2f7c6d..74121cf935f364c16799b5c31cc88714dfd6b702 100644
@@ -373,10 +373,10 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
     }
 }
 
-// SAFETY: The pointer returned by `into_foreign` comes from a well aligned
-// pointer to `ArcInner<T>`.
+// SAFETY: The pointer returned by `into_foreign` was originally allocated as an
+// `KBox<ArcInner<T>>`, so that type is what determines the alignment.
 unsafe impl<T: 'static> ForeignOwnable for Arc<T> {
-    const FOREIGN_ALIGN: usize = core::mem::align_of::<ArcInner<T>>();
+    const FOREIGN_ALIGN: usize = <KBox<ArcInner<T>> as ForeignOwnable>::FOREIGN_ALIGN;
 
     type Borrowed<'a> = ArcBorrow<'a, T>;
     type BorrowedMut<'a> = Self::Borrowed<'a>;
Signature · 1 line
2.50.0.727.gbf7dc18ff4-goog
maintainer
#7 lore raw

Re: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN

Quoted 12 lines · Alice Ryhl
rust/kernel/alloc/kbox.rs +1 -1
index bffe72f44cb33a265018e67d92d9f0abe82f8e22..fd3f1e0b9c3b3437fb50d8f1b28c92bc7cefd565 100644
@@ -400,12 +400,19 @@ fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
 }
 
 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
-// pointer to `T`.
+// pointer to `T` allocated by `A`.
 unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
 where

rust/kernel/alloc/kbox.rs fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> · line 414

Quoted 10 lines
rust/kernel/alloc/kbox.rs +7 -1
     A: Allocator,
 {
-    const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+    const FOREIGN_ALIGN: usize = {
+        let mut align = core::mem::align_of::<T>();
+        if align < A::MIN_ALIGN {
+            align = A::MIN_ALIGN;
+        }
+        align
+    };

Pretty unfortunate that core::cmp::max() can't be used from const context. :(

What do you think about

	const FOREIGN_ALIGN: usize =
	    if core::mem::align_of::<T>() < A::MIN_ALIGN {
	        A::MIN_ALIGN
	    } else {
	        core::mem::align_of::<T>()
	    };

instead? I think that reads a bit better.

author maintainer
#8 lore raw

Re: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN

Quoted 29 lines · Danilo Krummrich
Quoted 12 lines · Alice Ryhl
rust/kernel/alloc/kbox.rs +1 -1
index bffe72f44cb33a265018e67d92d9f0abe82f8e22..fd3f1e0b9c3b3437fb50d8f1b28c92bc7cefd565 100644
@@ -400,12 +400,19 @@ fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
 }
 
 // SAFETY: The pointer returned by `into_foreign` comes from a well aligned
-// pointer to `T`.
+// pointer to `T` allocated by `A`.
 unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
 where

rust/kernel/alloc/kbox.rs fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> · line 414

Quoted 10 lines
rust/kernel/alloc/kbox.rs +7 -1
     A: Allocator,
 {
-    const FOREIGN_ALIGN: usize = core::mem::align_of::<T>();
+    const FOREIGN_ALIGN: usize = {
+        let mut align = core::mem::align_of::<T>();
+        if align < A::MIN_ALIGN {
+            align = A::MIN_ALIGN;
+        }
+        align
+    };

Pretty unfortunate that core::cmp::max() can't be used from const context. :(

What do you think about

Quoted 8 lines
        const FOREIGN_ALIGN: usize =
            if core::mem::align_of::<T>() < A::MIN_ALIGN {
                A::MIN_ALIGN
            } else {
                core::mem::align_of::<T>()
            };

instead? I think that reads a bit better.

I don't mind doing that instead.

Alice

reviewer Reviewed-by on v1 2/2
#9 lore raw

Re: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN

In reply to Alice Ryhl
Quoted 10 lines · Alice Ryhl

When converting a Box<T> into a void pointer, the allocator might guarantee a higher alignment than the type itself does, and in that case it is guaranteed that the void pointer has that higher alignment.

This is quite useful when combined with the XArray, which you can only create using a ForeignOwnable whose FOREIGN_ALIGN is at least 4. This means that you can now always use a Box<T> with the XArray no matter the alignment of T.

Hey this is cool!

One question below.

Quoted 10 lines
---
 rust/kernel/alloc/kbox.rs | 15 +++++++++++----
 rust/kernel/sync/arc.rs   |  6 +++---
 2 files changed, 14 insertions(+), 7 deletions(-)
rust/kernel/sync/arc.rs +0 -0
index 63a66761d0c7d752e09ce7372bc230661b2f7c6d..74121cf935f364c16799b5c31cc88714dfd6b702 100644

rust/kernel/sync/arc.rs pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> { · line 379

Quoted 10 lines
rust/kernel/sync/arc.rs +3 -3
@@ -373,10 +373,10 @@ pub fn into_unique_or_drop(self) -> Option<Pin<UniqueArc<T>>> {
     }
 }
 
-// SAFETY: The pointer returned by `into_foreign` comes from a well aligned
-// pointer to `ArcInner<T>`.
+// SAFETY: The pointer returned by `into_foreign` was originally allocated as an
+// `KBox<ArcInner<T>>`, so that type is what determines the alignment.
 unsafe impl<T: 'static> ForeignOwnable for Arc<T> {
-    const FOREIGN_ALIGN: usize = core::mem::align_of::<ArcInner<T>>();
+    const FOREIGN_ALIGN: usize = <KBox<ArcInner<T>> as ForeignOwnable>::FOREIGN_ALIGN;

Do we at some point also want to give people the option to use vmalloc for Arc?

---
Cheers,
Benno

Quoted 3 lines
rust/kernel/sync/arc.rs +0 -0
     type Borrowed<'a> = ArcBorrow<'a, T>;
     type BorrowedMut<'a> = Self::Borrowed<'a>;
maintainer
#10 lore raw

Re: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN

Quoted 2 lines · Benno Lossin

Do we at some point also want to give people the option to use vmalloc for Arc?

I'm not sure how useful that is. Typically, larger allocations (e.g. buffers) are members of smaller reference counted objects that manage their lifetime, etc.