interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

GitHub aien-dev/aienux#64 (code only)

closed derived ef0c627d1be16d85 #64

Imported from GitHub aien-dev/aienux#64 (code only)

GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed).

Base 1d723bf46d1cbe9966a5857b4e3f5090fc81defd · Head fc6152b77dcdbc73b217b15073a3d353872c7bef

Fetch it

A git bundle of the pull request's head, 6274 bytes.

curl -fsSL https://interplane.io/drakestapleton/aienux/patches/ef0c627d1be16d85.bundle -o ef0c627d1be16d85.bundle
git fetch ef0c627d1be16d85.bundle refs/pull/64/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aienux
64
fc6152b77dcdbc73b217b15073a3d353872c7bef
{"kind":"github-import","owner":"aien-dev","repo":"aienux","number":64,"url":"https://github.com/aien-dev/aienux/pull/64","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:41Z","metadata":"unavailable","state_derived":true}

Changes

diff --git a/crates/aienos-kernel/src/acpi.rs b/crates/aienos-kernel/src/acpi.rs
index e501cff4..3a0ed54a 100644
--- a/crates/aienos-kernel/src/acpi.rs
+++ b/crates/aienos-kernel/src/acpi.rs
@@ -12,6 +12,8 @@
 pub const SDT_HEADER_LEN: usize = 36;
 const MADT_ENTRIES_OFFSET: usize = 44;
 const GICC_TYPE: u8 = 0x0B;
+const GICD_TYPE: u8 = 0x0C;
+const GICR_TYPE: u8 = 0x0E;
 const GICC_FLAGS: usize = 12;
 const GICC_MPIDR: usize = 68;
 const GICC_EFFICIENCY_CLASS: usize = 76;
@@ -31,6 +33,48 @@ pub enum AcpiError {
     BadEntry,
 }
 
+/// GICv3 physical register regions advertised by the MADT.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct GicBases {
+    pub distributor: Option<u64>,
+    pub redistributor: Option<(u64, u32)>,
+}
+
+/// Reads the first GIC distributor and redistributor regions from a MADT.
+pub fn madt_gic_bases(madt: &[u8]) -> Result<GicBases, AcpiError> {
+    let madt = checked_table(madt, b"APIC")?;
+    let mut bases = GicBases::default();
+    let mut at = MADT_ENTRIES_OFFSET;
+    while at < madt.len() {
+        let kind = madt[at];
+        let len = *madt.get(at + 1).ok_or(AcpiError::Truncated)? as usize;
+        if len < 2 || at + len > madt.len() {
+            return Err(AcpiError::BadEntry);
+        }
+        let entry = &madt[at..at + len];
+        if kind == GICD_TYPE {
+            if len < 24 {
+                return Err(AcpiError::BadEntry);
+            }
+            if bases.distributor.is_none() {
+                bases.distributor = u64_at(entry, 8);
+            }
+        } else if kind == GICR_TYPE {
+            if len < 16 {
+                return Err(AcpiError::BadEntry);
+            }
+            if bases.redistributor.is_none() {
+                bases.redistributor = Some((
+                    u64_at(entry, 4).ok_or(AcpiError::BadEntry)?,
+                    u32_at(entry, 12).ok_or(AcpiError::BadEntry)?,
+                ));
+            }
+        }
+        at += len;
+    }
+    Ok(bases)
+}
+
 fn u32_at(b: &[u8], at: usize) -> Option<u32> {
     Some(u32::from_le_bytes(b.get(at..at + 4)?.try_into().ok()?))
 }
@@ -235,11 +279,6 @@ mod tests {
     fn madt(entries: &[Vec<u8>]) -> Vec<u8> {
         let mut t = std::vec![0u8; MADT_ENTRIES_OFFSET];
         t[..4].copy_from_slice(b"APIC");
-        // A non-GICC entry (GIC distributor) that must be skipped.
-        let mut gicd = std::vec![0u8; 24];
-        gicd[0] = 0x0C;
-        gicd[1] = 24;
-        t.extend_from_slice(&gicd);
         for e in entries {
             t.extend_from_slice(e);
         }
@@ -250,6 +289,27 @@ mod tests {
         t
     }
 
+    #[test]
+    fn extracts_gicd_and_gicr_bases() {
+        let mut dist = std::vec![0u8; 24];
+        dist[0] = GICD_TYPE;
+        dist[1] = 24;
+        dist[8..16].copy_from_slice(&0x0800_0000u64.to_le_bytes());
+        let mut redist = std::vec![0u8; 16];
+        redist[0] = GICR_TYPE;
+        redist[1] = 16;
+        redist[4..12].copy_from_slice(&0x080a_0000u64.to_le_bytes());
+        redist[12..16].copy_from_slice(&0x20_0000u32.to_le_bytes());
+        let table = madt(&[dist, redist]);
+        assert_eq!(
+            madt_gic_bases(&table).unwrap(),
+            GicBases {
+                distributor: Some(0x0800_0000),
+                redistributor: Some((0x080a_0000, 0x20_0000)),
+            }
+        );
+    }
+
     #[test]
     fn counts_gb10_style_heterogeneous_cores_by_efficiency_class() {
         // Ten efficient cores (class 0) then ten performance cores (class 1).
diff --git a/crates/aienos-kernel/src/gic.rs b/crates/aienos-kernel/src/gic.rs
new file mode 100644
index 00000000..ce665545
--- /dev/null
+++ b/crates/aienos-kernel/src/gic.rs
@@ -0,0 +1,226 @@
+//! GICv3 register programming separated from the address and CPU interface.
+//! This module configures registers only. It does not unmask CPU interrupts.
+
+/// Register access implemented by volatile MMIO or a host fake.
+pub trait GicRegisters {
+    fn read32(&mut self, offset: usize) -> u32;
+    fn write32(&mut self, offset: usize, value: u32);
+    fn write64(&mut self, offset: usize, value: u64);
+}
+
+/// Volatile MMIO adapter for a GIC register frame mapped at its MADT address.
+pub struct MmioGicRegisters {
+    pub base: usize,
+}
+impl GicRegisters for MmioGicRegisters {
+    fn read32(&mut self, offset: usize) -> u32 {
+        crate::arch::MmioReg::<u32>::new(self.base + offset).read()
+    }
+    fn write32(&mut self, offset: usize, value: u32) {
+        crate::arch::MmioReg::<u32>::new(self.base + offset).write(value);
+    }
+    fn write64(&mut self, offset: usize, value: u64) {
+        crate::arch::MmioReg::<u64>::new(self.base + offset).write(value);
+    }
+}
+
+pub const GICD_CTLR: usize = 0x0000;
+pub const GICD_IGROUPR: usize = 0x0080;
+pub const GICD_ISENABLER: usize = 0x0100;
+pub const GICD_IPRIORITYR: usize = 0x0400;
+pub const GICD_IROUTER: usize = 0x6000;
+pub const GICR_WAKER: usize = 0x0014;
+pub const GICR_IGROUPR0: usize = 0x10080;
+pub const GICR_ISENABLER0: usize = 0x10100;
+pub const GICR_IPRIORITYR: usize = 0x10400;
+
+/// Distributor register block at the MADT GICD base.
+pub struct GicDistributor<R>(pub R);
+
+impl<R: GicRegisters> GicDistributor<R> {
+    /// Disable the distributor before configuring it.
+    pub fn disable(&mut self) {
+        self.0.write32(GICD_CTLR, 0);
+    }
+
+    /// Enable affinity routing and non-secure Group 1 delivery at the distributor.
+    pub fn enable_group1(&mut self) {
+        self.0.write32(GICD_CTLR, (1 << 4) | (1 << 1));
+    }
+
+    /// Place an SPI in Group 1, set its priority and affinity route, then enable it.
+    pub fn configure_spi(&mut self, intid: u32, priority: u8, affinity: u64) {
+        let word = (intid / 32) as usize;
+        let group = GICD_IGROUPR + word * 4;
+        let group_value = self.0.read32(group);
+        self.0.write32(group, group_value | (1 << (intid % 32)));
+        let pword = (intid / 4) as usize;
+        let shift = (intid % 4) * 8;
+        let old = self.0.read32(GICD_IPRIORITYR + pword * 4);
+        self.0.write32(
+            GICD_IPRIORITYR + pword * 4,
+            (old & !(0xff << shift)) | (u32::from(priority) << shift),
+        );
+        self.0.write64(
+            GICD_IROUTER + intid as usize * 8,
+            affinity & 0x0000_00ff_00ff_ffff,
+        );
+        self.0.write32(GICD_ISENABLER + word * 4, 1 << (intid % 32));
+    }
+}
+
+/// One CPU's redistributor. The register view must start at that CPU's
+/// RD_base (the GICR frame base from the MADT), NOT the SGI frame: offsets
+/// are RD_base-relative, so `GICR_WAKER` is at +0x14 and the SGI/PPI
+/// registers sit in the SGI frame at +0x10000 (`GICR_IGROUPR0` = 0x10080).
+pub struct GicRedistributor<R>(pub R);
+
+impl<R: GicRegisters> GicRedistributor<R> {
+    /// Wake this redistributor. Returns false if ChildrenAsleep did not clear.
+    pub fn wake(&mut self, poll_limit: usize) -> bool {
+        let value = self.0.read32(GICR_WAKER) & !(1 << 1);
+        self.0.write32(GICR_WAKER, value);
+        for _ in 0..poll_limit {
+            if self.0.read32(GICR_WAKER) & (1 << 2) == 0 {
+                return true;
+            }
+        }
+        false
+    }
+
+    /// Put an SGI or PPI in Group 1, set priority, and enable it.
+    pub fn configure_ppi(&mut self, intid: u8, priority: u8) {
+        assert!(intid < 32);
+        let group = self.0.read32(GICR_IGROUPR0);
+        self.0.write32(GICR_IGROUPR0, group | (1 << intid));
+        let offset = GICR_IPRIORITYR + (intid as usize / 4) * 4;
+        let shift = u32::from(intid % 4) * 8;
+        let old = self.0.read32(offset);
+        self.0.write32(
+            offset,
+            (old & !(0xff << shift)) | (u32::from(priority) << shift),
+        );
+        self.0.write32(GICR_ISENABLER0, 1 << intid);
+    }
+}
+
+/// CPU-interface operations that use ICC_* system registers.
+pub trait GicCpuInterface {
+    fn enable_group1(&mut self);
+    fn set_priority_mask(&mut self, mask: u8);
+    fn acknowledge(&mut self) -> u32;
+    fn end_interrupt(&mut self, intid: u32);
+}
+
+/// No-op CPU interface for host-side sequencing and policy tests.
+#[derive(Default)]
+pub struct FakeGicCpuInterface;
+impl GicCpuInterface for FakeGicCpuInterface {
+    fn enable_group1(&mut self) {}
+    fn set_priority_mask(&mut self, _: u8) {}
+    fn acknowledge(&mut self) -> u32 {
+        1023
+    }
+    fn end_interrupt(&mut self, _: u32) {}
+}
+
+/// AArch64 ICC_* CPU-interface register implementation.
+#[cfg(target_arch = "aarch64")]
+pub struct Aarch64GicCpuInterface;
+#[cfg(target_arch = "aarch64")]
+impl GicCpuInterface for Aarch64GicCpuInterface {
+    fn enable_group1(&mut self) {
+        unsafe {
+            core::arch::asm!("msr ICC_IGRPEN1_EL1, {0}", "isb", in(reg) 1u64, options(nostack));
+        }
+    }
+    fn set_priority_mask(&mut self, mask: u8) {
+        unsafe {
+            core::arch::asm!("msr ICC_PMR_EL1, {0}", "isb", in(reg) u64::from(mask), options(nostack));
+        }
+    }
+    fn acknowledge(&mut self) -> u32 {
+        let v: u64;
+        unsafe {
+            core::arch::asm!("mrs {0}, ICC_IAR1_EL1", out(reg) v, options(nomem, nostack));
+        }
+        v as u32
+    }
+    fn end_interrupt(&mut self, intid: u32) {
+        unsafe {
+            core::arch::asm!("msr ICC_EOIR1_EL1, {0}", "isb", in(reg) u64::from(intid), options(nostack));
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::vec::Vec;
+    #[derive(Default)]
+    struct Fake {
+        writes: Vec<(usize, u64)>,
+        value: u32,
+    }
+    impl GicRegisters for Fake {
+        fn read32(&mut self, _: usize) -> u32 {
+            self.value
+        }
+        fn write32(&mut self, offset: usize, value: u32) {
+            self.writes.push((offset, u64::from(value)));
+        }
+        fn write64(&mut self, offset: usize, value: u64) {
+            self.writes.push((offset, value));
+        }
+    }
+    #[test]
+    fn distributor_spi_programming_order() {
+        let mut gic = GicDistributor(Fake {
+            value: 0x8000_0000,
+            ..Fake::default()
+        });
+        gic.configure_spi(40, 0x80, 0x1234);
+        assert_eq!(
+            gic.0.writes,
+            vec![
+                (GICD_IGROUPR + 4, 0x8000_0100),
+                (GICD_IPRIORITYR + 40, 0x8000_0080),
+                (GICD_IROUTER + 320, 0x1234),
+                (GICD_ISENABLER + 4, 0x100),
+            ]
+        );
+    }
+    #[test]
+    fn register_offsets_match_gicv3_spec() {
+        // Distributor (GICD_base-relative).
+        assert_eq!(
+            (GICD_CTLR, GICD_IGROUPR, GICD_ISENABLER, GICD_IPRIORITYR),
+            (0x0, 0x80, 0x100, 0x400)
+        );
+        // GICD_IROUTER<n> is at 0x6000 + 8n; the first SPI (32) is at 0x6100.
+        assert_eq!(GICD_IROUTER + 32 * 8, 0x6100);
+        // Redistributor (RD_base-relative): WAKER in the RD frame, SGI/PPI
+        // registers in the SGI frame at +0x10000.
+        assert_eq!(GICR_WAKER, 0x14);
+        assert_eq!(
+            (GICR_IGROUPR0, GICR_ISENABLER0, GICR_IPRIORITYR),
+            (0x1_0080, 0x1_0100, 0x1_0400)
+        );
+    }
+
+    #[test]
+    fn redistributor_wakes_and_sets_ppi() {
+        let mut gic = GicRedistributor(Fake::default());
+        assert!(gic.wake(1));
+        gic.configure_ppi(27, 0xa0);
+        assert_eq!(
+            gic.0.writes,
+            vec![
+                (GICR_WAKER, 0),
+                (GICR_IGROUPR0, 1 << 27),
+                (GICR_IPRIORITYR + 24, 0xa000_0000),
+                (GICR_ISENABLER0, 1 << 27),
+            ]
+        );
+    }
+}
diff --git a/crates/aienos-kernel/src/lib.rs b/crates/aienos-kernel/src/lib.rs
index cad61c64..13e5cecf 100644
--- a/crates/aienos-kernel/src/lib.rs
+++ b/crates/aienos-kernel/src/lib.rs
@@ -15,11 +15,13 @@ pub mod console;
 pub mod crypto;
 pub mod display;
 pub mod fatal;
+pub mod gic;
 pub mod mem;
 pub mod recovery;
 pub mod report;
 pub mod store;
 pub mod sync;
+pub mod timer;
 pub mod usb;
 
 #[cfg(all(target_os = "none", not(feature = "std"), not(test)))]
diff --git a/crates/aienos-kernel/src/timer.rs b/crates/aienos-kernel/src/timer.rs
new file mode 100644
index 00000000..fa9ed05c
--- /dev/null
+++ b/crates/aienos-kernel/src/timer.rs
@@ -0,0 +1,94 @@
+//! Pure architectural timer arithmetic and injectable EL1 register access.
+
+/// Convert nanoseconds to counter ticks, rounding up so a requested delay is not shortened.
+pub const fn ns_to_ticks(ns: u64, frequency_hz: u64) -> Option<u64> {
+    if frequency_hz == 0 {
+        return None;
+    }
+    let product = (ns as u128) * (frequency_hz as u128);
+    let ticks = product.saturating_add(999_999_999) / 1_000_000_000;
+    if ticks > u64::MAX as u128 {
+        None
+    } else {
+        Some(ticks as u64)
+    }
+}
+
+/// Convert counter ticks to nanoseconds, truncating sub-nanosecond fractions.
+pub const fn ticks_to_ns(ticks: u64, frequency_hz: u64) -> Option<u64> {
+    if frequency_hz == 0 {
+        return None;
+    }
+    let ns = (ticks as u128) * 1_000_000_000 / frequency_hz as u128;
+    if ns > u64::MAX as u128 {
+        None
+    } else {
+        Some(ns as u64)
+    }
+}
+
+/// Return the absolute counter deadline after `delay_ns`, with checked overflow.
+pub const fn deadline_after(now: u64, delay_ns: u64, frequency_hz: u64) -> Option<u64> {
+    match ns_to_ticks(delay_ns, frequency_hz) {
+        Some(delta) => now.checked_add(delta),
+        None => None,
+    }
+}
+
+/// Architectural EL1 physical counter and timer access.
+pub trait TimerRegisters {
+    fn frequency(&self) -> u64;
+    fn counter(&self) -> u64;
+    fn set_compare(&mut self, deadline: u64);
+    fn enable_timer(&mut self, enabled: bool);
+}
+
+/// AArch64 EL1 physical timer access. EL2 bootstrap must grant EL1 timer access.
+#[cfg(target_arch = "aarch64")]
+pub struct Aarch64TimerRegisters;
+#[cfg(target_arch = "aarch64")]
+impl TimerRegisters for Aarch64TimerRegisters {
+    fn frequency(&self) -> u64 {
+        let value;
+        unsafe {
+            core::arch::asm!("mrs {0}, cntfrq_el0", out(reg) value, options(nomem, nostack));
+        }
+        value
+    }
+    fn counter(&self) -> u64 {
+        let value;
+        unsafe {
+            core::arch::asm!("mrs {0}, cntpct_el0", out(reg) value, options(nomem, nostack));
+        }
+        value
+    }
+    fn set_compare(&mut self, deadline: u64) {
+        unsafe {
+            core::arch::asm!("msr cntp_cval_el0, {0}", "isb", in(reg) deadline, options(nostack));
+        }
+    }
+    fn enable_timer(&mut self, enabled: bool) {
+        let control = u64::from(enabled);
+        unsafe {
+            core::arch::asm!("msr cntp_ctl_el0, {0}", "isb", in(reg) control, options(nostack));
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    #[test]
+    fn conversion_rounding_and_frequency_validation() {
+        assert_eq!(ns_to_ticks(1, 1_000_000), Some(1));
+        assert_eq!(ns_to_ticks(1_000, 1_000_000), Some(1));
+        assert_eq!(ticks_to_ns(1_000, 1_000_000), Some(1_000_000));
+        assert_eq!(ns_to_ticks(1, 0), None);
+    }
+    #[test]
+    fn deadline_detects_overflow() {
+        assert_eq!(deadline_after(50, 10, 1_000_000_000), Some(60));
+        assert_eq!(deadline_after(u64::MAX, 1, 1_000_000_000), None);
+        assert_eq!(deadline_after(0, u64::MAX, u64::MAX), None);
+    }
+}