Take ARCH_KMALLOC_MINALIGN into account for build-time XArray check
Subsystems (4)
Alice Ryhl
maintainercover 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]>
Alice Ryhl
maintainerPATCH 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
@@ -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
@@ -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
Alice Ryhl
maintainerPATCH 2/2 rust: alloc: take the allocator into account for FOREIGN_ALIGN
In reply to Alice RyhlWhen 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
@@ -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> = &'aT ;type BorrowedMut <'a> = &'amut 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 <&'aT >;type BorrowedMut <'a> =Pin <&'amut T >;
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 ;type Borrowed <'a> =ArcBorrow <'a,T >;type BorrowedMut <'a> =Self ::Borrowed <'a>;
Signature · 1 line
2.50.0.727.gbf7dc18ff4-goog
Danilo Krummrich
maintainerRe: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator
In reply to Alice RyhlQuoted 5 lines · Alice Ryhl
rust/kernel/alloc.rs +0
-0
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@@ -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>>,
Danilo Krummrich
maintainerRe: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN
In reply to Alice RyhlQuoted 12 lines · Alice Ryhl
rust/kernel/alloc/kbox.rs +1
-1@@ -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
-1A: 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.
Alice Ryhl
maintainerRe: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator
In reply to Danilo KrummrichQuoted 11 lines · Danilo Krummrich
Quoted 9 lines · Alice Ryhl
rust/kernel/alloc.rs +1
-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.
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
Danilo Krummrich
maintainerRe: [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@@ -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. :)
Re: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN
In reply to Alice RyhlQuoted 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_ALIGNis at least 4. This means that you can now always use a Box<T> with the XArray no matter the alignment of T.Signed-off-by Alice Ryhl <[email protected]>
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
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
-0type Borrowed <'a> =ArcBorrow <'a,T >;type BorrowedMut <'a> =Self ::Borrowed <'a>;
Re: [PATCH 1/2] rust: alloc: specify the minimum alignment of each allocator
In reply to Alice RyhlQuoted 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_ALIGNwhen 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.Signed-off-by Alice Ryhl <[email protected]>
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(+)
Danilo Krummrich
maintainerRe: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN
In reply to Benno LossinQuoted 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.
Alice Ryhl
maintainerRe: [PATCH 2/2] rust: alloc: take the allocator into account for FOREIGN_ALIGN
In reply to Danilo KrummrichQuoted 29 lines · Danilo Krummrich
Quoted 12 lines · Alice Ryhl
rust/kernel/alloc/kbox.rs +1
-1@@ -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
-1A: 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