Skip to contentSkip to conversation

rust: add `Alignment` type

PATCH Superseded Alexandre Courbot 4 participants 9 messages Aug 21, 2025 – Sep 8, 2025

Subsystems (7)

v4 of 5 Superseded Latest is v5 →

lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v4 cover rust: add `Alignment` type

Basically a resend of the previous version, plus fixes to build with the MSRV (1.78).

The first patch makes two additions:

- Bring an equivalent of the nightly upstream Alignment type [2] with an identical public interface,
- Add a new Alignable extension trait that provides a way to align values up or down according to an Alignment, and implement it on unsigned integer types.

The second patch makes use of these in the Nova driver.

[3] is recommended as a dependency, a small cleanup preventing an unwrap upon applying this series.

[1] https://github.com/rust-lang/libs-team/issues/631
[2] https://doc.rust-lang.org/std/ptr/struct.Alignment.html
[3] https://lore.kernel.org/rust-for-linux/[email protected]/

---
Changes in v4:
- Add the generic_nonzero feature (stabilized in Rust 1.79) to fix build with Rust 1.78.
- Import core::mem::align_of for older Rust versions (as the patch adding it to the prelude is not attainable from nova-next yet).
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Move align_down and align_up into their own Alignable trait. (thanks Miguel!)
- Fix Alignment::mask implementation to match upstream's.
- Add missing SAFETY: comments.
- Improve grammar on a few hard-to-parse comments.
- Link to v2: https://lore.kernel.org/r/[email protected]

Changes in v2:
- Remove last_checked_bit (use Rust's checked_ilog2 instead).
- Port Rust nightly Alignment type and extend it with align_down and align_up methods.
- Link to v1: https://lore.kernel.org/r/[email protected]

Changes since split from the nova-core series:
- Rename fls to last_set_bit,
- Generate per-type doctests,
- Add invariants section to PowerOfTwo.
- Do not use reference to self in PowerOfTwo methods since it implements Copy,
- Use #[derive] where possible instead of implementing traits manually,
- Remove Deref and Borrow implementations.

---
Alexandre Courbot (2):
rust: add Alignment type
gpu: nova-core: use Alignment for alignment-related operations

 Documentation/gpu/nova/core/todo.rst |   1 -
 drivers/gpu/nova-core/fb.rs          |   6 +-
 drivers/gpu/nova-core/vbios.rs       |   4 +-
 rust/kernel/lib.rs                   |   2 +
 rust/kernel/ptr.rs                   | 219 +++++++++++++++++++++++++++++++++++
 5 files changed, 226 insertions(+), 6 deletions(-)

---
base-commit: 062b3e4a1f880f104a8d4b90b767788786aa7b78
change-id: 20250620-num-9420281c02c7
prerequisite-message-id: <[email protected]>
prerequisite-patch-id: 2439f5f9b560ee4867716f0018b5326dcd72cda3

Best regards,

Signature · 1 line
Alexandre Courbot <[email protected]>
author maintainer
#1 lore raw

PATCH v4 1/2 rust: add `Alignment` type

Alignment operations are very common in the kernel. Since they are always performed using a power-of-two value, enforcing this invariant through a dedicated type leads to fewer bugs and can improve the generated code.

Introduce the Alignment type, inspired by the nightly Rust type of the same name and providing the same interface, and a new Alignable trait allowing unsigned integers to be aligned up or down.

---
 rust/kernel/lib.rs |   2 +
 rust/kernel/ptr.rs | 219 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 221 insertions(+)
rust/kernel/lib.rs +2 -0
index ed53169e795c0badf548025a57f946fa18bc73e3..c26a8b235fc78eb2e1bf71ac193f720e2581c6d2 100644
@@ -17,6 +17,7 @@
 // the unstable features in use.
 //
 // Stable since Rust 1.79.0.
+#![feature(generic_nonzero)]
 #![feature(inline_const)]
 //
 // Stable since Rust 1.81.0.
@@ -110,6 +111,7 @@
 pub mod platform;
 pub mod prelude;
 pub mod print;
+pub mod ptr;
 pub mod rbtree;
 pub mod regulator;
 pub mod revocable;
rust/kernel/ptr.rs new file +219 -0

219 lines not on this page · raw message

Signature · 1 line
2.50.1
maintainer Reviewed-by on v4 1/2
#2 lore raw
Quoted 10 lines · Alexandre Courbot

Alignment operations are very common in the kernel. Since they are always performed using a power-of-two value, enforcing this invariant through a dedicated type leads to fewer bugs and can improve the generated code.

Introduce the Alignment type, inspired by the nightly Rust type of the same name and providing the same interface, and a new Alignable trait allowing unsigned integers to be aligned up or down.

maintainer Reviewed-by on v4 1/2
#3 lore raw
In reply to Alexandre Courbot
Quoted 11 lines · Alexandre Courbot
rust/kernel/ptr.rs new file +11 -0
+    /// Validates that `align` is a power of two at build-time, and returns an [`Alignment`] of the
+    /// same value.
+    ///
+    /// A build error is triggered if `align` cannot be asserted to be a power of two.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::ptr::Alignment;
+    ///
+    /// let v = Alignment::new(16);

rust/kernel/ptr.rs line 49

Quoted 10 lines
rust/kernel/ptr.rs new file +10 -0
+    /// assert_eq!(v.as_usize(), 16);
+    /// ```
+    #[inline(always)]
+    pub const fn new(align: usize) -> Self {
+        build_assert!(align.is_power_of_two());
+
+        // INVARIANT: `align` is a power of two.
+        // SAFETY: `align` is a power of two, and thus non-zero.
+        Self(unsafe { NonZero::new_unchecked(align) })
+    }

For DmaMask::new() we used a const generic instead, which makes it more obvious to the caller that the argument must be known at compile time. So, I'd prefer this here as well.

Either way,

author maintainer
#4 lore raw
Quoted 23 lines · Danilo Krummrich
Quoted 11 lines · Alexandre Courbot
rust/kernel/ptr.rs new file +11 -0
+    /// Validates that `align` is a power of two at build-time, and returns an [`Alignment`] of the
+    /// same value.
+    ///
+    /// A build error is triggered if `align` cannot be asserted to be a power of two.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::ptr::Alignment;
+    ///
+    /// let v = Alignment::new(16);

rust/kernel/ptr.rs line 49

Quoted 10 lines
rust/kernel/ptr.rs new file +10 -0
+    /// assert_eq!(v.as_usize(), 16);
+    /// ```
+    #[inline(always)]
+    pub const fn new(align: usize) -> Self {
+        build_assert!(align.is_power_of_two());
+
+        // INVARIANT: `align` is a power of two.
+        // SAFETY: `align` is a power of two, and thus non-zero.
+        Self(unsafe { NonZero::new_unchecked(align) })
+    }
Quoted 3 lines

For DmaMask::new() we used a const generic instead, which makes it more obvious to the caller that the argument must be known at compile time. So, I'd prefer this here as well.

Ah, being consistent is good, and I think I prefer the const generic as well. Let's do the same thing here.

#5 lore raw
In reply to Alexandre Courbot

rust/kernel/ptr.rs line 17

Quoted 3 lines · Alexandre Courbot
rust/kernel/ptr.rs new file +2 -0
+/// TODO: Temporary substitute for the [`Alignment`] nightly type from the standard library, and to
+/// be eventually replaced by it.

Should this be a comment, i.e. //, rather than part of the docs? (It is fine intermixing if needed, or putting them at the end of the docs too).

rust/kernel/ptr.rs line 54

Quoted 4 lines
rust/kernel/ptr.rs new file +4 -0
+    /// Validates that `align` is a power of two at runtime, and returns an
+    /// [`Alignment`] of the same value.
+    ///
+    /// [`None`] is returned if `align` is not a power of two.

"Returns [None] if ..." is probably simpler.

(Sending these two nits since you will send a new version with the const generic.)

Thanks!

Cheers,
Miguel

author maintainer
#6 lore raw
Quoted 8 lines · Miguel Ojeda

rust/kernel/ptr.rs line 17

Quoted 3 lines · Alexandre Courbot
rust/kernel/ptr.rs new file +2 -0
+/// TODO: Temporary substitute for the [`Alignment`] nightly type from the standard library, and to
+/// be eventually replaced by it.

Should this be a comment, i.e. //, rather than part of the docs? (It is fine intermixing if needed, or putting them at the end of the docs too).

It's probably better as a regular comment indeed.

Quoted 10 lines

rust/kernel/ptr.rs line 54

Quoted 5 lines
rust/kernel/ptr.rs new file +4 -0
+    /// Validates that `align` is a power of two at runtime, and returns an
+    /// [`Alignment`] of the same value.
+    ///
+    /// [`None`] is returned if `align` is not a power of two.

"Returns [None] if ..." is probably simpler.

(Sending these two nits since you will send a new version with the const generic.)

Thanks, I'll apply them!

author maintainer
#7 lore raw

PATCH v4 2/2 gpu: nova-core: use Alignment for alignment-related operations

In reply to Alexandre Courbot

Make use of the newly-available Alignment type and remove the corresponding TODO item.

---
 Documentation/gpu/nova/core/todo.rst | 1 -
 drivers/gpu/nova-core/fb.rs          | 6 +++---
 drivers/gpu/nova-core/vbios.rs       | 4 ++--
 3 files changed, 5 insertions(+), 6 deletions(-)
Documentation/gpu/nova/core/todo.rst +0 -1
index 48b20656dcb16056db7784fa186f161126aae9aa..89431fec9041b1f35cc55799c91f48dc6bc918eb 100644
@@ -145,7 +145,6 @@ Numerical operations [NUMM]
 Nova uses integer operations that are not part of the standard library (or not
 implemented in an optimized way for the kernel). These include:
 
-- Aligning up and down to a power of two,
 - The "Find Last Set Bit" (`fls` function of the C part of the kernel)
   operation.
 
drivers/gpu/nova-core/fb.rs +3 -3
index 4a702525fff4f394b75fcf54145ba78e34a1a539..344cb5d2d919c456212d60d7210667de8041f812 100644
@@ -3,6 +3,7 @@
 use core::ops::Range;
 
 use kernel::prelude::*;
+use kernel::ptr::{Alignable, Alignment};
 use kernel::sizes::*;
 use kernel::types::ARef;
 use kernel::{dev_warn, device};
@@ -130,10 +131,9 @@ pub(crate) fn new(chipset: Chipset, bar: &Bar0) -> Result<Self> {
         };
 
         let frts = {
-            const FRTS_DOWN_ALIGN: u64 = SZ_128K as u64;
+            const FRTS_DOWN_ALIGN: Alignment = Alignment::new(SZ_128K);
             const FRTS_SIZE: u64 = SZ_1M as u64;
-            // TODO[NUMM]: replace with `align_down` once it lands.
-            let frts_base = (vga_workspace.start & !(FRTS_DOWN_ALIGN - 1)) - FRTS_SIZE;
+            let frts_base = vga_workspace.start.align_down(FRTS_DOWN_ALIGN) - FRTS_SIZE;
 
             frts_base..frts_base + FRTS_SIZE
         };
drivers/gpu/nova-core/vbios.rs +2 -2
index 50fbea69fc0038255a0a2b8f7bad57cd55eb65a2..9b81c39b11cea91a93359a239078576165a07200 100644
@@ -10,6 +10,7 @@
 use kernel::error::Result;
 use kernel::pci;
 use kernel::prelude::*;
+use kernel::ptr::{Alignable, Alignment};
 
 /// The offset of the VBIOS ROM in the BAR0 space.
 const ROM_OFFSET: usize = 0x300000;
@@ -177,8 +178,7 @@ fn next(&mut self) -> Option<Self::Item> {
 
         // Advance to next image (aligned to 512 bytes).
         self.current_offset += image_size;
-        // TODO[NUMM]: replace with `align_up` once it lands.
-        self.current_offset = self.current_offset.next_multiple_of(512);
+        self.current_offset = self.current_offset.align_up(Alignment::new(512))?;
 
         Some(Ok(full_image))
     }
Signature · 1 line
2.50.1
author maintainer
#8 lore raw
In reply to Alexandre Courbot
Quoted 13 lines · Alexandre Courbot

Basically a resend of the previous version, plus fixes to build with the MSRV (1.78).

The first patch makes two additions:

- Bring an equivalent of the nightly upstream Alignment type [2] with an identical public interface,
- Add a new Alignable extension trait that provides a way to align values up or down according to an Alignment, and implement it on unsigned integer types.

The second patch makes use of these in the Nova driver.

Quoted 8 lines

[3] is recommended as a dependency, a small cleanup preventing an unwrap upon applying this series.

[1] https://github.com/rust-lang/libs-team/issues/631
[2] https://doc.rust-lang.org/std/ptr/struct.Alignment.html
[3] https://lore.kernel.org/rust-for-linux/[email protected]/

Gentle ping for this feature, how are we feeling about it?