aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-heartbeat / src / aligned.rs
| 1 | use std::alloc::{alloc_zeroed, dealloc, Layout}; |
| 2 | use std::ptr::NonNull; |
| 3 | |
| 4 | use crate::IO_ALIGN; |
| 5 | |
| 6 | /// Heap buffer aligned to [`IO_ALIGN`] with a length rounded up to it, as |
| 7 | /// O_DIRECT requires. |
| 8 | pub struct AlignedBuf { |
| 9 | ptr: NonNull<u8>, |
| 10 | layout: Layout, |
| 11 | } |
| 12 | |
| 13 | // SAFETY: plain owned heap memory; aliasing is controlled by the owner. |
| 14 | unsafe impl Send for AlignedBuf {} |
| 15 | unsafe impl Sync for AlignedBuf {} |
| 16 | |
| 17 | impl AlignedBuf { |
| 18 | pub fn new(len: usize) -> Self { |
| 19 | let len = round_up(len.max(1), IO_ALIGN); |
| 20 | let layout = Layout::from_size_align(len, IO_ALIGN).expect("valid layout"); |
| 21 | // SAFETY: layout has non-zero size. |
| 22 | let raw = unsafe { alloc_zeroed(layout) }; |
| 23 | let ptr = NonNull::new(raw).unwrap_or_else(|| std::alloc::handle_alloc_error(layout)); |
| 24 | Self { ptr, layout } |
| 25 | } |
| 26 | |
| 27 | pub fn len(&self) -> usize { |
| 28 | self.layout.size() |
| 29 | } |
| 30 | |
| 31 | pub fn is_empty(&self) -> bool { |
| 32 | false |
| 33 | } |
| 34 | |
| 35 | pub fn as_slice(&self) -> &[u8] { |
| 36 | // SAFETY: ptr is valid for layout.size() initialised bytes. |
| 37 | unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.layout.size()) } |
| 38 | } |
| 39 | |
| 40 | pub fn as_mut_slice(&mut self) -> &mut [u8] { |
| 41 | // SAFETY: as above, and &mut self gives exclusivity. |
| 42 | unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.layout.size()) } |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl Drop for AlignedBuf { |
| 47 | fn drop(&mut self) { |
| 48 | // SAFETY: allocated with this layout in `new`. |
| 49 | unsafe { dealloc(self.ptr.as_ptr(), self.layout) } |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | pub fn round_up(v: usize, a: usize) -> usize { |
| 54 | v.div_ceil(a) * a |
| 55 | } |
| 56 | |
| 57 | pub fn round_down(v: u64, a: u64) -> u64 { |
| 58 | v / a * a |
| 59 | } |