[PATCH] rust: mem: add `Align` type

From: Gary Guo

Date: Tue Jun 09 2026 - 08:06:57 EST


From: Gary Guo <gary@xxxxxxxxxxx>

Rust's `repr(align())` only works with integers. Add an `Align` type so it
can also be specified via const generics.

Signed-off-by: Gary Guo <gary@xxxxxxxxxxx>
---
rust/kernel/lib.rs | 1 +
rust/kernel/mem.rs | 59 ++++++++++++++++++++++++++++++++++++++++++++++
2 files changed, 60 insertions(+)
create mode 100644 rust/kernel/mem.rs

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index 9512af7156df..0a12c3011c61 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -92,6 +92,7 @@
pub mod kunit;
pub mod list;
pub mod maple_tree;
+pub mod mem;
pub mod miscdevice;
pub mod mm;
pub mod module_param;
diff --git a/rust/kernel/mem.rs b/rust/kernel/mem.rs
new file mode 100644
index 000000000000..32e2fe547cfd
--- /dev/null
+++ b/rust/kernel/mem.rs
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: GPL-2.0
+
+//! Utilities handling things related to memory layouts.
+
+// TODO: `Alignment` should be moved here as well, Rust moved it upstream in 1.96.
+pub use crate::ptr::Alignment;
+
+/// Trait indicating that [`Align<N>`] is a valid alignment.
+pub trait ValidAlign {
+ #[doc(hidden)]
+ type Repr;
+}
+
+/// Zero-sized type that provides the alignment specified via the generic parameter.
+///
+/// # Examples
+///
+/// ```
+/// # use kernel::mem::Align;
+/// const ALIGN: usize = 128;
+/// struct MyStruct {
+/// align: Align<ALIGN>,
+/// }
+/// assert_eq!(align_of::<MyStruct>(), ALIGN);
+/// ```
+#[repr(transparent)]
+#[derive(Default)]
+pub struct Align<const N: usize>([<Self as ValidAlign>::Repr; 0])
+where
+ Self: ValidAlign;
+
+impl<const N: usize> Align<N>
+where
+ Self: ValidAlign,
+{
+ /// Create a new [`Align<N>`].
+ #[inline]
+ pub const fn new() -> Self {
+ Align([])
+ }
+}
+
+macro_rules! impl_align {
+ () => {};
+ ($a:literal $($rest:literal)*) => {
+ const _: () = {
+ #[repr(align($a))]
+ pub struct Repr;
+
+ impl ValidAlign for Align<$a> {
+ type Repr = Repr;
+ }
+ };
+
+ impl_align!($($rest)*);
+ }
+}
+
+impl_align!(1 2 4 8 16 32 64 128 256 512 1024 2048 4096);

base-commit: a87737435cfa134f9cdcc696ba3080759d04cf72
prerequisite-patch-id: 0000000000000000000000000000000000000000
--
2.54.0