Skip to contentSkip to conversation

rust: add `Alignment` type

PATCH Applied Alexandre Courbot 3 participants 12 messages Sep 8, 2025 – Sep 22, 2025

Subsystems (7)
lore
Share & tools
lore

Alexandre Courbot

author maintainer
#0 lore raw

v5 cover rust: add `Alignment` type

The first patch makes two additions:

- Bring an equivalent of the nightly upstream Alignment type [1] with an near-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.

[1] https://doc.rust-lang.org/std/ptr/struct.Alignment.html

---
Changes in v5:
- Update doccomments a bit.
- Use a const generic instead of a regular argument for the const constructor.
- Link to v4: https://lore.kernel.org/r/[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                   | 226 +++++++++++++++++++++++++++++++++++
 5 files changed, 233 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 v5 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 | 226 +++++++++++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 228 insertions(+)
rust/kernel/lib.rs +2 -0
index fcffc3988a90392f1d5fc19f15c75d9ba7104f9a..833bb070e9a6697dad93ba10c61f5dd52da70f35 100644
@@ -17,6 +17,7 @@
 // the unstable features in use.
 //
 // Stable since Rust 1.79.0.
+#![feature(generic_nonzero)]
 #![feature(inline_const)]
 #![feature(pointer_is_aligned)]
 //
@@ -111,6 +112,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 +226 -0

226 lines not on this page · raw message

Signature · 1 line
2.51.0
#2 lore raw

rust/kernel/ptr.rs line 50

Quoted 8 lines · Alexandre Courbot
rust/kernel/ptr.rs new file +7 -0
+        if 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) })
+        } else {
+            build_error!("Provided alignment is not a power of two.");
+        }

Would build_assert! at the top work instead?

Quoted 1 line

+ /// Returns this alignment as a usize.

Intra-doc link.

Quoted 1 line

+ // SAFETY: per the invariants, self.0 is always a power of two so this block will

"Per".

I can pick this, with or without the user -- or do you need this in Nova this cycle?

Thanks!

Cheers,
Miguel

author maintainer
#3 lore raw

Hi Miguel,

Quoted 11 lines · Miguel Ojeda

rust/kernel/ptr.rs line 50

Quoted 8 lines · Alexandre Courbot
rust/kernel/ptr.rs new file +7 -0
+        if 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) })
+        } else {
+            build_error!("Provided alignment is not a power of two.");
+        }

Would build_assert! at the top work instead?

Oops, it certainly would.

Quoted 11 lines
Quoted 2 lines

+ /// Returns this alignment as a usize.

Intra-doc link.

Quoted 1 line

+ // SAFETY: per the invariants, self.0 is always a power of two so this block will

"Per".

I can pick this, with or without the user -- or do you need this in Nova this cycle?

With -rc6 approaching, I don't think we will merge any Nova code taking advantage of this for this cycle, so please feel free to take this patch. We can then merge patch 2 through drm-rust after -rc1 is released.

Should I send a new revision with your fixes, or will you apply them?

#4 lore raw
Quoted 5 lines · Alexandre Courbot

With -rc6 approaching, I don't think we will merge any Nova code taking advantage of this for this cycle, so please feel free to take this patch. We can then merge patch 2 through drm-rust after -rc1 is released.

Sure, sounds good. I can also take patch 2 already as a user of this if you prefer (ideally with an Acked-by).

Quoted 1 line

Should I send a new revision with your fixes, or will you apply them?

I can, no worries, thanks!

Cheers,
Miguel

author maintainer Acked-by
#5 lore raw
Quoted 9 lines · Miguel Ojeda
Quoted 5 lines · Alexandre Courbot

With -rc6 approaching, I don't think we will merge any Nova code taking advantage of this for this cycle, so please feel free to take this patch. We can then merge patch 2 through drm-rust after -rc1 is released.

Sure, sounds good. I can also take patch 2 already as a user of this if you prefer (ideally with an Acked-by).

Ah right, you will want to introduce a user for this new API. Sure, feel free to take patch 2 as well!

maintainer Acked-by
#6 lore raw
In reply to Miguel Ojeda
Quoted 9 lines · Miguel Ojeda
Quoted 5 lines · Alexandre Courbot

With -rc6 approaching, I don't think we will merge any Nova code taking advantage of this for this cycle, so please feel free to take this patch. We can then merge patch 2 through drm-rust after -rc1 is released.

Sure, sounds good. I can also take patch 2 already as a user of this if you prefer (ideally with an Acked-by).

Yeah, this way around make much more sense,

author maintainer
#7 lore raw

PATCH v5 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 68559902ae78bdef8d9bbe88a2f33eecde2ebcab..27d9edab8347c5ed3be104d62a9e32709238bb92 100644
@@ -3,6 +3,7 @@
 use core::ops::Range;
 
 use kernel::prelude::*;
+use kernel::ptr::{Alignable, Alignment};
 use kernel::sizes::*;
 use kernel::sync::aref::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 e6a06071420566560d69697e85dd0c6b384f33cb..71fbe71b84db9d93fd7ac8eca58e67f97e4bc46a 100644
@@ -9,6 +9,7 @@
 use kernel::device;
 use kernel::error::Result;
 use kernel::prelude::*;
+use kernel::ptr::{Alignable, Alignment};
 use kernel::types::ARef;
 
 /// The offset of the VBIOS ROM in the BAR0 space.
@@ -174,8 +175,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.51.0
author maintainer
#10 lore raw
Quoted 6 lines · Miguel Ojeda
Quoted 3 lines · Alexandre Courbot

prerequisite-message-id: <[email protected]>
prerequisite-patch-id: 2439f5f9b560ee4867716f0018b5326dcd72cda3

I guess you had this in your branch but is not actually needed, right?

Right, that will leave one potential use site for Alignment but it will be removed as that patch will land, so it should not be a problem.

Applied
#11 lore raw
In reply to Alexandre Courbot
Quoted 9 lines · Alexandre Courbot

The first patch makes two additions:

- Bring an equivalent of the nightly upstream Alignment type [1] with an near-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.

Quoted 5 lines

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

[1] https://doc.rust-lang.org/std/ptr/struct.Alignment.html

Applied to rust-next -- thanks everyone!

[ Used build_assert!, added intra-doc link, allowed
clippy::incompatible_msrv, added feature(const_option), capitalized safety comment. - Miguel ]

Cheers,
Miguel