From 24352e48c8d69765dbce99cea2af813fb1f0f8d3 Mon Sep 17 00:00:00 2001 From: Tyler Smith <74526874+tylertms@users.noreply.github.com> Date: Sun, 1 Nov 2026 22:46:15 +0000 Subject: [PATCH] fix(platform): preserve native IRQ and resident resource ownership --- Cargo.lock | 2 + crates/stela-boot-core/Cargo.toml | 1 + crates/stela-boot-core/src/ioapic.rs | 237 ++- crates/stela-boot-core/src/ioapic/tests.rs | 420 ++++- crates/stela-boot-core/src/lib.rs | 1 + crates/stela-boot-core/src/resident_image.rs | 114 ++ crates/stela-boot-core/src/vtd.rs | 7 + crates/stela-boot/Cargo.lock | 1 + crates/stela-boot/Cargo.toml | 2 +- crates/stela-boot/src/engine/aml/sci.rs | 17 +- crates/stela-boot/src/engine/gpu.rs | 266 ++- crates/stela-boot/src/engine/host.rs | 2 +- crates/stela-boot/src/engine/host/signals.rs | 15 + crates/stela-boot/src/engine/interrupts.rs | 2 +- crates/stela-boot/src/engine/kernel_work.rs | 47 + crates/stela-boot/src/engine/remapping/amd.rs | 29 +- .../src/engine/remapping/preparation.rs | 43 +- crates/stela-boot/src/engine/start.rs | 14 +- crates/stela-boot/src/handoff.rs | 3 + crates/stela-boot/src/main.rs | 1 + crates/stela-boot/src/native_image.rs | 211 +++ crates/stela-boot/src/native_irq.rs | 57 +- .../stela-boot/src/native_irq/diagnostic.rs | 141 +- .../src/native_irq/level_diagnostic.rs | 43 +- crates/stela-boot/src/native_irq/root.rs | 11 +- .../src/native_irq/work_diagnostic.rs | 30 +- .../stela-boot/src/native_mmio/diagnostic.rs | 37 +- crates/stela-boot/src/native_mmio/shared.rs | 35 +- crates/stela-boot/src/system.rs | 2 + crates/stela-boot/src/system/memory.rs | 23 +- crates/stela-driver-base/Cargo.toml | 2 + crates/stela-driver-base/src/bus/irq.rs | 1552 ++++++++++++----- .../src/bus/irq/posted_msi.rs | 593 +++++-- crates/stela-driver-base/src/bus/irq/tests.rs | 800 +++++++-- .../src/bus/mmio/owned/registry.rs | 8 + crates/stela-driver-base/src/bus/pci/msi.rs | 27 +- .../src/bus/pci/msi/retirement.rs | 9 +- .../src/bus/pci/msi/tests/programming.rs | 76 + crates/stela-driver-base/src/bus/pci/msix.rs | 64 +- .../src/bus/pci/msix/tests.rs | 102 +- crates/stela-driver-base/src/bus/pci/owned.rs | 20 + .../src/bus/pci/requester.rs | 2 + .../src/bus/pci/requester/irq_identity.rs | 57 + .../src/bus/pci/requester/preparation.rs | 84 +- .../pci/requester/preparation/attachment.rs | 299 ++++ .../bus/pci/requester/preparation/tests.rs | 75 +- .../preparation/tests/irq_actions.rs | 371 ++++ .../stela-driver-base/src/bus/vmd/source.rs | 22 +- crates/stela-driver-base/src/bus/vmd/tests.rs | 21 +- .../src/aqtion/native/cold.rs | 2 +- .../src/aqtion/native/lifetime.rs | 2 +- .../src/aqtion/tests/ownership.rs | 2 +- .../src/aqtion/tests/ownership/model.rs | 17 +- crates/stela-driver-net/src/tg3/io/cold.rs | 3 +- .../stela-driver-net/src/tg3/io/tests/cold.rs | 13 +- crates/stela-driver-net/src/tg3/packet.rs | 6 +- .../src/tg3/packet/tests/attachment.rs | 26 +- crates/stela-drivers/Cargo.toml | 1 + .../src/bluetooth/bcm4377/native.rs | 151 +- .../src/bluetooth/bcm4377/native/cold.rs | 4 +- .../src/bluetooth/bcm4377/tests/native.rs | 310 +++- .../stela-drivers/src/bluetooth/intel_pcie.rs | 40 +- .../src/bluetooth/intel_pcie/firmware.rs | 6 + .../src/bluetooth/intel_pcie/native.rs | 157 +- .../src/bluetooth/intel_pcie/native/cold.rs | 2 +- .../bluetooth/intel_pcie/native/lifetime.rs | 74 +- .../src/bluetooth/intel_pcie/tests.rs | 47 + .../intel_pcie/tests/native_models.rs | 24 +- .../intel_pcie/tests/native_models/root.rs | 169 +- .../bluetooth/intel_pcie/tests/ownership.rs | 2 +- .../intel_pcie/tests/ownership/cold.rs | 8 +- .../intel_pcie/tests/ownership/lifetime.rs | 46 + .../intel_pcie/tests/ownership/model.rs | 40 +- crates/stela-drivers/src/input/ish/native.rs | 72 +- crates/stela-drivers/src/input/ish/tests.rs | 87 +- crates/stela-drivers/src/probe/native.rs | 44 +- .../src/usb/ehci/native/requester.rs | 2 +- crates/stela-drivers/src/usb/xhci/native.rs | 7 +- crates/stela-linux/Cargo.toml | 3 +- crates/stela-linux/build/native.rs | 20 + crates/stela-linux/src/catalogue.rs | 378 ++++ .../stela-linux/src/compat/kernel/catalogue.c | 494 ++++++ crates/stela-linux/src/compat/kernel/device.c | 15 +- crates/stela-linux/src/compat/kernel/irq.c | 217 ++- crates/stela-linux/src/compat/kernel/linux.c | 3 +- crates/stela-linux/src/compat/kernel/page.c | 101 ++ crates/stela-linux/src/compat/kernel/pci.c | 16 +- .../stela-linux/src/compat/kernel/pci_host.c | 35 +- .../stela-linux/src/compat/kernel/registry.c | 75 + .../stela-linux/src/compat/kernel/service.c | 4 +- crates/stela-linux/src/compat/kernel/task.c | 3 + .../stela-linux/src/compat/kernel/workqueue.c | 5 + .../stela-linux/src/compat/stela/catalogue.h | 36 + crates/stela-linux/src/compat/stela/irq.h | 2 + crates/stela-linux/src/compat/stela/linux.h | 16 +- crates/stela-linux/src/compat/stela/page.h | 11 + crates/stela-linux/src/compat/stela/pci.h | 20 +- .../stela-linux/src/compat/stela/registry.h | 7 + crates/stela-linux/src/compat/stela/service.h | 4 +- .../src/compat/stela/service_test.c | 69 +- .../src/compat/stela/workqueue_test.c | 44 +- crates/stela-linux/src/function.rs | 176 +- .../stela-linux/src/function/tests/fatal.rs | 202 ++- .../src/function/tests/lifetime.rs | 73 + crates/stela-linux/src/kernel.rs | 179 ++ crates/stela-linux/src/lib.rs | 4 + crates/stela-linux/src/owner.rs | 105 +- crates/stela-linux/src/pages.rs | 194 ++- crates/stela-linux/src/pages/mapping.rs | 211 +++ crates/stela-linux/src/pages/tests.rs | 3 + .../src/pages/tests/mapping_pin.rs | 179 ++ crates/stela-linux/src/service.rs | 166 +- crates/stela-linux/src/task/tests.rs | 103 +- 113 files changed, 9135 insertions(+), 1400 deletions(-) create mode 100644 crates/stela-boot-core/src/resident_image.rs create mode 100644 crates/stela-boot/src/native_image.rs create mode 100644 crates/stela-driver-base/src/bus/pci/requester/irq_identity.rs create mode 100644 crates/stela-driver-base/src/bus/pci/requester/preparation/attachment.rs create mode 100644 crates/stela-driver-base/src/bus/pci/requester/preparation/tests/irq_actions.rs create mode 100644 crates/stela-linux/src/catalogue.rs create mode 100644 crates/stela-linux/src/compat/kernel/catalogue.c create mode 100644 crates/stela-linux/src/compat/stela/catalogue.h create mode 100644 crates/stela-linux/src/kernel.rs create mode 100644 crates/stela-linux/src/pages/mapping.rs create mode 100644 crates/stela-linux/src/pages/tests/mapping_pin.rs diff --git a/Cargo.lock b/Cargo.lock index 77b9bf8919..e4d1e4e50b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2123,6 +2123,7 @@ dependencies = [ "stela-compiler", "stela-contracts", "stela-crypto", + "stela-driver-base", "stela-drivers", "stela-engine", "stela-formats", @@ -2389,6 +2390,7 @@ dependencies = [ "stela-c-build", "stela-crypto", "stela-driver-base", + "stela-driver-core", "tempfile", "zeroize", ] diff --git a/crates/stela-boot-core/Cargo.toml b/crates/stela-boot-core/Cargo.toml index eb5d5df757..ca5dd1c94a 100644 --- a/crates/stela-boot-core/Cargo.toml +++ b/crates/stela-boot-core/Cargo.toml @@ -39,6 +39,7 @@ stela-runtime = { path = "../stela-runtime" } stela-soc-data = { path = "../stela-soc-data" } [dev-dependencies] +stela-driver-base = { path = "../stela-driver-base", features = ["test-support"] } serde_json.workspace = true # An independent SHA-256 the tests check digests against. sha2 = { version = "0.10", default-features = false } diff --git a/crates/stela-boot-core/src/ioapic.rs b/crates/stela-boot-core/src/ioapic.rs index 96d2cd53b5..0f94a2bace 100644 --- a/crates/stela-boot-core/src/ioapic.rs +++ b/crates/stela-boot-core/src/ioapic.rs @@ -11,11 +11,12 @@ use alloc::{boxed::Box, sync::Arc}; use core::{ cell::UnsafeCell, mem::ManuallyDrop, - sync::atomic::{AtomicBool, AtomicU64, Ordering}, + sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}, }; use stela_drivers::bus::irq::{ - FIRST_VECTOR, IrqError, LineRoute, Platform, Polarity, Route, RouteRequest, Source, Target, - Trigger, VECTOR_COUNT, + ChipEoi, CpuTarget, FIRST_VECTOR, IrqError, LineRoute, Platform, Polarity, RegistryIdentity, + Route, Source, Target, Trigger, VECTOR_COUNT, + posted_msi::{self, NotificationDomain}, }; const MASK: u32 = 1 << 16; @@ -31,16 +32,19 @@ const MAX_PINS: usize = 120; pub unsafe trait Registers: Send + Sync { fn read(&self, index: u8) -> u32; fn write(&self, index: u8, value: u32); + /// Actual direct MMIO EOI register, not an IOREGSEL/IOWIN index. + /// The caller checked this controller's version is at least 0x20. + fn write_eoi(&self, vector: u8); } pub struct Mmio(usize); impl Mmio { /// # Safety - /// `base` is an exclusive UC IOAPIC mapping of at least 32 bytes, + /// `base` is an exclusive UC IOAPIC mapping of at least 68 bytes, /// aligned to 4 KiB and kept across all roots through final release or /// permanent quarantine. No WB/WC alias exists. No IRQ-context release. pub unsafe fn new(base: usize) -> Result { - if base == 0 || base & 4095 != 0 || base.checked_add(32).is_none() { + if base == 0 || base & 4095 != 0 || base.checked_add(68).is_none() { return Err(IrqError::Route); } Ok(Self(base)) @@ -63,6 +67,11 @@ unsafe impl Registers for Mmio { ((self.0 + 16) as *mut u32).write_volatile(value); } } + fn write_eoi(&self, vector: u8) { + // SAFETY: original complete UC controller mapping; Unit serializes + // access and checked version >=0x20 before this direct register write. + unsafe { ((self.0 + 0x40) as *mut u32).write_volatile(u32::from(vector)) }; + } } /// Real contributors to one physical line, kept as an immutable group. @@ -91,6 +100,9 @@ pub struct State { pub struct Unit { registers: R, platform: P, + domain: Arc, + registry: RegistryIdentity, + version: u8, id: u8, gsi_base: u32, pins: u16, @@ -112,13 +124,18 @@ impl Unit { /// suppression is disabled and remains disabled through final retirement. /// No other CPU/SMM/firmware can program these redirection entries. Pin /// ownership/quiescence must separately be proved for each claim. + /// `domain` is the actual retained CPU/root/controller-format owner, not + /// a target-derived permission; it excludes live remapping-mode changes. pub unsafe fn attach( registers: R, platform: P, + domain: Arc, + registry: RegistryIdentity, id: u8, gsi_base: u32, ) -> Result, IrqError> { - platform.check_cpu()?; + platform.check_process()?; + domain.check().map_err(IrqError::Delivery)?; let saved = platform.save_and_disable(); let version = registers.read(1); // SAFETY: `saved` came from `save_and_disable` on this CPU above. @@ -126,8 +143,8 @@ impl Unit { if version == u32::MAX { return Err(IrqError::FailedRead); } - // Every version takes the local APIC's broadcast EOI, the only EOI - // used here: Intel's 0x11 and 0x20, AMD's 0x21. The MADT's ID is the + // Versions below0x20 require mask/edge/restore for explicit EOI. + // Later versions expose the direct EOI register. The MADT's ID is the // unit's, as Linux keeps it on x86-64; firmware need not program the // ID register to match. let pins = ((version >> 16) & 255) as u16 + 1; @@ -137,6 +154,9 @@ impl Unit { Ok(Arc::new(Self { registers, platform, + domain, + registry, + version: version as u8, id, gsi_base, pins, @@ -264,6 +284,10 @@ impl Unit { epoch, target: None, retired: true, + lifetime: Arc::new(PinLifetime { + phase: AtomicU8::new(CLAIMED), + failed: AtomicBool::new(false), + }), }) } } @@ -290,6 +314,136 @@ pub struct Pin { epoch: u64, target: Option, retired: bool, + lifetime: Arc, +} +const CLAIMED: u8 = 0; +const PROGRAMMED: u8 = 1; +const RETIRED: u8 = 2; +const RELEASED: u8 = 3; +struct PinLifetime { + phase: AtomicU8, + failed: AtomicBool, +} +struct PinDomain { + unit: ManuallyDrop>>, + lifetime: ManuallyDrop>, +} +impl Drop for PinDomain { + fn drop(&mut self) { + if self.unit.platform.check_process().is_err() { + return; + } + // SAFETY: original process context; Slot/caller owns no in-flight + // reference when this final process-owned endpoint is released. + unsafe { + ManuallyDrop::drop(&mut self.lifetime); + ManuallyDrop::drop(&mut self.unit); + } + } +} +// SAFETY: original Unit/root domain and the actual private claim allocation +// remain held. Checks use immutable/atomic metadata only, without Unit locks, +// raw source access, allocation or release in IRQ context. +unsafe impl NotificationDomain for PinDomain { + fn check(&self) -> Result<(), posted_msi::Error> { + self.unit.domain.check()?; + if self.lifetime.failed.load(Ordering::Acquire) + || self.lifetime.phase.load(Ordering::Acquire) == RELEASED + { + return Err(posted_msi::Error::RootFailed); + } + Ok(()) + } +} + +struct PinEoi { + unit: ManuallyDrop>>, + lifetime: ManuallyDrop>, + pin: u8, + epoch: u64, + target: Target, + line: LineRoute, +} +impl Drop for PinEoi { + fn drop(&mut self) { + if self.unit.platform.check_process().is_err() { + return; + } + // SAFETY: only process-owned final release may end kept controller + // resources; a foreign/ISR default Drop instead retains both fields. + unsafe { + ManuallyDrop::drop(&mut self.lifetime); + ManuallyDrop::drop(&mut self.unit); + } + } +} +impl PinEoi { + fn acknowledge(&self, observed: Trigger) -> Result<(), IrqError> { + self.unit.platform.check_cpu()?; + self.unit.domain.check().map_err(IrqError::Delivery)?; + let phase = self.lifetime.phase.load(Ordering::Acquire); + if !matches!(phase, PROGRAMMED | RETIRED) || self.lifetime.failed.load(Ordering::Acquire) { + return Err(IrqError::Unregistered); + } + let _guard = self.unit.lock(); + // SAFETY: original selector/claim lock. Retirement disarms handler + // endpoints before final Slot withdrawal, but keeps this physical pin + // owned until every captured chip EOI and the Source finally release. + let epoch = unsafe { (*self.unit.epochs.get())[usize::from(self.pin)] }; + if epoch != self.epoch && !(phase == RETIRED && epoch == 0) { + return Err(IrqError::Unregistered); + } + let low = self.unit.low(self.pin)?; + let high = self.unit.registers.read(0x11 + self.pin * 2); + let expected = u32::from(self.target.vector) + | 1 << 15 + | if self.line.polarity == Polarity::Low { + 1 << 13 + } else { + 0 + }; + if low & (CONFIG & !MASK) != expected || high != u32::from(self.target.destination) << 24 { + return Err(IrqError::Route); + } + if observed == Trigger::Level { + return Ok(()); + } + // Intel SDM12.8.4: an edge seen by the CPU has no EOI broadcast. + // Linux __eoi_ioapic_pin handles this with direct EOI or a masked + // edge/level transition on older controllers; never a selector0x40. + if self.unit.version >= 0x20 { + self.unit.registers.write_eoi(self.target.vector); + } else { + let masked = low | MASK; + self.unit.registers.write(0x10 + self.pin * 2, masked); + if self.unit.low(self.pin)? & CONFIG != masked & CONFIG { + return Err(IrqError::Mask); + } + let edge = masked & !(1 << 15); + self.unit.registers.write(0x10 + self.pin * 2, edge); + if self.unit.low(self.pin)? & CONFIG != edge & CONFIG { + return Err(IrqError::Route); + } + self.unit.registers.write(0x10 + self.pin * 2, low); + if self.unit.low(self.pin)? & CONFIG != low & CONFIG { + return Err(IrqError::Route); + } + } + Ok(()) + } +} +// SAFETY: endpoint captures only the original checked Registry reservation; +// no access is admitted until actual masked route programming has completed. +// Slot retains original Unit/claim/lifetime through local+chip EOI inflight. +// Same-CPU IRQ-save selector locking is independent of the !Send Source. +unsafe impl ChipEoi for PinEoi { + fn after_local_eoi(&self, observed: Trigger) -> Result<(), IrqError> { + let result = self.acknowledge(observed); + if result.is_err() { + self.lifetime.failed.store(true, Ordering::Release); + } + result + } } impl Pin { /// Pre-bind a real parent mask endpoint in process context before callback @@ -305,6 +459,7 @@ impl Pin { unit: Arc::clone(&self.unit), pin: self.pin, epoch: self.epoch, + lifetime: self.lifetime.clone(), }) } } @@ -315,6 +470,7 @@ pub struct ParentMask { unit: Arc>, pin: u8, epoch: u64, + lifetime: Arc, } impl ParentMask { /// Rearm the same claimed route after its deferred source has been drained. @@ -329,6 +485,9 @@ impl ParentMask { /// physical event after unmask is handled by the same callback. pub unsafe fn rearm(&self) -> Result<(), IrqError> { self.unit.platform.check_cpu()?; + if self.lifetime.failed.load(Ordering::Acquire) { + return Err(IrqError::Drain); + } let _guard = self.unit.lock(); // SAFETY: the lock serializes claim/epoch checks with route retirement. if unsafe { (*self.unit.epochs.get())[usize::from(self.pin)] } != self.epoch { @@ -374,7 +533,37 @@ unsafe impl stela_drivers::bus::irq::ParentMask for P } // SAFETY: devices and unit are held, physical ownership comes from claim's // explicit grant. The canonical registry alone publishes/releases callbacks. -unsafe impl Source for Pin { +unsafe impl Source for Pin { + fn notification_domain(&self) -> Result, IrqError> { + self.unit.platform.check_process()?; + self.unit.domain.check().map_err(IrqError::Delivery)?; + Ok(Arc::new(PinDomain { + unit: ManuallyDrop::new(Arc::clone(&self.unit)), + lifetime: ManuallyDrop::new(self.lifetime.clone()), + })) + } + fn eoi_endpoint( + &mut self, + target: &CpuTarget<'_>, + ) -> Result>, IrqError> { + self.unit.platform.check_process()?; + target.check_current()?; + if !target.belongs_to(self.unit.registry) { + return Err(IrqError::Route); + } + let actual = target.descriptor(); + if self.lifetime.failed.load(Ordering::Acquire) { + return Err(IrqError::Route); + } + Ok(Some(Arc::new(PinEoi { + unit: ManuallyDrop::new(Arc::clone(&self.unit)), + lifetime: ManuallyDrop::new(self.lifetime.clone()), + pin: self.pin, + epoch: self.epoch, + target: actual, + line: self.line, + }))) + } fn mask(&mut self) -> Result<(), IrqError> { self.unit.platform.check_cpu()?; let result = { @@ -394,12 +583,21 @@ unsafe impl Source for Pin { fn quiesce(&mut self) -> Result<(), IrqError> { self.devices.quiesce() } - fn route(&self) -> RouteRequest { - RouteRequest::Line(self.line) + fn route_kind(&self) -> stela_drivers::bus::irq::RouteKind { + stela_drivers::bus::irq::RouteKind::Line } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { - self.unit.platform.check_cpu()?; - let Route::Line { target, line } = route else { + fn requester(&self) -> Option<&stela_drivers::bus::pci::requester::RequesterId> { + None + } + unsafe fn program( + &mut self, + route: &stela_drivers::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { + self.unit.platform.check_process()?; + if !route.belongs_to(self.unit.registry) { + return Err(IrqError::Route); + } + let Route::Line { target, line } = route.programming() else { return Err(IrqError::Route); }; if line != self.line @@ -449,6 +647,7 @@ unsafe impl Source for Pin { { return Err(IrqError::Route); } + self.lifetime.phase.store(PROGRAMMED, Ordering::Release); Ok(()) } unsafe fn unmask(&mut self) -> Result<(), IrqError> { @@ -473,6 +672,9 @@ unsafe impl Source for Pin { } unsafe fn synchronize(&mut self) -> Result<(), IrqError> { self.unit.platform.check_cpu()?; + if self.lifetime.failed.load(Ordering::Acquire) { + return Err(IrqError::Drain); + } self.devices.quiesce()?; let start = self.unit.platform.ticks(); loop { @@ -503,17 +705,22 @@ unsafe impl Source for Pin { let _guard = self.unit.lock(); // SAFETY: the unit lock held above serializes the epoch table. unsafe { (*self.unit.epochs.get())[usize::from(self.pin)] = 0 }; + self.lifetime.phase.store(RETIRED, Ordering::Release); Ok(()) } } impl Drop for Pin { fn drop(&mut self) { - if !self.retired || self.unit.platform.check_cpu().is_err() { + if !self.retired + || self.lifetime.failed.load(Ordering::Acquire) + || self.unit.platform.check_process().is_err() + { self.unit.quarantined.fetch_add(1, Ordering::Relaxed); return; } { let _guard = self.unit.lock(); + self.lifetime.phase.store(RELEASED, Ordering::Release); // SAFETY: the unit lock and IRQ save serialize this selector/window pair on the owning // CPU. unsafe { diff --git a/crates/stela-boot-core/src/ioapic/tests.rs b/crates/stela-boot-core/src/ioapic/tests.rs index 054fe4762b..de136ab853 100644 --- a/crates/stela-boot-core/src/ioapic/tests.rs +++ b/crates/stela-boot-core/src/ioapic/tests.rs @@ -10,6 +10,7 @@ struct Hardware { fail_read: bool, refuse_mask: bool, broken_eoi: bool, + tmr: Trigger, events: alloc::vec::Vec<&'static str>, } impl Hardware { @@ -23,16 +24,19 @@ impl Hardware { ); self.regs[0x22] |= REMOTE_IRR; self.pending = true; + self.tmr = Trigger::Level; self.events.push("deliver"); } } - fn eoi(&mut self) { + fn eoi(&mut self) -> Trigger { + let observed = self.tmr; self.pending = false; self.events.push("eoi"); - if !self.broken_eoi { + if observed == Trigger::Level && !self.broken_eoi { self.regs[0x22] &= !REMOTE_IRR; self.service(); } + observed } } struct Board { @@ -42,6 +46,8 @@ struct Board { calls: AtomicUsize, registry: AtomicPtr>, vector: core::sync::atomic::AtomicU8, + domain_live: AtomicBool, + arming_old_edge: AtomicBool, } impl Board { fn new() -> Arc { @@ -58,6 +64,7 @@ impl Board { fail_read: false, refuse_mask: false, broken_eoi: false, + tmr: Trigger::Edge, events: alloc::vec::Vec::new(), }), ticks: AtomicU64::new(0), @@ -65,6 +72,8 @@ impl Board { calls: AtomicUsize::new(0), registry: AtomicPtr::new(core::ptr::null_mut()), vector: core::sync::atomic::AtomicU8::new(0), + domain_live: AtomicBool::new(true), + arming_old_edge: AtomicBool::new(false), }) } } @@ -102,14 +111,44 @@ unsafe impl Registers for Io { } if old & CONFIG != v & CONFIG && (old ^ v) & !MASK != 0 { assert_ne!(old & MASK, 0, "electrical/vector changed before mask"); - assert_eq!(old & (REMOTE_IRR | DELIVERY), 0); + if old & (1 << 15) != 0 && v & (1 << 15) == 0 { + assert_eq!((old ^ v) & (CONFIG & !(1 << 15)), 0); + } else { + assert_eq!(old & (REMOTE_IRR | DELIVERY), 0); + } } // Hardware does not allow software to clear RO RemoteIRR. h.regs[i] = (v & !(REMOTE_IRR | DELIVERY)) | old & (REMOTE_IRR | DELIVERY); + if old & (1 << 15) != 0 && v & (1 << 15) == 0 && !h.broken_eoi { + h.regs[i] &= !REMOTE_IRR; + h.events.push("edge-eoi"); + } h.events.push(if v & MASK != 0 { "mask" } else { "unmask" }); h.service(); } } + fn write_eoi(&self, vector: u8) { + let mut h = self.0.hw.lock().unwrap(); + assert_eq!(h.regs[0x22] as u8, vector); + assert!(h.regs[1] as u8 >= 0x20); + h.events.push("direct-eoi"); + if !h.broken_eoi { + h.regs[0x22] &= !REMOTE_IRR; + h.service(); + } + } +} +struct Domain(Arc); +// SAFETY: the original independent board peer owns this exact CPU/controller +// mode. Domain loss is controlled independently from RTE/pending/TMR effects. +unsafe impl NotificationDomain for Domain { + fn check(&self) -> Result<(), posted_msi::Error> { + if self.0.domain_live.load(Ordering::Acquire) { + Ok(()) + } else { + Err(posted_msi::Error::RootFailed) + } + } } struct Cpu(Arc); // SAFETY: the board model is the single CPU this test unit runs on. @@ -117,6 +156,9 @@ unsafe impl Platform for Cpu { fn check_cpu(&self) -> Result<(), IrqError> { Ok(()) } + fn check_process(&self) -> Result<(), stela_drivers::bus::irq::IrqError> { + self.check_cpu() + } fn save_and_disable(&self) -> u64 { 0 } @@ -133,8 +175,8 @@ unsafe impl Platform for Cpu { fn pending(&self, _: u8) -> Result { Ok(self.0.hw.lock().unwrap().pending) } - fn eoi(&self) { - self.0.hw.lock().unwrap().eoi(); + fn eoi(&self, _: u8) -> Result { + Ok(self.0.hw.lock().unwrap().eoi()) } fn ticks(&self) -> u64 { self.0.ticks.fetch_add(1, Ordering::Relaxed) @@ -161,6 +203,18 @@ unsafe impl Devices for Contributors { let mut h = self.0.hw.lock().unwrap(); h.asserted = 0; h.events.push("stopped"); + drop(h); + if self.0.arming_old_edge.swap(false, Ordering::AcqRel) { + { + let mut hardware = self.0.hw.lock().unwrap(); + hardware.pending = true; + hardware.tmr = Trigger::Edge; + hardware.events.push("old-edge-arming"); + } + // SAFETY: fixture publishes the original permanent Registry first. + let registry = unsafe { &*self.0.registry.load(Ordering::Acquire) }; + assert!(registry.dispatch(self.0.vector.load(Ordering::Relaxed))); + } Ok(()) } unsafe fn enable(&mut self) -> Result<(), IrqError> { @@ -195,11 +249,25 @@ type Fixture = ( LineRoute, ); fn fixture() -> Fixture { + fixture_version(0x11) +} +fn fixture_version(version: u8) -> Fixture { let b = Board::new(); - // SAFETY: the model board is this unit's only selector/window owner. - let u = unsafe { Unit::attach(Io(b.clone()), Cpu(b.clone()), 0, 0) }.unwrap(); + b.hw.lock().unwrap().regs[1] = u32::from(version) | 23 << 16; let r = Box::leak(Box::new(Registry::new(Cpu(b.clone())))); b.registry.store(r, Ordering::Relaxed); + // SAFETY: the model board is this unit's only selector/window owner. + let u = unsafe { + Unit::attach( + Io(b.clone()), + Cpu(b.clone()), + Arc::new(Domain(b.clone())), + r.identity(), + 0, + 0, + ) + } + .unwrap(); ( b, u, @@ -211,6 +279,237 @@ fn fixture() -> Fixture { }, ) } + +#[test] +fn old_edge_during_arming_gets_only_local_eoi_before_pin_programming() { + let (board, unit, registry, line) = fixture_version(0x20); + // SAFETY: original fixture owns this exact stopped physical source. + let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + board.arming_old_edge.store(true, Ordering::Release); + let mut registration = registry + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(board.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) + .unwrap(); + assert_eq!(board.calls.load(Ordering::Relaxed), 0); + { + let hardware = board.hw.lock().unwrap(); + assert!(!hardware.pending); + let old = hardware + .events + .iter() + .position(|event| *event == "old-edge-arming") + .unwrap(); + let local = hardware + .events + .iter() + .position(|event| *event == "eoi") + .unwrap(); + let destination = hardware + .events + .iter() + .position(|event| *event == "destination") + .unwrap(); + assert!(old < local && local < destination); + assert!(!hardware.events.contains(&"direct-eoi")); + assert!(!hardware.events.contains(&"edge-eoi")); + } + { + let mut hardware = board.hw.lock().unwrap(); + hardware.asserted = 1; + hardware.service(); + } + assert!(registry.dispatch(registration.vector())); + assert_eq!(board.calls.load(Ordering::Relaxed), 1); + assert_eq!(board.hw.lock().unwrap().regs[0x22] & REMOTE_IRR, 0); + finish(registration.retire().unwrap()); + assert_eq!(board.drops.load(Ordering::Relaxed), 1); +} + +#[test] +fn actual_registry_route_refuses_different_electrical_line_before_programming() { + let (board, unit, registry, line) = fixture(); + // SAFETY: actual stopped fixture group owns precisely this claimed GSI. + let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let high = board.hw.lock().unwrap().regs[0x23]; + assert!( + registry + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(board.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(LineRoute { gsi: 8, ..line }), + }) + .is_err() + ); + assert_eq!(board.hw.lock().unwrap().regs[0x23], high); + assert_eq!(board.hw.lock().unwrap().regs[0x22] & 255, 0); +} + +#[test] +fn foreign_registry_reservation_refuses_before_any_route_programming() { + let (board, unit, _, line) = fixture(); + let foreign = Box::leak(Box::new(Registry::new(Cpu(board.clone())))); + // SAFETY: actual fixture owns this stopped physical source. + let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let high_before = board.hw.lock().unwrap().regs[0x23]; + assert!( + foreign + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(board.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) + .is_err() + ); + assert_eq!(board.hw.lock().unwrap().regs[0x23], high_before); + assert_eq!(board.hw.lock().unwrap().regs[0x22] & 255, 0); +} + +#[test] +fn pin_domain_refuses_revoked_root_without_waiting_for_controller_lock() { + let (board, unit, _, line) = fixture(); + // SAFETY: bounded source and genuine original board domain. + let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let domain = pin.notification_domain().unwrap(); + let _held = unit.lock(); + board.domain_live.store(false, Ordering::Release); + // Independent original-root revocation is checked before any selector lock. + assert_eq!(domain.check(), Err(posted_msi::Error::RootFailed)); + board.domain_live.store(true, Ordering::Release); +} + +#[test] +fn old_edge_notification_clears_current_level_remote_irr_with_real_chip_eoi() { + struct Deferred(Arc>); + impl Handler for Deferred { + fn handle(&self) -> Disposition { + stela_drivers::bus::irq::ParentMask::mask(&*self.0).unwrap(); + Disposition::Handled + } + } + for version in [0x11, 0x20, 0x21] { + for deferred in [false, true] { + let (board, unit, registry, line) = fixture_version(version); + // SAFETY: this exact board owns the stopped physical source group. + let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let parent = Arc::new(pin.parent_mask().unwrap()); + let handler: Arc = if deferred { + Arc::new(Deferred(parent)) + } else { + Arc::new(Member(board.clone(), 1, true)) + }; + let mut route = registry + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler, + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) + .unwrap(); + { + let mut h = board.hw.lock().unwrap(); + h.asserted = 1; + h.service(); + assert_ne!(h.regs[0x22] & REMOTE_IRR, 0); + // Independent accepted old edge notification changes CPU TMR; + // controller RemoteIRR and current source cause remain real. + h.tmr = Trigger::Edge; + h.events.clear(); + } + assert!(registry.dispatch(route.vector())); + { + let h = board.hw.lock().unwrap(); + assert_eq!(h.regs[0x22] & REMOTE_IRR, 0); + assert_eq!(h.regs[0x22] & MASK != 0, deferred); + let kind = if version < 0x20 { + "edge-eoi" + } else { + "direct-eoi" + }; + let local = h.events.iter().position(|event| *event == "eoi").unwrap(); + let chip = h.events.iter().position(|event| *event == kind).unwrap(); + assert!(local < chip); + } + finish(route.retire().unwrap()); + } + } +} + +#[test] +fn captured_chip_endpoint_remains_valid_through_retired_source_then_cannot_touch_reuse() { + let (board, unit, _, line) = fixture_version(0x20); + // SAFETY: same independent stopped board source and bounded programming peer. + let mut pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let target = Target { + destination: 3, + vector: 0x51, + }; + // Independent bounded hardware peer: do not invent a Registry reservation. + // This fixture tests endpoint lifetime after the real pin state was installed. + pin.target = Some(target); + pin.retired = false; + pin.lifetime.phase.store(PROGRAMMED, Ordering::Release); + { + let mut hardware = board.hw.lock().unwrap(); + hardware.regs[0x22] = MASK | u32::from(target.vector) | (1 << 13) | (1 << 15); + hardware.regs[0x23] = u32::from(target.destination) << 24; + } + let domain = pin.notification_domain().unwrap(); + let endpoint = PinEoi { + unit: ManuallyDrop::new(unit.clone()), + lifetime: ManuallyDrop::new(pin.lifetime.clone()), + pin: pin.pin, + epoch: pin.epoch, + target, + line, + }; + // SAFETY: original CPU callback/work peer is fully stopped and source masked. + unsafe { pin.synchronize() }.unwrap(); + domain.check().unwrap(); + endpoint.after_local_eoi(Trigger::Edge).unwrap(); + drop(pin); + assert_eq!(board.drops.load(Ordering::Relaxed), 1); + assert_eq!(domain.check(), Err(posted_msi::Error::RootFailed)); + // SAFETY: the exact old board group has retired before this fresh claim. + let replacement = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let writes = board.hw.lock().unwrap().events.len(); + assert_eq!( + endpoint.after_local_eoi(Trigger::Edge), + Err(IrqError::Unregistered) + ); + assert_eq!(board.hw.lock().unwrap().events.len(), writes); + drop(replacement); +} + +#[test] +fn chip_eoi_fault_keeps_source_and_forbids_deferred_rearm() { + let (board, unit, registry, line) = fixture_version(0x20); + // SAFETY: this exact stopped board group belongs to the fixture. + let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); + let parent = pin.parent_mask().unwrap(); + let mut route = registry + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(board.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) + .unwrap(); + { + let mut h = board.hw.lock().unwrap(); + h.asserted = 1; + h.service(); + h.tmr = Trigger::Edge; + h.fail_read = true; + } + assert!(registry.dispatch(route.vector())); + board.hw.lock().unwrap().fail_read = false; + // SAFETY: original process peer; a failed chip acknowledgement cannot rearm. + assert_eq!(unsafe { parent.rearm() }, Err(IrqError::Drain)); + assert!(route.retire().is_err()); + drop(route); + assert_eq!(board.drops.load(Ordering::Relaxed), 0); +} #[test] fn real_parent_mask_contains_asserted_level_and_stale_endpoint_cannot_mask_reused_pin() { struct FailedDemux(Arc>); @@ -227,7 +526,11 @@ fn real_parent_mask_contains_asserted_level_and_stale_endpoint_cannot_mask_reuse let pin = unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }.unwrap(); let endpoint = Arc::new(pin.parent_mask().unwrap()); let mut registration = r - .request(Box::new(pin), Arc::new(FailedDemux(endpoint.clone()))) + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(FailedDemux(endpoint.clone())), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) .unwrap(); { let mut h = b.hw.lock().unwrap(); @@ -245,7 +548,7 @@ fn real_parent_mask_contains_asserted_level_and_stale_endpoint_cannot_mask_reuse assert_eq!(h.regs[0x22] & REMOTE_IRR, 0); assert!(!h.pending, "masked parent must not retrigger after EOI"); } - registration.retire().unwrap(); + finish(registration.retire().unwrap()); assert_eq!( stela_drivers::bus::irq::ParentMask::mask(&*endpoint), Err(IrqError::Unregistered) @@ -254,7 +557,11 @@ fn real_parent_mask_contains_asserted_level_and_stale_endpoint_cannot_mask_reuse let replacement = unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }.unwrap(); let replacement_mask = replacement.parent_mask().unwrap(); let mut replacement = r - .request(Box::new(replacement), Arc::new(Member(b.clone(), 1, true))) + .request(stela_drivers::bus::irq::Request { + source: Box::new(replacement), + handler: Arc::new(Member(b.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) .unwrap(); assert_eq!( stela_drivers::bus::irq::ParentMask::mask(&*endpoint), @@ -269,7 +576,7 @@ fn real_parent_mask_contains_asserted_level_and_stale_endpoint_cannot_mask_reuse stela_drivers::bus::irq::ParentMask::mask(&replacement_mask), Ok(()) ); - replacement.retire().unwrap(); + finish(replacement.retire().unwrap()); } #[test] @@ -286,7 +593,11 @@ fn deferred_rearm_checks_drain_epoch_and_retirement() { let pin = unsafe { unit.claim(line, Box::new(Contributors(board.clone()))) }.unwrap(); let parent = Arc::new(pin.parent_mask().unwrap()); let mut route = registry - .request(Box::new(pin), Arc::new(Deferred(parent.clone()))) + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Deferred(parent.clone())), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) .unwrap(); // A still-live unmasked route cannot be rearmed as if it was drained. // SAFETY: the test is the parent mask's only caller, in process context. @@ -316,7 +627,7 @@ fn deferred_rearm_checks_drain_epoch_and_retirement() { // and no deferred producer remains on this owning fixture CPU. unsafe { parent.rearm() }.unwrap(); assert_eq!(board.hw.lock().unwrap().regs[0x22] & MASK, 0); - route.retire().unwrap(); + finish(route.retire().unwrap()); // SAFETY: the test is the parent mask's only caller, in process context. assert_eq!(unsafe { parent.rearm() }, Err(IrqError::Unregistered)); } @@ -328,7 +639,11 @@ fn parent_mask_readback_failures_are_errors_and_claim_epochs_never_wrap() { let pin = unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }.unwrap(); let endpoint = pin.parent_mask().unwrap(); let mut registration = r - .request(Box::new(pin), Arc::new(Member(b.clone(), 1, true))) + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(b.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) .unwrap(); b.hw.lock().unwrap().refuse_mask = true; assert_eq!( @@ -345,7 +660,7 @@ fn parent_mask_readback_failures_are_errors_and_claim_epochs_never_wrap() { h.fail_read = false; h.refuse_mask = false; } - registration.retire().unwrap(); + finish(registration.retire().unwrap()); { let _guard = u.lock(); // SAFETY: the unit lock held above serializes the epoch counter. @@ -370,7 +685,13 @@ fn true_level_retriggers_after_eoi_until_cause_ack_then_shared_group_retires() { let first: Arc = Arc::new(Member(b.clone(), 1, false)); let second: Arc = Arc::new(Member(b.clone(), 2, true)); let group = Arc::new(SharedHandlers::new(alloc::vec![first.clone(), second.clone()]).unwrap()); - let mut registration = r.request(Box::new(pin), group.clone()).unwrap(); + let mut registration = r + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: group.clone(), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) + .unwrap(); { let mut h = b.hw.lock().unwrap(); h.asserted = 3; @@ -388,7 +709,7 @@ fn true_level_retriggers_after_eoi_until_cause_ack_then_shared_group_retires() { assert_eq!(Arc::strong_count(&first), 2); // A second delivery remains possible; removal must mask first, // stop every contributor, then drain CPU EOI and IOAPIC RemoteIRR. - registration.retire().unwrap(); + finish(registration.retire().unwrap()); let h = b.hw.lock().unwrap(); assert!(!h.pending); assert_eq!(h.regs[0x22] & REMOTE_IRR, 0); @@ -414,7 +735,11 @@ fn failed_controller_eoi_or_read_keeps_route_and_contributors_for_real_retry() { // SAFETY: the fixture owns the stopped line and its contributors. let pin = unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }.unwrap(); let mut registration = r - .request(Box::new(pin), Arc::new(Member(b.clone(), 1, true))) + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(b.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) .unwrap(); { let mut h = b.hw.lock().unwrap(); @@ -422,7 +747,7 @@ fn failed_controller_eoi_or_read_keeps_route_and_contributors_for_real_retry() { h.service(); h.broken_eoi = true; } - assert_eq!(registration.retire(), Err(IrqError::Drain)); + assert!(matches!(registration.retire(), Err(IrqError::Drain))); assert_eq!(b.drops.load(Ordering::Relaxed), 0); assert!(matches!( // SAFETY: the fixture owns the stopped line and its contributors. @@ -433,14 +758,14 @@ fn failed_controller_eoi_or_read_keeps_route_and_contributors_for_real_retry() { let mut h = b.hw.lock().unwrap(); h.fail_read = true; } - assert_eq!(registration.retire(), Err(IrqError::FailedRead)); + assert!(matches!(registration.retire(), Err(IrqError::FailedRead))); { let mut h = b.hw.lock().unwrap(); h.fail_read = false; h.broken_eoi = false; h.eoi(); } - registration.retire().unwrap(); + finish(registration.retire().unwrap()); assert_eq!(u.quarantine_count(), 0); } #[test] @@ -461,32 +786,21 @@ fn electrical_route_mismatch_duplicate_claim_mask_failure_and_abandoned_pin_are_ Err(IrqError::Unsupported) )); // SAFETY: the fixture owns the stopped line and its contributors. - let mut pin = unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }.unwrap(); + let pin = unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }.unwrap(); assert!(matches!( // SAFETY: the fixture owns the stopped line and its contributors. unsafe { u.claim(line, Box::new(Contributors(b.clone()))) }, Err(IrqError::Exhausted) )); - let mismatch = LineRoute { gsi: 8, ..line }; - assert_eq!( - // SAFETY: the unit lock and IRQ save serialize this selector/window pair on the owning - // CPU. - unsafe { - pin.program(Route::Line { - target: Target { - destination: 3, - vector: FIRST_VECTOR, - }, - line: mismatch, - }) - }, - Err(IrqError::Route) - ); let mut registration = r - .request(Box::new(pin), Arc::new(Member(b.clone(), 1, true))) + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: Arc::new(Member(b.clone(), 1, true)), + routing: stela_drivers::bus::irq::RouteRequest::Line(line), + }) .unwrap(); b.hw.lock().unwrap().refuse_mask = true; - assert_eq!(registration.retire(), Err(IrqError::Mask)); + assert!(matches!(registration.retire(), Err(IrqError::Mask))); let before = b.drops.load(Ordering::Relaxed); drop(registration); assert_eq!(r.quarantine_count(), 1); @@ -497,17 +811,23 @@ fn electrical_route_mismatch_duplicate_claim_mask_failure_and_abandoned_pin_are_ let other = LineRoute { gsi: 10, ..line }; // SAFETY: the fixture owns the stopped line and its contributors. let mut pin = unsafe { u.claim(other, Box::new(Contributors(b.clone()))) }.unwrap(); - // SAFETY: the unit lock and IRQ save serialize this selector/window pair on the owning CPU. - unsafe { - pin.program(Route::Line { - target: Target { - destination: 3, - vector: FIRST_VECTOR + 1, - }, - line: other, - }) - } - .unwrap(); + // Independent physical peer: hardware publication has already occurred. + // No fabricated Registry reservation or completion receipt is constructed. + pin.target = Some(Target { + destination: 3, + vector: FIRST_VECTOR + 1, + }); + pin.retired = false; + pin.lifetime.phase.store(PROGRAMMED, Ordering::Release); drop(pin); assert_eq!(u.quarantine_count(), 1); } + +fn finish(retired: stela_drivers::bus::irq::RetiredSource) { + // SAFETY: this model's exact line route completed on its owner CPU. + let (source, callback, route) = + unsafe { retired.into_parts() }.unwrap_or_else(|_| panic!("model owner changed")); + drop(source); + drop(callback); + drop(route); +} diff --git a/crates/stela-boot-core/src/lib.rs b/crates/stela-boot-core/src/lib.rs index 4ff34536d8..710aa48126 100644 --- a/crates/stela-boot-core/src/lib.rs +++ b/crates/stela-boot-core/src/lib.rs @@ -54,6 +54,7 @@ pub mod record; pub mod remapping; #[cfg(target_arch = "x86_64")] pub mod requester; +pub mod resident_image; pub mod root_transition; pub mod screen; pub mod shutdown; diff --git a/crates/stela-boot-core/src/resident_image.rs b/crates/stela-boot-core/src/resident_image.rs new file mode 100644 index 0000000000..e89e97dfcf --- /dev/null +++ b/crates/stela-boot-core/src/resident_image.rs @@ -0,0 +1,114 @@ +//! Geometry of a relocated image inside an independently owned allocation. +//! This describes byte ranges only; it creates no allocation, code or root pin. +use core::ops::Range; + +const PAGE: u64 = 4096; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + Geometry, + Overflow, + OutsideAllocation, +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct Layout { + allocation: (u64, u64), + physical: u64, + bytes: u64, + virtual_base: u64, +} +impl Layout { + pub fn within( + allocation: Range, + image_bytes: usize, + alignment: u64, + virtual_base: u64, + ) -> Result { + if allocation.start == 0 + || allocation.start >= allocation.end + || !allocation.start.is_multiple_of(PAGE) + || !allocation.end.is_multiple_of(PAGE) + || image_bytes == 0 + || image_bytes > isize::MAX as usize + || alignment < PAGE + || !alignment.is_power_of_two() + || !virtual_base.is_multiple_of(PAGE) + { + return Err(Error::Geometry); + } + let bytes = (image_bytes as u64) + .checked_next_multiple_of(PAGE) + .ok_or(Error::Overflow)?; + let physical = allocation + .start + .checked_next_multiple_of(alignment) + .ok_or(Error::Overflow)?; + let end = physical.checked_add(bytes).ok_or(Error::Overflow)?; + virtual_base.checked_add(bytes).ok_or(Error::Overflow)?; + if end > allocation.end { + return Err(Error::OutsideAllocation); + } + Ok(Self { + allocation: (allocation.start, allocation.end), + physical, + bytes, + virtual_base, + }) + } + pub fn allocation(self) -> Range { + self.allocation.0..self.allocation.1 + } + pub fn physical(self) -> Range { + self.physical..self.physical + self.bytes + } + pub fn virtual_range(self) -> Range { + self.virtual_base..self.virtual_base + self.bytes + } + pub fn overlaps(self, other: Range) -> bool { + self.allocation.0 < other.end && other.start < self.allocation.1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rounded_copy_stays_in_original_allocation() { + let image = + Layout::within(0x101000..0x501000, 0x200001, 0x200000, 0xffff800000000000).unwrap(); + assert_eq!(image.physical(), 0x200000..0x401000); + assert_eq!(image.allocation(), 0x101000..0x501000); + assert_eq!( + image.virtual_range(), + 0xffff800000000000..0xffff800000201000 + ); + } + #[test] + fn allocation_padding_remains_excluded_from_reuse() { + let image = Layout::within(0x101000..0x501000, 4096, 0x200000, 0x10000000).unwrap(); + assert!(image.overlaps(0x101000..0x102000)); + assert!(image.overlaps(0x500000..0x501000)); + assert!(!image.overlaps(0x100000..0x101000)); + assert!(!image.overlaps(0x501000..0x502000)); + } + #[test] + fn malformed_allocations_and_virtual_extents_refuse() { + for (allocation, bytes, alignment, virtual_base, error) in [ + (0..0x100000, 1, 4096, 0x1000, Error::Geometry), + (0x1000..0x1000, 1, 4096, 0x1000, Error::Geometry), + (0x1001..0x3000, 1, 4096, 0x1000, Error::Geometry), + (0x1000..0x3001, 1, 4096, 0x1000, Error::Geometry), + (0x1000..0x3000, 0, 4096, 0x1000, Error::Geometry), + (0x1000..0x3000, 1, 8191, 0x1000, Error::Geometry), + (0x1000..0x3000, 1, 4096, 0x1001, Error::Geometry), + (0x1000..0x3000, 8193, 4096, 0x1000, Error::OutsideAllocation), + (0x1000..0x3000, 1, 4096, u64::MAX - 4095, Error::Overflow), + ] { + assert_eq!( + Layout::within(allocation, bytes, alignment, virtual_base), + Err(error) + ); + } + } +} diff --git a/crates/stela-boot-core/src/vtd.rs b/crates/stela-boot-core/src/vtd.rs index b459936863..f388358cdf 100644 --- a/crates/stela-boot-core/src/vtd.rs +++ b/crates/stela-boot-core/src/vtd.rs @@ -1142,6 +1142,13 @@ impl RequesterDomain { .filter(|d| d.did == self.did && d.generation == self.generation && !d.quarantined) .ok_or(DmaError::Unmapped) } + /// Observe this exact retained domain's mapping inventory without changing + /// a context, command queue or configuration. Callers retain their actual + /// original process/root context; this supplies no detach/stop receipt. + pub fn has_live_mappings(&self) -> Result { + let mut guard = self.unit.lock(); + Ok(!self.domain(guard.state(), false)?.mappings.is_empty()) + } /// # Safety /// The device is stopped before disabling, or every enabled DMA /// address is published under this owned domain. Device IRQ/work/reset and diff --git a/crates/stela-boot/Cargo.lock b/crates/stela-boot/Cargo.lock index 8acd5d87e2..7c027415d0 100644 --- a/crates/stela-boot/Cargo.lock +++ b/crates/stela-boot/Cargo.lock @@ -1165,6 +1165,7 @@ dependencies = [ "stela-c-build", "stela-crypto", "stela-driver-base", + "stela-driver-core", "zeroize", ] diff --git a/crates/stela-boot/Cargo.toml b/crates/stela-boot/Cargo.toml index 4b95b4b26b..010e4089c5 100644 --- a/crates/stela-boot/Cargo.toml +++ b/crates/stela-boot/Cargo.toml @@ -26,7 +26,7 @@ test = false [features] default = [] -diagnostics = [] +diagnostics = ["stela-drivers/irq-diagnostics"] native-profile = ["stela-soc/native-profile", "stela-engine/native-profile"] # NVK, NIR and NAK in the image, from `cargo xtask gpu nvk`. nvk = ["dep:stela-mesa", "stela-drivers/metal-linked"] diff --git a/crates/stela-boot/src/engine/aml/sci.rs b/crates/stela-boot/src/engine/aml/sci.rs index 196f0d638c..5db7af7421 100644 --- a/crates/stela-boot/src/engine/aml/sci.rs +++ b/crates/stela-boot/src/engine/aml/sci.rs @@ -91,7 +91,13 @@ impl Prepared { pending: pending.clone(), failed: failed.clone(), }); - let registration = native_irq::service()?.request(Box::new(pin), callback)?; + let registration = native_irq::service()? + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: callback, + routing: stela_drivers::bus::irq::RouteRequest::Line(self.line), + }) + .map_err(|e| e.error)?; Ok(Armed { pending, failed, @@ -249,6 +255,13 @@ impl Armed { unsafe { self.parent.rearm() } } pub(super) fn retire(&mut self) -> Result<(), IrqError> { - self.registration.retire() + let retired = self.registration.retire()?; + // SAFETY: same original SCI line owner, stopped sources and completed callback. + let (source, callback, route) = + unsafe { retired.into_parts() }.map_err(|failure| failure.error)?; + drop(source); + drop(callback); + drop(route); + Ok(()) } } diff --git a/crates/stela-boot/src/engine/gpu.rs b/crates/stela-boot/src/engine/gpu.rs index f245c33e92..70e7f5e1f0 100644 --- a/crates/stela-boot/src/engine/gpu.rs +++ b/crates/stela-boot/src/engine/gpu.rs @@ -52,18 +52,15 @@ use stela_drivers::gpu::metal::nvidia::PcieLink; use stela_drivers::{ bus::{ dma::mapping::DmaDomain, - irq::{Disposition, Handler, IrqError, IrqRegistration, Route, RouteRequest, Source}, + irq::{Disposition, Handler, IrqError, IrqRegistration, Route, Source}, mmio::owned, pci::{Bar, ConfigSpace, Function, owned::OwnedConfig}, }, firmware::{Catalog, Provider, Requirement, Target}, gpu, - platform::{ - image::NativeReadOnlyImage, - work::{ - Cpu, WorkError, - service::{Clock, Domain, Idle}, - }, + platform::work::{ + Cpu, WorkError, + service::{Clock, Domain, Idle}, }, probe::{NativeServices, ServiceError}, }; @@ -186,51 +183,6 @@ unsafe impl Idle for Events { } } -/// `.rdata` of the running image, which Linux keeps constant names in. -struct ReadOnlyImage(Range); - -unsafe extern "C" { - /// The image's first byte, which the linker defines. - static __ImageBase: u8; -} - -impl ReadOnlyImage { - /// The section from the headers the image was loaded with. - fn locate() -> Option { - const NEW_HEADER: usize = 0x3c; - const SECTION_COUNT: usize = 6; - const OPTIONAL_SIZE: usize = 20; - const SECTIONS: usize = 24; - const SECTION_BYTES: usize = 40; - let base = addr_of!(__ImageBase); - // SAFETY: the loader keeps the image's headers, little-endian on x86. - let read = |at: usize, bytes: usize| unsafe { - (0..bytes).fold(0usize, |value, byte| { - value | usize::from(base.add(at + byte).read()) << (8 * byte) - }) - }; - let header = read(NEW_HEADER, 4); - let sections = header + SECTIONS + read(header + OPTIONAL_SIZE, 2); - (0..read(header + SECTION_COUNT, 2)).find_map(|index| { - let section = sections + index * SECTION_BYTES; - // SAFETY: as for `read`. - let name = unsafe { core::slice::from_raw_parts(base.add(section), 8) }; - (name == b".rdata\0\0").then(|| { - let start = base as usize + read(section + 12, 4); - Self(start..start + read(section + 8, 4)) - }) - }) - } -} - -// SAFETY: the image's own read-only section, which never moves or changes and -// holds every literal of the Rust and C code linked into it. -unsafe impl NativeReadOnlyImage for ReadOnlyImage { - fn contains(&self, address: usize) -> bool { - self.0.contains(&address) - } -} - unsafe fn allocate_zeroed(layout: Layout) -> *mut u8 { // SAFETY: the registration's contract, which this allocator's one attempt // at its lock meets; the C side frees through the global allocator. @@ -267,55 +219,95 @@ impl ConfigSpace for SharedConfig { struct MsiSource { config: SharedConfig, msi: Msi, + programmed: bool, + event: stela_linux::service::IrqEvent, + environment: *const Environment, + line: u32, } // SAFETY: the function was stopped when claimed, with no route of its own. -// Nothing here frees: the config and capability stay with the registration, and -// nouveau has masked its interrupts by the time it frees the line. +// Nothing here frees: config/capability stay with the registration. Terminal +// engine/payload/Linux-work joining is unavailable, so a programmed route's +// close refuses and retains owners even if nouveau masked its local source. unsafe impl Source for MsiSource { fn mask(&mut self) -> Result<(), IrqError> { + let command = self.config.read16(4); + if command == u16::MAX { + return Err(IrqError::FailedRead); + } + self.config.write16(4, command | 1 << 10); self.msi.disable(&mut self.config); + let actual = self.config.read16(4); + let control = self.msi.control(&self.config); + if actual == u16::MAX || control == u16::MAX { + return Err(IrqError::FailedRead); + } + if actual & (1 << 10) == 0 || control & 1 != 0 { + return Err(IrqError::Mask); + } Ok(()) } fn quiesce(&mut self) -> Result<(), IrqError> { + if self.programmed { + // GPU engine/payload and Linux service work have no independent + // joined terminal acknowledgement here. Retain the old route. + return Err(IrqError::Unsupported); + } self.mask() } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> stela_drivers::bus::irq::RouteKind { + stela_drivers::bus::irq::RouteKind::Msi } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { - let Route::Msi(message) = route else { + fn requester(&self) -> Option<&stela_drivers::bus::pci::requester::RequesterId> { + None + } + unsafe fn program( + &mut self, + route: &stela_drivers::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { + let Route::Msi(message) = route.programming() else { return Err(IrqError::Route); }; let data = u16::try_from(message.data).map_err(|_| IrqError::Route)?; + self.programmed = true; self.msi.program(&mut self.config, message.address, data); Ok(()) } unsafe fn unmask(&mut self) -> Result<(), IrqError> { self.msi.enable(&mut self.config); + let control = self.msi.control(&self.config); + if control == u16::MAX { + return Err(IrqError::FailedRead); + } + if control & 1 == 0 { + return Err(IrqError::Mask); + } Ok(()) } unsafe fn synchronize(&mut self) -> Result<(), IrqError> { - Ok(()) + unsafe extern "C" { + fn stela_linux_irq_actions_joined(irq: u32) -> bool; + } + // SAFETY: native callback runs below the exact entered Linux owner; + // C free_irq retains its closing request and joined work until return. + if !unsafe { stela_linux_irq_actions_joined(self.line) } { + return Err(IrqError::Drain); + } + self.event.begin_close(); + // SAFETY: Registry already closed this exact action and drained native + // CPU/inflight/EOI; the original pinned environment/event are retained. + unsafe { (&*self.environment).join_irq(&self.event) }.map_err(|_| IrqError::Drain) } } /// Records an interrupt for the service task. struct Fired { - environment: *const Environment, - line: u32, + event: stela_linux::service::IrqEvent, } -// SAFETY: `raise` is the environment's interrupt-safe entry, and it lives for -// the boot. -unsafe impl Send for Fired {} -// SAFETY: as above. -unsafe impl Sync for Fired {} - impl Handler for Fired { fn handle(&self) -> Disposition { - // SAFETY: the environment outlives every route, as above. - match unsafe { &*self.environment }.raise(self.line) { + match self.event.raise() { Ok(()) => Disposition::Handled, Err(_) => Disposition::NotMine, } @@ -349,6 +341,7 @@ struct Line { config: SharedConfig, msi: Option, registration: Option>, + retired: Option>, } /// What Linux code gets from Stela. @@ -514,42 +507,132 @@ impl Platform for Host { self.unmap(address as u64, count); } - fn irq_enable(&self, irq: u32) -> Result<(), Errno> { + fn irq_enable(&self, irq: u32) -> Result<(), stela_linux::owner::IrqEnableError> { + use stela_linux::owner::IrqEnableError; + // Refuse a foreign native execution context before classifying any + // owner return; no errno itself proves a clean unpublished attempt. + let controller = native_irq::service().map_err(|_| IrqEnableError::retained(ENODEV))?; let mut lines = self.lines.borrow_mut(); - let line = lines.get_mut(irq as usize).ok_or(EINVAL)?; - let msi = line.msi.ok_or(EOPNOTSUPP)?; - let controller = native_irq::service().map_err(|_| ENODEV)?; + let Some(line) = lines.get_mut(irq as usize) else { + // SAFETY: checked original process, before any route/event/source. + return Err(unsafe { IrqEnableError::unexposed(EINVAL) }); + }; + if line.retired.is_some() { + return Err(IrqEnableError::retained(EOPNOTSUPP)); + } + if let Some(registration) = &mut line.registration { + return registration + .unmask() + .map_err(|_| IrqEnableError::retained(EIO)); + } + let Some(msi) = line.msi else { + // SAFETY: no native attempt or service epoch was issued. + return Err(unsafe { IrqEnableError::unexposed(EOPNOTSUPP) }); + }; + // SAFETY: actual original entered process; any preceding epoch joined. + let event = unsafe { self.environment().irq_epoch(irq) } + .map_err(|_| IrqEnableError::retained(EIO))?; let source = Box::new(MsiSource { config: line.config.clone(), msi, - }); - let handler = Arc::new(Fired { + programmed: false, + event: event.clone(), environment: self.environment.get(), line: irq, }); - match controller.request(source, handler) { + let handler = Arc::new(Fired { + event: event.clone(), + }); + match controller.request(stela_drivers::bus::irq::Request { + source, + handler, + routing: stela_drivers::bus::irq::RouteRequest::Msi( + stela_drivers::bus::irq::posted_msi::MsiRoute::unavailable(), + ), + }) { Ok(registration) => { line.registration = Some(registration); Ok(()) } - Err(error) => { - self.report(format_args!("interrupt {irq} refused: {error:?}")); - Err(EIO) + Err(refusal) => { + let errno = match refusal.error { + stela_drivers::bus::irq::IrqError::Exhausted => ENOMEM, + stela_drivers::bus::irq::IrqError::Unavailable => ENODEV, + stela_drivers::bus::irq::IrqError::Unsupported + | stela_drivers::bus::irq::IrqError::Delivery( + stela_drivers::bus::irq::posted_msi::Error::RootUnavailable + | stela_drivers::bus::irq::posted_msi::Error::Unsupported, + ) => EOPNOTSUPP, + _ => EIO, + }; + if errno == EOPNOTSUPP { + self.unsupported(c"interrupt notification admission"); + } else { + self.report(format_args!("interrupt {irq} refused: {refusal:?}")); + } + let Some(untouched) = refusal.returned else { + return Err(IrqEnableError::retained(EIO)); + }; + // SAFETY: actual checked prepublication return; extraction + // repeats the original process/context/provider checks. + let (source, handler, routing) = + unsafe { untouched.into_parts() }.map_err(|_| IrqEnableError::retained(EIO))?; + // Retain actual inputs before any fallible cancellation/join. + let mut source = core::mem::ManuallyDrop::new(source); + let mut handler = core::mem::ManuallyDrop::new(handler); + let stela_drivers::bus::irq::RouteRequest::Msi(route) = routing else { + return Err(IrqEnableError::retained(EIO)); + }; + route + .cancel_unattached() + .map_err(|_| IrqEnableError::retained(EIO))?; + event.begin_close(); + // SAFETY: RequestError returned actual untouched owners before + // Slot/root/source publication, so this new event has no native + // callback producer. Join still checks exact epoch/activity. + unsafe { self.environment().join_irq(&event) } + .map_err(|_| IrqEnableError::retained(EIO))?; + // SAFETY: same original process, unused route canceled and exact + // new service epoch actually joined; no C action reachability. + unsafe { + core::mem::ManuallyDrop::drop(&mut source); + core::mem::ManuallyDrop::drop(&mut handler); + } + // SAFETY: all original return/cancel/join facts above, not errno. + Err(unsafe { IrqEnableError::unexposed(errno) }) } } } - fn irq_disable(&self, irq: u32) { + fn irq_disable(&self, irq: u32) -> Result<(), Errno> { let mut lines = self.lines.borrow_mut(); - let registration = lines - .get_mut(irq as usize) - .and_then(|line| line.registration.take()); - if let Some(mut registration) = registration - && let Err(error) = registration.retire() - { - self.report(format_args!("interrupt {irq} kept: {error:?}")); - // Retirement failed, so the route stays held for the boot. - core::mem::forget(registration); + let line = lines.get_mut(irq as usize).ok_or(EINVAL)?; + match &mut line.registration { + Some(registration) => registration.mask().map_err(|_| EIO), + None => Ok(()), + } + } + fn irq_retire(&self, irq: u32) -> Result<(), Errno> { + let mut lines = self.lines.borrow_mut(); + let line = lines.get_mut(irq as usize).ok_or(EINVAL)?; + if line.retired.is_some() { + return Err(EOPNOTSUPP); + } + let Some(registration) = line.registration.as_mut() else { + return Ok(()); + }; + match registration.retire() { + Err(error) => { + self.report(format_args!("interrupt {irq} action retained: {error:?}")); + Err(EOPNOTSUPP) + } + Ok(retired) => { + // GPU has no original endpoint/entry delivery factory or + // custody transfer yet. Do not return completed free_irq from + // a future partial source implementation; keep typed owners. + line.retired = Some(retired); + Err(EOPNOTSUPP) + } } } @@ -882,7 +965,7 @@ pub(super) fn open(machine: Machine, claimed: Vec) -> Result<(), Error> #[cfg(feature = "nvk")] heap_bytes, } = machine; - let image = ReadOnlyImage::locate().ok_or(kernel_work::Error::Inventory)?; + let image = work.image()?; #[cfg(feature = "nvk")] let claiming = !claimed.is_empty(); let lines = claimed @@ -891,6 +974,7 @@ pub(super) fn open(machine: Machine, claimed: Vec) -> Result<(), Error> config: claimed.device.config.clone(), msi: claimed.device.msi, registration: None, + retired: None, }) .collect(); let bars = claimed @@ -929,7 +1013,7 @@ pub(super) fn open(machine: Machine, claimed: Vec) -> Result<(), Error> // SAFETY: one environment for the boot, on the boot CPU before any producer // or PE: the image and heap are this binary's, and the page catalog is kept. unsafe { - stela_linux::image::register(Arc::new(image)).map_err(|_| kernel_work::Error::Inventory)?; + stela_linux::image::register(image).map_err(|_| kernel_work::Error::Inventory)?; stela_linux::heap::register(allocate_zeroed).map_err(|_| kernel_work::Error::Inventory)?; let catalog = native_memory::linux_pages().map_err(|_| kernel_work::Error::Inventory)?; core::mem::forget(catalog); diff --git a/crates/stela-boot/src/engine/host.rs b/crates/stela-boot/src/engine/host.rs index 190153e49f..fdda78ba51 100644 --- a/crates/stela-boot/src/engine/host.rs +++ b/crates/stela-boot/src/engine/host.rs @@ -67,7 +67,7 @@ pub(crate) use signals::{ join_shootdown, ring, root_irq_active, shootdown, shootdown_interrupt, sleep_for, undelivered_doorbells, wake_interrupt, }; -pub use signals::{stray_interrupt, timer_interrupt}; +pub use signals::{spurious_interrupt, stray_interrupt, timer_interrupt}; #[cfg(feature = "diagnostics")] pub(crate) mod fp_diagnostic; pub(super) mod local; diff --git a/crates/stela-boot/src/engine/host/signals.rs b/crates/stela-boot/src/engine/host/signals.rs index 44e8634236..40ed128a2d 100644 --- a/crates/stela-boot/src/engine/host/signals.rs +++ b/crates/stela-boot/src/engine/host/signals.rs @@ -149,3 +149,18 @@ pub fn stray_interrupt(_vector: u8) { state.stray += 1; state.apic.eoi(); } + +/// A true APIC spurious event sets no ISR bit. A delayed ordinary fixed +/// interrupt may use the newly reserved spurious vector and still needs EOI. +/// Common entry keeps IF off, the original per-CPU APIC and this IDT/GS record +/// live; no callback/source allocation or attribution is involved. +pub fn spurious_interrupt() { + let state = state(); + let isr = state.apic.read(0x170); + if isr == u32::MAX { + crate::output::fatal("native spurious-vector ISR is unreadable"); + } + if isr & (1 << 31) != 0 { + state.apic.eoi(); + } +} diff --git a/crates/stela-boot/src/engine/interrupts.rs b/crates/stela-boot/src/engine/interrupts.rs index ed5177845c..5ad2a22c55 100644 --- a/crates/stela-boot/src/engine/interrupts.rs +++ b/crates/stela-boot/src/engine/interrupts.rs @@ -473,7 +473,7 @@ pub(crate) extern "sysv64" fn interrupt(frame: &mut Frame, saved: &SavedState<'_ TIMER_VECTOR => host::timer_interrupt(), NATIVE_WAKE_VECTOR => host::wake_interrupt(), SHOOTDOWN_VECTOR => host::shootdown_interrupt(), - SPURIOUS_VECTOR => {} + SPURIOUS_VECTOR => host::spurious_interrupt(), vector @ 32.. => host::stray_interrupt(vector), _ => fatal(frame), } diff --git a/crates/stela-boot/src/engine/kernel_work.rs b/crates/stela-boot/src/engine/kernel_work.rs index 7bd1f2d32d..3c293f7ccd 100644 --- a/crates/stela-boot/src/engine/kernel_work.rs +++ b/crates/stela-boot/src/engine/kernel_work.rs @@ -48,6 +48,7 @@ pub(crate) enum Error { Cache(MemoryError), Work(WorkError), Qualification, + Image(crate::native_image::Error), #[cfg(feature = "diagnostics")] NoKernelStacks, #[cfg(feature = "diagnostics")] @@ -68,6 +69,7 @@ impl core::fmt::Display for Error { } Self::Work(error) => write!(f, "native continuation admission: {error:?}"), Self::Qualification => f.write_str("native continuation identity or stack differs"), + Self::Image(error) => write!(f, "kernel work executable backing: {error}"), #[cfg(feature = "diagnostics")] Self::NoKernelStacks => { f.write_str("actual work pool has no Linux-compatible stack slots") @@ -81,9 +83,26 @@ struct Reservation { identity: Arc, _wire: &'static native_mmio::Wire, _handoff: &'static Handoff, + _image: crate::native_image::CodePin, allocation: native_smp::resources::AllocationClaim, released_stack_views: AtomicUsize, } +/// Immutable DATA classifier retaining this exact Queue's original image, +/// allocation and native root/table custody. This is never executable authority. +pub(super) struct ReadOnlyImage { + _reservation: Arc, + ranges: Vec>, +} +// SAFETY: only KernelWork::image constructs this value under the same actual +// kept original root. The relocated allocation and every native mapping remain +// owned by Reservation; readonly_ranges admits only original immutable DATA, +// after relocation, with no later patcher, DMA/guest loan or allocator reuse. +// contains only checks stored bounds and never dereferences a caller pointer. +unsafe impl stela_drivers::platform::image::NativeReadOnlyImage for ReadOnlyImage { + fn contains(&self, address: usize) -> bool { + self.ranges.iter().any(|range| range.contains(&address)) + } +} struct Backing { _reservation: Arc, bounds: Range, @@ -248,6 +267,16 @@ impl KernelWork { } // SAFETY: loader root, excluding task/native entry. let _root = unsafe { RestoreRoot::enter(handoff.root) }; + // SAFETY: the same validated original handoff/loader root; source + // allocation, guest exclusions and callback code stay pinned below. + let image = unsafe { handoff.native_image.pin(handoff) }.map_err(Error::Image)?; + let allocation = handoff.native_image.allocation_region(); + if !wire.loader_ram(allocation.physical, allocation.bytes) { + return Err(Error::Image(crate::native_image::Error::NotLoaderData)); + } + // SAFETY: original image/header aliases are kept and no writer runs. + unsafe { image.check_callback(Self::prepare_plan as *const () as usize) } + .map_err(Error::Image)?; let mut spans = Vec::new(); spans .try_reserve_exact(plan.count()) @@ -327,6 +356,7 @@ impl KernelWork { identity, _wire: wire, _handoff: handoff, + _image: image, allocation, released_stack_views: AtomicUsize::new(0), }); @@ -464,6 +494,23 @@ impl KernelWork { self.busy.set(false); Ok(result) } + /// Immutable native DATA from the same original relocated engine allocation + /// and root graph retained by this Queue, never a second image producer. + pub(super) fn image(&self) -> Result, Error> { + self.dispatch(|_| { + // SAFETY: dispatch entered the actual retained LoaderTables root + // on its owning BSP, excluding IRQ/native frames and table writers. + let ranges = + unsafe { self._cpu.reservation._image.readonly_ranges() }.map_err(Error::Image)?; + if ranges.is_empty() { + return Err(Error::Inventory); + } + Ok(Arc::new(ReadOnlyImage { + _reservation: self._cpu.reservation.clone(), + ranges, + })) + })? + } /// The CPU the runtime runs on. pub(super) fn cpu(&self) -> Arc { self.cpu.clone() diff --git a/crates/stela-boot/src/engine/remapping/amd.rs b/crates/stela-boot/src/engine/remapping/amd.rs index 75f1cce9b3..43906fb11e 100644 --- a/crates/stela-boot/src/engine/remapping/amd.rs +++ b/crates/stela-boot/src/engine/remapping/amd.rs @@ -483,7 +483,7 @@ unsafe impl stela_drivers::bus::pci::requester::preparation::Root for ColdRoot { unsafe fn bind( &self, binding: RequesterBinding, - ) -> Result, DmaError> + ) -> Result, DmaError> { if !on_boot_processor() || binding.address() != self.address { return Err(DmaError::IommuUnavailable); @@ -503,19 +503,38 @@ struct Attachment { // Backend detach blocks all aliases, completes invalidation and releases the // shared configuration binding only after success. Retired requesters reject // all later methods; failure/Drop keeps uncertain trees and their binding. -unsafe impl stela_drivers::bus::pci::requester::preparation::Attachment for Attachment { +unsafe impl stela_drivers::bus::pci::requester::preparation::AttachmentBackend for Attachment { + fn irq_owner( + &mut self, + _requester: &stela_drivers::bus::pci::requester::RequesterId, + _config: Option<&stela_drivers::bus::pci::owned::ConfigRetention>, + ) -> Result>, DmaError> { + // Explicit capability refusal: no original boot root/context and exact + // source grant have been supplied to this attached owner. A retained + // DMA root, SID, numeric message or fresh BDF lookup cannot mint one. + Ok(None) + } + fn domain(&self) -> Arc { self.domain.clone() } - unsafe fn detach(&mut self) -> Result<(), DmaError> { + unsafe fn detach( + &mut self, + ) -> Result<(), stela_drivers::bus::pci::requester::preparation::DetachError> { let mut inner = self.domain.inner()?; if !inner.mappings.is_empty() { - return Err(DmaError::MappingFailed); + return Err( + stela_drivers::bus::pci::requester::preparation::DetachError::Unexposed( + DmaError::MappingFailed, + ), + ); } // SAFETY: paired driver supplies halt and payload/IRQ/work drainage // under the retained root/epoch. Both mapping inventories refuse live // leases before DTE effects; wrapper inventory is empty above. - unsafe { inner.requester.detach() }.map_err(failed) + unsafe { inner.requester.detach() }.map_err(|error| { + stela_drivers::bus::pci::requester::preparation::DetachError::Uncertain(failed(error)) + }) } } diff --git a/crates/stela-boot/src/engine/remapping/preparation.rs b/crates/stela-boot/src/engine/remapping/preparation.rs index f2369e00ed..c3850d3110 100644 --- a/crates/stela-boot/src/engine/remapping/preparation.rs +++ b/crates/stela-boot/src/engine/remapping/preparation.rs @@ -1,10 +1,7 @@ //! The retained original VT-d/AMD root used during vendor cold preparation. use super::*; use alloc::boxed::Box; -use stela_drivers::bus::{ - dma::mapping::DmaError, - pci::requester::preparation::{Attachment, Root}, -}; +use stela_drivers::bus::{dma::mapping::DmaError, pci::requester::preparation::Root}; struct VtdRoot { address: Address, @@ -19,7 +16,11 @@ unsafe impl Root for VtdRoot { fn drain(&self) -> Result<(), DmaError> { self.unit.drain_initial_requester(requester(self.address)) } - unsafe fn bind(&self, binding: RequesterBinding) -> Result, DmaError> { + unsafe fn bind( + &self, + binding: RequesterBinding, + ) -> Result, DmaError> + { if binding.address() != self.address { return Err(DmaError::IommuUnavailable); } @@ -47,14 +48,42 @@ struct VtdAttachment { // the context and completes invalidation before returning its retained claim. // Old Arc references check that generation and cannot reach a replacement. // An unacknowledged domain Drop quarantines its claim, tables and unit. -unsafe impl Attachment for VtdAttachment { +unsafe impl stela_drivers::bus::pci::requester::preparation::AttachmentBackend for VtdAttachment { + fn irq_owner( + &mut self, + _requester: &stela_drivers::bus::pci::requester::RequesterId, + _config: Option<&stela_drivers::bus::pci::owned::ConfigRetention>, + ) -> Result>, DmaError> { + // Explicit component prerequisite. The separate native producer delta + // consumes the actual original all-unit mode/root owner and actual + // source pairing; no numeric/BDF observer or empty success replaces it. + Ok(None) + } + fn domain(&self) -> Arc { self.domain.clone() } - unsafe fn detach(&mut self) -> Result<(), DmaError> { + unsafe fn detach( + &mut self, + ) -> Result<(), stela_drivers::bus::pci::requester::preparation::DetachError> { // SAFETY: caller supplies current-epoch quiescence and payload/IRQ/work // drains with original owners kept. Backend refuses live mappings // before context effects. + // This metadata-only preflight precedes every hardware effect. Actual + // detach failures below are all uncertain, regardless of error variant. + if self + .domain + .has_live_mappings() + .map_err(stela_drivers::bus::pci::requester::preparation::DetachError::Unexposed)? + { + return Err( + stela_drivers::bus::pci::requester::preparation::DetachError::Unexposed( + DmaError::MappingFailed, + ), + ); + } + // SAFETY: caller retains the quiesced current epoch and joined IRQ/work; + // the preflight above ruled out live payload mappings before detach. let claim = unsafe { self.domain.detach() }.map_err(|error| { output::arguments(format_args!( "HOST IOMMU VT-d detach {} refused: {error:?}\n", diff --git a/crates/stela-boot/src/engine/start.rs b/crates/stela-boot/src/engine/start.rs index bbff99dc2a..f9c255c656 100644 --- a/crates/stela-boot/src/engine/start.rs +++ b/crates/stela-boot/src/engine/start.rs @@ -1844,6 +1844,13 @@ fn install_host(handoff: &'static Handoff, options: &Options, ram: &[RamRange]) } #[cfg(feature = "diagnostics")] if options.native_mmio_check { + // No original notification-domain producer is composed at this caller. + // Refuse before mixed/MMIO/clock/IOAPIC qualification effects; only an + // actual same-handoff product may replace this explicit missing input. + let notification = crate::native_mmio::diagnostic::require_notification_owner(None) + .unwrap_or_else(|_| { + output::fatal("native MMIO original notification owner unavailable") + }); // SAFETY: this explicit UP entry owns the task pool for the boot it // stops. It retires every view before the MMIO phases and never // activates a second permission or publishes a service. @@ -1854,12 +1861,11 @@ fn install_host(handoff: &'static Handoff, options: &Options, ram: &[RamRange]) // SAFETY: explicit bounded native diagnostic on the original kept // handoff/owner. Success stops before guest entry; permanent mapping // and IRQ registries keep this exact physical root until VM shutdown. - unsafe { crate::native_mmio::diagnostic::check(handoff, &mut host_owner) }.unwrap_or_else( - |error| { + unsafe { crate::native_mmio::diagnostic::check(handoff, &mut host_owner, notification) } + .unwrap_or_else(|error| { output::arguments(format_args!("CHECK native-mmio FAIL {error:?}\n")); output::fatal("native MMIO root qualification failed") - }, - ); + }); stop_here("native MMIO root qualification complete", 0x10); } InstalledHost { diff --git a/crates/stela-boot/src/handoff.rs b/crates/stela-boot/src/handoff.rs index 8b183c3c75..b6f47340d6 100644 --- a/crates/stela-boot/src/handoff.rs +++ b/crates/stela-boot/src/handoff.rs @@ -85,6 +85,9 @@ pub struct Handoff { pub(crate) native_task_allocations: crate::native_smp::resources::TaskAllocations, /// Original loader table allocations; root is only their copied descriptor. pub(crate) native_loader_tables: crate::paging::loader::LoaderTables, + /// Moved original allocation of the relocated static Rust/C engine image. + /// Observed PE/header ranges cannot recreate this non-Clone owner. + pub(crate) native_image: crate::native_image::ResidentImage, } /// A read of the firmware's real-time clock: its time as UTC and its diff --git a/crates/stela-boot/src/main.rs b/crates/stela-boot/src/main.rs index edfce6d054..fafd267142 100644 --- a/crates/stela-boot/src/main.rs +++ b/crates/stela-boot/src/main.rs @@ -47,6 +47,7 @@ mod log_file; pub(crate) mod native_clock; pub mod native_dma; mod native_idle; +mod native_image; pub mod native_irq; pub mod native_memory; #[expect( diff --git a/crates/stela-boot/src/native_image.rs b/crates/stela-boot/src/native_image.rs new file mode 100644 index 0000000000..2b90d41128 --- /dev/null +++ b/crates/stela-boot/src/native_image.rs @@ -0,0 +1,211 @@ +//! Original allocation owner of the relocated, statically linked engine image. +//! Range observations and read-only data classifiers cannot construct this pin. +use crate::{ + handoff::{Handoff, Region}, + layout, +}; +use stela_boot_core::{pe, resident_image::Layout}; +use uefi::boot::{self, AllocateType, MemoryType}; + +pub(crate) enum Error { + Allocation(uefi::Status), + Geometry(stela_boot_core::resident_image::Error), + Overflow, + ForeignHandoff, + ExposedAllocation, + Header(crate::Refusal), + ForeignCode, + NotLoaderData, +} +impl core::fmt::Debug for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Allocation(status) => f.debug_tuple("Allocation").field(status).finish(), + Self::Geometry(error) => f.debug_tuple("Geometry").field(error).finish(), + Self::Header(error) => f.debug_tuple("Header").field(error).finish(), + Self::Overflow => f.write_str("Overflow"), + Self::ForeignHandoff => f.write_str("ForeignHandoff"), + Self::ExposedAllocation => f.write_str("ExposedAllocation"), + Self::ForeignCode => f.write_str("ForeignCode"), + Self::NotLoaderData => f.write_str("NotLoaderData"), + } + } +} +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "resident kernel image: {self:?}") + } +} + +/// Created only by the successful UEFI allocation below. No public raw-range +/// constructor, Clone, free or retarget operation exists. The complete allocation, +/// including alignment padding, remains LoaderData for the whole boot. +struct Allocation { + physical: u64, + bytes: u64, +} + +pub(crate) struct ResidentImage { + _allocation: Allocation, + geometry: Layout, + image_bytes: usize, +} +impl ResidentImage { + pub(crate) fn allocate(image_bytes: usize, virtual_base: u64) -> Result { + const ALIGNMENT: u64 = 2 * 1024 * 1024; + if image_bytes == 0 + || image_bytes > isize::MAX as usize + || !virtual_base.is_multiple_of(4096) + { + return Err(Error::Geometry( + stela_boot_core::resident_image::Error::Geometry, + )); + } + let bytes = (image_bytes as u64) + .checked_add(ALIGNMENT) + .and_then(|bytes| bytes.checked_next_multiple_of(4096)) + .ok_or(Error::Overflow)?; + let pages = usize::try_from(bytes / 4096).map_err(|_| Error::Overflow)?; + let page = boot::allocate_pages(AllocateType::AnyPages, MemoryType::LOADER_DATA, pages) + .map_err(|error| Error::Allocation(error.status()))?; + // SAFETY: successful fresh firmware allocation owns exactly bytes; + // zero padding before copying prevents exposing former RAM contents. + unsafe { page.as_ptr().write_bytes(0, bytes as usize) }; + let allocation = Allocation { + physical: page.as_ptr() as u64, + bytes, + }; + let geometry = Layout::within( + allocation.physical + ..allocation + .physical + .checked_add(allocation.bytes) + .ok_or(Error::Overflow)?, + image_bytes, + ALIGNMENT, + virtual_base, + ) + .map_err(Error::Geometry)?; + Ok(Self { + _allocation: allocation, + geometry, + image_bytes, + }) + } + /// Observation only, used to copy/relocate/map this same owned allocation. + pub(crate) fn region(&self) -> Region { + let span = self.geometry.physical(); + Region { + physical: span.start, + bytes: span.end - span.start, + } + } + pub(crate) fn allocation_region(&self) -> Region { + Region { + physical: self._allocation.physical, + bytes: self._allocation.bytes, + } + } + /// Pin the same original allocation under the final immutable handoff. + /// + /// # Safety + /// On the validated actual CPU under an owned native root. Its real kept + /// RootIdentity/LoaderTables graph maps this exact original copied PE at + /// its geometry virtual alias with the original PE section permissions. + /// Its retained WB physical observation alias may be privileged RW/NX; + /// exclusive allocation custody forbids mutation through that alias after + /// relocation of headers, code or immutable DATA. No patcher, DMA/guest + /// loan, allocator reuse or root writer changes those bytes or this epoch. + /// The root may be the original loader root or its actually owned shared + /// native projection. Numeric CR3/ranges alone are insufficient; this pin + /// conveys allocation custody, never CPU/root/cache access permission. + /// The final guest inventory excludes all LoaderCode/LoaderData allocations. + pub(crate) unsafe fn pin(&'static self, handoff: &'static Handoff) -> Result { + if !core::ptr::eq(self, &handoff.native_image) + || self.geometry.virtual_range().start != layout::image() + || handoff.guest_count > handoff.guest.len() + { + return Err(Error::ForeignHandoff); + } + let regions = handoff.guest[..handoff.guest_count].iter().chain([ + &handoff.heap, + &handoff.stack, + &handoff.code, + &handoff.pool, + &handoff.native_resources.tasks, + ]); + for region in regions { + let end = region + .physical + .checked_add(region.bytes) + .ok_or(Error::Overflow)?; + if region.bytes != 0 && self.geometry.overlaps(region.physical..end) { + return Err(Error::ExposedAllocation); + } + } + Ok(CodePin { image: self }) + } +} + +/// Retains the original allocation object in the same never-freed handoff. +/// The queue separately keeps the exact loader/root mappings and CPU owner. +#[derive(Clone)] +pub(crate) struct CodePin { + image: &'static ResidentImage, +} +impl CodePin { + /// Original immutable, non-executable PE sections, observed under the same + /// kept native root. These observations alone never create code authority. + /// + /// # Safety + /// Same original immutable-header/root contract as check_callback. + pub(crate) unsafe fn readonly_ranges( + &self, + ) -> Result>, Error> { + let physical = self.image.geometry.physical().start; + let base = layout::physical(physical) as *const u8; + let sections = pe::sections(self.image.image_bytes, |offset, out| { + // SAFETY: the parser bounds every read within this same real image. + unsafe { + core::ptr::copy_nonoverlapping(base.add(offset), out.as_mut_ptr(), out.len()) + }; + }) + .map_err(Error::Header)?; + let virtual_base = self.image.geometry.virtual_range().start as usize; + Ok(sections + .into_iter() + .filter(|section| !section.writable && !section.executable) + .map(|section| (virtual_base + section.first)..(virtual_base + section.end)) + .collect()) + } + /// Check an actual callback lies in this image's original executable section. + /// This does not grant arbitrary code-loading or user execution permission. + /// + /// # Safety + /// Same kept original CPU/root/immutable-header contract as ResidentImage::pin. + pub(crate) unsafe fn check_callback(&self, address: usize) -> Result<(), Error> { + let virtual_range = self.image.geometry.virtual_range(); + let offset = (address as u64) + .checked_sub(virtual_range.start) + .filter(|offset| *offset < self.image.image_bytes as u64) + .ok_or(Error::ForeignCode)? as usize; + let physical = self.image.geometry.physical().start; + let base = layout::physical(physical) as *const u8; + let sections = pe::sections(self.image.image_bytes, |offset, out| { + // SAFETY: pe::sections bounds each short read within the exact + // original image allocation, without borrowing writable statics. + unsafe { + core::ptr::copy_nonoverlapping(base.add(offset), out.as_mut_ptr(), out.len()) + }; + }) + .map_err(Error::Header)?; + if sections + .iter() + .any(|section| section.executable && section.first <= offset && offset < section.end) + { + Ok(()) + } else { + Err(Error::ForeignCode) + } + } +} diff --git a/crates/stela-boot/src/native_irq.rs b/crates/stela-boot/src/native_irq.rs index 583c917ed0..90de6f4ad3 100644 --- a/crates/stela-boot/src/native_irq.rs +++ b/crates/stela-boot/src/native_irq.rs @@ -9,7 +9,7 @@ use core::{ arch::asm, sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, AtomicU64, Ordering}, }; -use stela_drivers::bus::irq::{IrqController, IrqError, Platform, Registry, Target}; +use stela_drivers::bus::irq::{IrqController, IrqError, Platform, Registry, Target, Trigger}; use stela_drivers::platform::work::Cpu; use stela_boot_core::crs; @@ -146,6 +146,19 @@ fn id(apic: &Apic) -> Result { Ok(if apic.is_x2apic() { raw } else { raw >> 24 }) } +fn in_service_vector(apic: &Apic) -> Result, IrqError> { + for bank in (0..8u32).rev() { + let bits = apic.read(0x100 + bank * 16); + if bits == u32::MAX { + return Err(IrqError::FailedRead); + } + if bits != 0 { + return Ok(Some((bank * 32 + 31 - bits.leading_zeros()) as u8)); + } + } + Ok(None) +} + /// Attach the existing, already enabled APIC and installed device-vector IDT. /// /// # Safety @@ -239,6 +252,21 @@ unsafe impl Platform for NativePlatform { } Ok(()) } + fn check_process(&self) -> Result<(), IrqError> { + self.check_cpu()?; + if current_context()?.is_some() { + return Err(IrqError::WrongCpu); + } + if let Some(cpu) = root_cpu() { + cpu.check_cpu().map_err(|_| IrqError::WrongCpu)?; + if cpu.in_interrupt() { + return Err(IrqError::WrongCpu); + } + } + // Without root_adapter this is only the original explicit early boot + // diagnostic grant; it creates no remapper/native delivery capability. + Ok(()) + } fn save_and_disable(&self) -> u64 { let saved; // SAFETY: native privileged CPU; memory clobber orders the critical @@ -275,8 +303,31 @@ unsafe impl Platform for NativePlatform { } Ok((irr | isr) & (1u32 << (vector % 32)) != 0) } - fn eoi(&self) { - controller().eoi(); + fn eoi(&self, vector: u8) -> Result { + self.check_cpu()?; + let apic = controller(); + // EOI removes the highest-priority ISR bit, not a caller-selected + // vector. A process/debug dispatch or nested lower-vector call must + // never acknowledge somebody else's still-active interrupt. + if in_service_vector(&apic)? != Some(vector) { + return Err(IrqError::Drain); + } + let tmr = apic.read(0x180 + u32::from(vector / 32) * 16); + let spurious = apic.read(apic::SPURIOUS); + // Read TMR before local EOI. Even a changed broadcast policy cannot + // justify leaving this actual in-service interrupt unacknowledged. + apic.eoi(); + if tmr == u32::MAX || spurious == u32::MAX { + return Err(IrqError::FailedRead); + } + if spurious & (1 << 12) != 0 { + return Err(IrqError::Unsupported); + } + Ok(if tmr & (1u32 << (vector % 32)) == 0 { + Trigger::Edge + } else { + Trigger::Level + }) } fn ticks(&self) -> u64 { root_cpu().map_or_else(apic::rdtsc, |cpu| cpu.ticks()) diff --git a/crates/stela-boot/src/native_irq/diagnostic.rs b/crates/stela-boot/src/native_irq/diagnostic.rs index 9b87fce6aa..9df7869978 100644 --- a/crates/stela-boot/src/native_irq/diagnostic.rs +++ b/crates/stela-boot/src/native_irq/diagnostic.rs @@ -1,6 +1,6 @@ //! EDU MSI lifecycle under the source-bound QEMU TCG fixture grant. use crate::Result; -use alloc::{format, string::String, sync::Arc}; +use alloc::{boxed::Box, format, string::String, sync::Arc}; use core::{ arch::asm, sync::atomic::{AtomicU32, AtomicU64, Ordering}, @@ -9,7 +9,11 @@ use stela_contracts::refuse; use stela_drivers::{ Clock, bus::{ - irq::{Disposition, Handler, IrqError, Route, RouteRequest, Source}, + irq::{ + CpuTarget, Disposition, Handler, IrqError, MsiMessage, Platform, Request, Route, + RouteRequest, Source, + posted_msi::{self, AllocationError, EndpointRetirement, MsiRoute, RouteOwner}, + }, pci::{ConfigSpace, Function as PciFunction, Msi, owned::OwnedConfig}, }, }; @@ -65,6 +69,110 @@ impl Handler for Edu { } } +/// Only this existing boot-diagnostics module can issue the bounded TCG +/// contract. It has no RequesterId, config pin, or native detach/reset proof. +struct TcgDomain { + edu: Arc, +} +// SAFETY: issued only inside the existing exact single-BSP synchronous TCG +// fixture. Actual CPU and original retained EDU identity are checked on IRQ. +unsafe impl posted_msi::NotificationDomain for TcgDomain { + fn check(&self) -> core::result::Result<(), posted_msi::Error> { + super::NativePlatform(()) + .check_cpu() + .map_err(|_| posted_msi::Error::Context)?; + if self.edu.read(0) != 0x0100_00ed { + return Err(posted_msi::Error::RootFailed); + } + Ok(()) + } +} +struct TcgDelivery { + edu: Arc, + message: Option, +} +impl TcgDelivery { + fn check(&self) -> core::result::Result<(), posted_msi::Error> { + super::NativePlatform(()) + .check_process() + .map_err(|_| posted_msi::Error::Context)?; + // Read actual exact retained EDU registers, never infer delivery from + // an unrelated source's idle or a generic all-success provider. + if self.edu.read(0) != 0x0100_00ed { + return Err(posted_msi::Error::RootFailed); + } + Ok(()) + } +} +// SAFETY: private diagnostics issuer is reached only after the original exact +// single-BSP synchronous TCG EDU fixture contract and VT-d shutdown. The owned +// EDU peer checks its actual stopped state; this is model evidence only. +unsafe impl RouteOwner for TcgDelivery { + fn allocate( + &mut self, + target: &CpuTarget<'_>, + ) -> core::result::Result { + self.check().map_err(AllocationError::Unexposed)?; + if !target.belongs_to(super::CONTROLLER.identity()) { + return Err(AllocationError::Unexposed(posted_msi::Error::Context)); + } + target + .check_current() + .map_err(|_| AllocationError::Unexposed(posted_msi::Error::Context))?; + let data = target.descriptor(); + let message = MsiMessage { + address: 0xfee0_0000 | u64::from(data.destination) << 12, + data: u32::from(data.vector), + }; + if self.message.is_some() { + return Err(AllocationError::Unexposed(posted_msi::Error::AlreadyBound)); + } + self.message = Some(message); + Ok(message) + } + fn validate(&self) -> core::result::Result<(), posted_msi::Error> { + self.check() + } + fn notification_domain( + &self, + ) -> core::result::Result, posted_msi::Error> { + self.check()?; + Ok(Arc::new(TcgDomain { + edu: self.edu.clone(), + })) + } + unsafe fn strong_fence(&mut self) -> core::result::Result<(), posted_msi::Error> { + self.check()?; + if self.message.is_none() + || !self.edu.dma_idle() + || self.edu.read(0x20) & 1 != 0 + || self.edu.read(0x24) != 0 + { + return Err(posted_msi::Error::RootFailed); + } + // Under this exact synchronous TCG device contract, stopped RUN/DMA + // and acknowledged causes exclude another queued EDU callback. + Ok(()) + } + unsafe fn release_endpoint( + &mut self, + proof: &EndpointRetirement<'_>, + ) -> core::result::Result<(), posted_msi::Error> { + self.check()?; + if proof.requester().is_some() { + return Err(posted_msi::Error::NotRetired); + } + Ok(()) + } +} +pub(super) fn tcg_route(edu: Arc) -> RouteRequest { + // SAFETY: module-private issuer of this exact diagnostics contract, never + // an attachment grant or a native platform service. + RouteRequest::Msi(unsafe { + MsiRoute::bounded_fixture(Box::new(TcgDelivery { edu, message: None })) + }) +} + pub(super) struct EduSource { pub(super) function: Function, msi: Msi, @@ -127,14 +235,20 @@ unsafe impl Source for EduSource { } Ok(()) } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> stela_drivers::bus::irq::RouteKind { + stela_drivers::bus::irq::RouteKind::Msi + } + fn requester(&self) -> Option<&stela_drivers::bus::pci::requester::RequesterId> { + None } unsafe fn synchronize(&mut self) -> Result<(), IrqError> { self.quiesce() } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { - let Route::Msi(message) = route else { + unsafe fn program( + &mut self, + route: &stela_drivers::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { + let Route::Msi(message) = route.programming() else { return Err(IrqError::Route); }; if self.control() & 1 != 0 @@ -247,7 +361,11 @@ pub(super) fn prepare_source(function: Function, base: u64, clock: Clock) -> Res pub(crate) fn run(function: Function, base: u64, clock: Clock) -> Result<(String, Function)> { let Parts { source, edu } = prepare_source(function, base, clock)?; let mut registration = super::CONTROLLER - .request_owned(source, edu.clone()) + .request_owned(Request { + source, + handler: edu.clone(), + routing: tcg_route(edu.clone()), + }) .map_err(|error| refuse!("EDU MSI request: {error}", ?error))?; let vector = registration.vector(); // No heap/resource lock is held. The real IDT handler acknowledges the @@ -288,7 +406,14 @@ pub(crate) fn run(function: Function, base: u64, clock: Clock) -> Result<(String // configuration/root owner is introduced by the following INTx phase. // SAFETY: concrete source owns the stopped EDU/Function. Keep its original // callback owner until the source is consumed immediately below. - let (source, handler, _route) = unsafe { retired.into_parts() }; + let (source, handler, mut route) = unsafe { retired.into_parts() }.map_err(|failure| { + let error = failure.error; + refuse!("EDU retirement context changed: {error}", ?error) + })?; + route + .release_unattached_fixture() + .map_err(|e| refuse!("EDU bounded route release: {e}", ?e))?; + drop(route); let EduSource { function, msi: _, diff --git a/crates/stela-boot/src/native_irq/level_diagnostic.rs b/crates/stela-boot/src/native_irq/level_diagnostic.rs index 95852b3380..6c52ec5e7a 100644 --- a/crates/stela-boot/src/native_irq/level_diagnostic.rs +++ b/crates/stela-boot/src/native_irq/level_diagnostic.rs @@ -52,6 +52,19 @@ const LINE: LineRoute = LineRoute { polarity: Polarity::High, trigger: Trigger::Level, }; +/// Source-bound diagnostic admission only; never a NativeServices producer. +struct FixtureDomain; +// SAFETY: constructed only inside the previously independently validated +// single-BSP Q35/TCG SMM-off fixture, retaining its boot-owned root/APIC/IDT +// and unchanging non-remapped IOAPIC interpretation for this bounded run. +unsafe impl stela_drivers::bus::irq::posted_msi::NotificationDomain for FixtureDomain { + fn check(&self) -> core::result::Result<(), stela_drivers::bus::irq::posted_msi::Error> { + super::NativePlatform(()) + .check_cpu() + .map_err(|_| stela_drivers::bus::irq::posted_msi::Error::Context) + } +} + const INTX_DISABLE: u16 = 1 << 10; type Io = ioapic::Unit; @@ -154,9 +167,17 @@ impl Prepared { .map_err(|e| refuse!("IOAPIC mapping: {e}", ?e))?; // SAFETY: exact previously checked Q35 single-BSP fixture, kept // UC IOAPIC page, EOI broadcast on, no firmware/SMM/other owner. - let unit = - unsafe { ioapic::Unit::attach(registers, platform, self.unit.id, self.unit.gsi_base) } - .map_err(|e| refuse!("IOAPIC attach: {e}", ?e))?; + let unit = unsafe { + ioapic::Unit::attach( + registers, + platform, + Arc::new(FixtureDomain), + super::CONTROLLER.identity(), + self.unit.id, + self.unit.gsi_base, + ) + } + .map_err(|e| refuse!("IOAPIC attach: {e}", ?e))?; self.routing .owner(LINE, &[(self.unit, unit.pins())]) .map_err(|e| refuse!("live IOAPIC GSI owner: {e}", ?e))?; @@ -208,7 +229,11 @@ impl Prepared { .map_err(|e| refuse!("IOAPIC line claim: {e}", ?e))?; let mut registration = super::service() .map_err(|e| refuse!("level service: {e}", ?e))? - .request(Box::new(pin), handlers.clone()) + .request(stela_drivers::bus::irq::Request { + source: Box::new(pin), + handler: handlers.clone(), + routing: stela_drivers::bus::irq::RouteRequest::Line(LINE), + }) .map_err(|e| refuse!("level request: {e}", ?e))?; let vector = registration.vector(); // SAFETY: the level handler group is registered and interrupts are masked again right after @@ -244,9 +269,17 @@ impl Prepared { handled = ?registration.handled() )); } - registration + let retired = registration .retire() .map_err(|e| refuse!("level retirement: {e}", ?e))?; + // SAFETY: exact line retirement succeeded on its owner CPU; source precedes callback. + let (source, callback, route) = unsafe { retired.into_parts() }.map_err(|failure| { + let error = failure.error; + refuse!("line owner context changed: {error}", ?error) + })?; + drop(source); + drop(callback); + drop(route); let state = unit .state(LINE.gsi) .map_err(|e| refuse!("retired IOAPIC: {e}", ?e))?; diff --git a/crates/stela-boot/src/native_irq/root.rs b/crates/stela-boot/src/native_irq/root.rs index c25a29db12..d40de5a705 100644 --- a/crates/stela-boot/src/native_irq/root.rs +++ b/crates/stela-boot/src/native_irq/root.rs @@ -59,6 +59,9 @@ unsafe impl ioapic::Registers for Registers { fn write(&self, index: u8, value: u32) { ioapic::Registers::write(&self.mmio, index, value); } + fn write_eoi(&self, vector: u8) { + ioapic::Registers::write_eoi(&self.mmio, vector); + } } impl Drop for Registers { fn drop(&mut self) { @@ -133,7 +136,11 @@ impl Root { execution: &crate::native_clock::DriverExecution<'_>, authority: &Authority, madt: &'static [u8], + domain: Arc, ) -> Result { + domain + .check() + .map_err(|error| Error::Irq(IrqError::Delivery(error)))?; let scope = execution.process_scope().map_err(Error::Cpu)?; let cpu = scope.cpu().map_err(Error::Cpu)?; // SAFETY: complete external-controller/main handoff is required @@ -159,7 +166,7 @@ impl Root { let mut mapping = authority .map_physical(physical, CacheAttribute::Uncached, Protection::ReadWrite) .map_err(Error::Mapping)?; - let address = match mapping.address(0, 32) { + let address = match mapping.address(0, 68) { Ok(address) => address.as_ptr() as usize, Err(error) => { // SAFETY: No IOAPIC access or published source has occurred. @@ -181,6 +188,8 @@ impl Root { ioapic::Unit::attach( registers, NativePlatform(()), + domain.clone(), + super::CONTROLLER.identity(), descriptor.id, descriptor.gsi_base, ) diff --git a/crates/stela-boot/src/native_irq/work_diagnostic.rs b/crates/stela-boot/src/native_irq/work_diagnostic.rs index 19a802c804..e8d9836beb 100644 --- a/crates/stela-boot/src/native_irq/work_diagnostic.rs +++ b/crates/stela-boot/src/native_irq/work_diagnostic.rs @@ -16,7 +16,7 @@ use stela_contracts::refuse; use stela_drivers::{ Clock, bus::{ - irq::{Disposition, Handler, IrqError, Platform, Route, RouteRequest, Source}, + irq::{Disposition, Handler, IrqError, Platform, Source}, pci::{Function as PciFunction, owned::OwnedConfig}, }, platform::work::{Cpu, Executor, Kind, Queue, WorkError}, @@ -166,10 +166,16 @@ unsafe impl Source for WorkSource { fn mask(&mut self) -> Result<(), IrqError> { self.inner.mask() } - fn route(&self) -> RouteRequest { - self.inner.route() + fn route_kind(&self) -> stela_drivers::bus::irq::RouteKind { + self.inner.route_kind() } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { + fn requester(&self) -> Option<&stela_drivers::bus::pci::requester::RequesterId> { + self.inner.requester() + } + unsafe fn program( + &mut self, + route: &stela_drivers::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { // SAFETY: forwards the registry's own call under the same contract. unsafe { self.inner.program(route) } } @@ -399,7 +405,11 @@ pub(crate) fn run( clock, }); let mut registration = super::CONTROLLER - .request_owned(*source, handler.clone()) + .request_owned(stela_drivers::bus::irq::Request { + source: *source, + handler: handler.clone(), + routing: super::diagnostic::tcg_route(parts.edu.clone()), + }) .map_err(|e| refuse!("IRQ work request: {e}", ?e))?; let vector = registration.vector(); // Dispatcher permits MSI progress. All callbacks run @@ -457,7 +467,15 @@ pub(crate) fn run( .map_err(|e| refuse!("IRQ work mask/synchronize/drain: {e}", ?e))?; // SAFETY: route+callback+work drain just completed on this BSP; // keep returned callback while consuming its original concrete source. - let (source, returned_handler, _route) = unsafe { retired.into_parts() }; + let (source, returned_handler, mut route) = + unsafe { retired.into_parts() }.map_err(|failure| { + let error = failure.error; + refuse!("IRQ work retirement context changed: {error}", ?error) + })?; + route + .release_unattached_fixture() + .map_err(|e| refuse!("IRQ work bounded route release: {e}", ?e))?; + drop(route); let WorkSource { inner, executor: source_executor, diff --git a/crates/stela-boot/src/native_mmio/diagnostic.rs b/crates/stela-boot/src/native_mmio/diagnostic.rs index 0ca31d9992..de653cb4f1 100644 --- a/crates/stela-boot/src/native_mmio/diagnostic.rs +++ b/crates/stela-boot/src/native_mmio/diagnostic.rs @@ -171,13 +171,41 @@ unsafe fn check_native_hpet(handoff: &Handoff, owner: &mut HostOwner) -> Result< Ok(()) } +/// Require an already genuine caller-owned notification domain. This checks +/// presence/liveness only; it creates no domain, ownership or history grant. +pub(crate) fn require_notification_owner( + notification: Option< + alloc::sync::Arc, + >, +) -> Result, Error> { + let notification = stage( + "original-notification-owner", + notification.ok_or(Error::Unavailable), + )?; + if let Err(error) = notification.check() { + crate::output::arguments(format_args!( + "CHECK native-mmio REFUSED stage=notification-domain error={error:?}\n" + )); + return Err(Error::Unavailable); + } + Ok(notification) +} + /// # Safety /// Explicit native diagnostic owns this post-EBS BSP, all controller /// resources and the complete original HPET/LAPIC source. No firmware, SMM, /// other CPU or legacy driver owns or accesses HPET control/counter/comparator/ /// decode/route state or IOAPIC/ECAM during the kernel-image epoch. Caller stops the boot immediately afterward, preserving the /// permanently installed Permission/IRQ/clock's physical root owner. -pub(crate) unsafe fn check(handoff: &Handoff, owner: &mut HostOwner) -> Result<(), Error> { +/// `notification` is the actual retained original CPU/root/controller-format +/// owner for this SAME handoff. Table/map/timed-CPU data never constructs it. +pub(crate) unsafe fn check( + handoff: &Handoff, + owner: &mut HostOwner, + notification: alloc::sync::Arc, +) -> Result<(), Error> { + // A checked real input is required even for direct diagnostic callers. + let notification = require_notification_owner(Some(notification))?; if handoff.native_resources.cores != 1 || handoff.storage.present { return Err(Error::Unavailable); } @@ -218,7 +246,12 @@ pub(crate) unsafe fn check(handoff: &Handoff, owner: &mut HostOwner) -> Result<( "irq-root-attach", // SAFETY: the driver execution owns interrupt delivery and the claimed IOAPICs. unsafe { - crate::native_irq::root::Root::attach(&execution, source.authority(), source.madt()) + crate::native_irq::root::Root::attach( + &execution, + source.authority(), + source.madt(), + notification, + ) } .map_err(|error| { crate::output::arguments(format_args!( diff --git a/crates/stela-boot/src/native_mmio/shared.rs b/crates/stela-boot/src/native_mmio/shared.rs index cc27a607a2..ab45890583 100644 --- a/crates/stela-boot/src/native_mmio/shared.rs +++ b/crates/stela-boot/src/native_mmio/shared.rs @@ -379,6 +379,7 @@ pub(crate) struct Source { /// Each claimed ECAM bus, by its window and bus. buses: core::cell::RefCell>, ioapics: core::cell::RefCell)>>, + irq_domain: Option>, } impl Source { @@ -502,6 +503,7 @@ impl Source { window, buses: core::cell::RefCell::new(Vec::new()), ioapics: core::cell::RefCell::new(Vec::new()), + irq_domain: None, }) } @@ -699,6 +701,9 @@ unsafe impl crate::native_irq::ioapic::Registers for IoapicRegisters { fn write(&self, index: u8, value: u32) { crate::native_irq::ioapic::Registers::write(&self.mmio, index, value); } + fn write_eoi(&self, vector: u8) { + crate::native_irq::ioapic::Registers::write_eoi(&self.mmio, vector); + } } impl Drop for IoapicRegisters { fn drop(&mut self) { @@ -719,6 +724,10 @@ pub(crate) type IoapicUnit = crate::native_irq::ioapic::Unit; impl Source { + // Positive PCI mode ownership does not supply original IOAPIC/RTE custody. + // A separate real line-controller producer is required before this domain + // can be installed; current Line/SCI admission stays unavailable. + /// Reuse this source's one selector/window owner and UC mapping. /// /// # Safety @@ -728,6 +737,16 @@ impl Source { &self, descriptor: crate::native_irq::madt::Unit, ) -> Result, Error> { + self.identity.check_current().map_err(failed)?; + if self.identity.in_interrupt() { + return Err(Error::Busy); + } + let domain = self + .irq_domain + .as_ref() + .cloned() + .ok_or(Error::Unavailable)?; + domain.check().map_err(failed)?; if let Some((_, unit)) = self .ioapics .borrow() @@ -756,7 +775,7 @@ impl Source { CacheAttribute::Uncached, Protection::ReadWrite, )?; - let address = mapping.address(0, 32)?.as_ptr() as usize; + let address = mapping.address(0, 68)?.as_ptr() as usize; // SAFETY: exclusive all-root UC mapping of the MADT controller page. let mmio = unsafe { crate::native_irq::ioapic::Mmio::new(address) }.map_err(failed)?; let registers = IoapicRegisters { @@ -765,9 +784,17 @@ impl Source { }; let platform = crate::native_irq::NativePlatform::current().map_err(failed)?; // SAFETY: mapping and complete exclusive controller handoff above. - let unit = - unsafe { IoapicUnit::attach(registers, platform, descriptor.id, descriptor.gsi_base) } - .map_err(failed)?; + let unit = unsafe { + IoapicUnit::attach( + registers, + platform, + domain, + crate::native_irq::CONTROLLER.identity(), + descriptor.id, + descriptor.gsi_base, + ) + } + .map_err(failed)?; self.ioapics.borrow_mut().push((descriptor, unit.clone())); Ok(unit) } diff --git a/crates/stela-boot/src/system.rs b/crates/stela-boot/src/system.rs index 11fbcbcf15..4b95fe51dc 100644 --- a/crates/stela-boot/src/system.rs +++ b/crates/stela-boot/src/system.rs @@ -712,6 +712,7 @@ fn load( placement, screen, apic_base, + resident, .. } = image; let memory::EngineMemory { @@ -842,6 +843,7 @@ fn load( }, native_task_allocations, native_loader_tables: loader_tables, + native_image: resident, }); } // SAFETY: boot services ended; the completed root maps this code and diff --git a/crates/stela-boot/src/system/memory.rs b/crates/stela-boot/src/system/memory.rs index 50069cf4ea..9775f45fae 100644 --- a/crates/stela-boot/src/system/memory.rs +++ b/crates/stela-boot/src/system/memory.rs @@ -18,6 +18,7 @@ pub(super) struct EngineImage { pub snapshot: Snapshot, pub image: firmware::Image, pub engine: Region, + pub resident: crate::native_image::ResidentImage, pub ram: Vec<(usize, usize)>, pub screen: Option, pub apic_base: u64, @@ -47,15 +48,6 @@ pub(super) fn prepare_image() -> Result { if image.start != snapshot.start || image.end - image.start != snapshot.bytes { return Err(refuse!("image layout changed after the snapshot")); } - let engine = allocate_large(snapshot.bytes as u64)?; - // SAFETY: two distinct live allocations of `bytes`. - unsafe { - core::ptr::copy_nonoverlapping( - snapshot.copy as *const u8, - engine.physical as *mut u8, - snapshot.bytes, - ); - } let ram = firmware::ram()?; let screen = Framebuffer::from_firmware(); let apic_base = crate::apic::base_msr(); @@ -72,6 +64,18 @@ pub(super) fn prepare_image() -> Result { "host physical addresses lie beyond what any placement's physmap reaches" ))?; layout::set(placement); + let resident = crate::native_image::ResidentImage::allocate(snapshot.bytes, layout::image()) + .map_err(|error| refuse!("engine image allocation failed", %error))?; + let engine = resident.region(); + // SAFETY: the pristine source and the newly owned, zeroed image allocation + // are distinct and each covers exactly snapshot.bytes. + unsafe { + core::ptr::copy_nonoverlapping( + snapshot.copy as *const u8, + engine.physical as *mut u8, + snapshot.bytes, + ); + } relocate( engine.physical as usize, snapshot.bytes, @@ -81,6 +85,7 @@ pub(super) fn prepare_image() -> Result { snapshot, image, engine, + resident, ram, screen, apic_base, diff --git a/crates/stela-driver-base/Cargo.toml b/crates/stela-driver-base/Cargo.toml index e8047e4b44..d8b968cfbd 100644 --- a/crates/stela-driver-base/Cargo.toml +++ b/crates/stela-driver-base/Cargo.toml @@ -18,6 +18,8 @@ linux-kernel = [] ram-disk = [] # The virtual clock and models other driver crates' tests share. test-support = [] +# Explicit bounded boot IRQ diagnostics, never native-service delivery. +irq-diagnostics = [] [dependencies] stela-driver-core = { path = "../stela-driver-core" } diff --git a/crates/stela-driver-base/src/bus/irq.rs b/crates/stela-driver-base/src/bus/irq.rs index e6b24d4242..eb7516e574 100644 --- a/crates/stela-driver-base/src/bus/irq.rs +++ b/crates/stela-driver-base/src/bus/irq.rs @@ -1,7 +1,6 @@ -//! Owned native interrupt registrations. Device acknowledgement, completion -//! fences and reset algorithms belong to the device handler/source owner. +//! Original notification domains and exact CPU/callback/service action joins. pub mod posted_msi; - +use crate::bus::pci::requester::{RequesterId, preparation::DetachedRequester}; use alloc::{boxed::Box, sync::Arc}; use core::{ marker::PhantomData, @@ -16,7 +15,6 @@ const ARMING: u8 = 0; const LIVE: u8 = 1; const CLOSING: u8 = 2; const QUARANTINED: u8 = 3; - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum IrqError { Unavailable, @@ -29,15 +27,27 @@ pub enum IrqError { Route, Drain, Unregistered, + Delivery(posted_msi::Error), } - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct MsiMessage { pub address: u64, pub data: u32, } - -/// Physical fixed-delivery target, checked by the owning CPU adapter. +impl MsiMessage { + /// Data-format validation only. No message value grants route authority. + /// Current remappable programming supports SHV=0 and zero subhandle data; + /// the CPU vector remains in the checked root route, not in this data word. + pub(crate) fn valid_pci_format(self) -> bool { + if self.address & 3 != 0 { + return false; + } + let remapped = self.address & 0xfff0_0010 == 0xfee0_0010; + !remapped + || (self.address <= u64::from(u32::MAX) && self.address & 8 == 0 && self.data == 0) + } +} +/// Programming descriptor only; Registry's private reservation grants ownership. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Target { pub destination: u8, @@ -60,8 +70,12 @@ pub struct LineRoute { pub trigger: Trigger, } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum RouteRequest { +pub enum RouteKind { Msi, + Line, +} +pub enum RouteRequest { + Msi(posted_msi::MsiRoute), Line(LineRoute), } #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -75,6 +89,103 @@ pub enum Disposition { Handled, } +/// Private allocation identity, kept alive across vector reuse by every proof. +#[derive(Clone)] +pub struct RouteId(Arc); +struct RouteIdentity { + platform: &'static dyn Platform, + target: Target, + requester: Option, + reserved: AtomicBool, + registry: RegistryIdentity, +} +impl RouteId { + pub(crate) fn same(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub(crate) fn target(&self) -> Target { + self.0.target + } + pub(crate) fn check_process(&self) -> Result<(), IrqError> { + self.0.platform.check_process()?; + decode_error(self.0.registry.fault.load(Ordering::Acquire)).map_or(Ok(()), Err) + } +} +/// Borrowed view of an owned Registry reservation, never native entered authority. +/// Only Registry creates it after checking actual CPU/root and exclusive vector. +pub struct CpuTarget<'a> { + id: &'a RouteId, +} +impl CpuTarget<'_> { + /// Join the actual retained Registry allocation, never vector numbers. + pub fn belongs_to(&self, registry: RegistryIdentity) -> bool { + self.id.0.registry.same(registry) + } + pub fn descriptor(&self) -> Target { + self.id.target() + } + pub fn check_current(&self) -> Result<(), IrqError> { + self.id.check_process()?; + if !self.id.0.reserved.load(Ordering::Acquire) { + return Err(IrqError::Unregistered); + } + Ok(()) + } + pub(crate) fn id(&self) -> &RouteId { + self.id + } + pub(crate) fn matches_requester(&self, requester: &RequesterId) -> bool { + self.id + .0 + .requester + .as_ref() + .is_some_and(|own| own.same_requester(requester)) + } +} +/// Programming view tied to this exact original route. Copied numbers are data. +pub struct AllocatedRoute<'a> { + id: Option<&'a RouteId>, + programming: Route, +} +impl AllocatedRoute<'_> { + /// Symbolic programming data for isolated source-effect models only. + /// # Safety + /// No physical endpoint or native route may be programmed by this view. + /// It cannot mint a CpuTarget, root grant or any retirement receipt. + #[cfg(any(test, feature = "test-support"))] + pub unsafe fn model_programming(programming: Route) -> Self { + Self { + id: None, + programming, + } + } + pub fn programming(&self) -> Route { + self.programming + } + pub fn belongs_to(&self, registry: RegistryIdentity) -> bool { + self.id.is_some_and(|id| id.0.registry.same(registry)) + } + pub fn matches_requester(&self, requester: &RequesterId) -> bool { + self.id + .and_then(|id| id.0.requester.as_ref()) + .is_some_and(|own| own.same_requester(requester)) + } + /// # Safety + /// This is the existing complete VMD source/fanout owner programming only + /// its owned child ingress. It grants no independent child Registry route, + /// root capability, detach or interrupt-retirement receipt. + pub(crate) unsafe fn vmd_child(&self, message: MsiMessage) -> AllocatedRoute<'_> { + AllocatedRoute { + id: self.id, + programming: Route::Msi(message), + } + } +} +pub struct Request { + pub source: S, + pub handler: Arc, + pub routing: RouteRequest, +} /// Immutable, pre-bound sharing group. Every member remains held until /// the entire physical source group is masked, stopped and drained. Joining /// or removing a member requires complete group retirement and re-registration; @@ -107,40 +218,63 @@ impl Handler for SharedHandlers { } } -/// A request that did not register. Once the CPU check passes, a refusal -/// before anything is published gives the source and handler back -/// unchanged, so the driver can keep polling its device; after a wrong-CPU -/// check or an uncertain arming failure they stay held. +/// Full untouched owners returned only after a checked prepublication refusal. +/// Default Drop retains; checked extraction permits explicit retry/cancellation. +pub struct UnregisteredSource { + request: ManuallyDrop>>, + platform: &'static dyn Platform, + owner_cpu: PhantomData<*mut ()>, +} +impl UnregisteredSource { + /// # Safety + /// Keep handler through source release and honor its independent resource + /// obligations. No retirement proof is supplied by this untouched request. + #[expect( + clippy::type_complexity, + reason = "explicit source/handler/route transfer preserves the checked extraction contract" + )] + pub unsafe fn into_parts( + mut self, + ) -> Result<(Box, Arc, RouteRequest), ExtractionFailure> { + if let Err(error) = self.platform.check_process() { + return Err(ExtractionFailure { + error, + retained: self, + }); + } + if let RouteRequest::Msi(msi) = &self.request.routing + && let Err(error) = msi.check_unpublished() + { + return Err(ExtractionFailure { + error: IrqError::Delivery(error), + retained: self, + }); + } + // SAFETY: unique checked untouched owner, taken once; fields retain on + // every error/default Drop and no callback runs during extraction. + let request = unsafe { ManuallyDrop::take(&mut self.request) }; + Ok((request.source, request.handler, request.routing)) + } +} +pub struct ExtractionFailure { + pub error: IrqError, + pub retained: T, +} pub struct RequestError { pub error: IrqError, - pub returned: Option<(Box, Arc)>, + pub returned: Option>, } - -/// Concrete-source refusal from request_owned. Only checked, untouched owners -/// are returned; wrong-CPU or uncertain published ownership stays quarantined. -/// The error itself stays CPU-affine, including when S happens to be Send. pub struct OwnedRequestError { pub error: IrqError, pub returned: Option>, owner_cpu: PhantomData<*mut ()>, } -/// Untouched original owners from a checked prepublication refusal. Default -/// Drop preserves source-before-callback release on the creating CPU. This -/// wrapper proves no registry retirement and cannot mint a RetiredRoute. -pub struct UnregisteredSource { - source: Box, - handler: Arc, - owner_cpu: PhantomData<*mut ()>, -} -impl UnregisteredSource { - /// Recover the exact untouched owners for device-specific fallback/retry. - /// - /// # Safety - /// Stay on the original checked process CPU and keep handler until the - /// source is consumed/released, including independent device/DMA-dependent - /// lifetime obligations. No stop/drain or retired-route proof is supplied. - pub unsafe fn into_parts(self) -> (Box, Arc) { - (self.source, self.handler) +impl core::fmt::Debug for RequestError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("RequestError") + .field("error", &self.error) + .field("returned", &self.returned.is_some()) + .finish() } } impl core::fmt::Debug for OwnedRequestError { @@ -151,16 +285,6 @@ impl core::fmt::Debug for OwnedRequestError { .finish() } } - -impl core::fmt::Debug for RequestError { - fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { - f.debug_struct("RequestError") - .field("error", &self.error) - .field("returned", &self.returned.is_some()) - .finish() - } -} - impl From for RequestError { fn from(error: IrqError) -> Self { Self { @@ -169,29 +293,25 @@ impl From for RequestError { } } } - -/// Object-safe mount service for driver consumers, independent of CPU type. -/// The platform initializes and permanently keeps the controller. pub trait IrqController: Sync { + #[expect( + clippy::result_large_err, + reason = "return original owners inline without allocation after context or publication refusal" + )] fn request( &'static self, - source: Box, - handler: Arc, - ) -> Result, IrqError>; + request: Request>, + ) -> Result, RequestError>; fn quarantine_count(&self) -> u64; } - -/// Process/deferred, CPU-affine owner. This trait supplies no -/// Send/Sync promise; neither operations nor final Drop are hard-IRQ-safe. pub trait IrqRegistration { fn vector(&self) -> u8; fn handled(&self) -> Result; - fn retire(&mut self) -> Result<(), IrqError>; - /// Complete the same stop/drain sequence and return the original source. - /// A failure keeps both owners in this registration for retry/quarantine. - fn retire_source(&mut self) -> Result, IrqError>; + /// Reversible source mask, not root/action retirement. + fn mask(&mut self) -> Result<(), IrqError>; + fn unmask(&mut self) -> Result<(), IrqError>; + fn retire(&mut self) -> Result, IrqError>; } - /// Physical-parent mask capability for a hard-IRQ failure. /// This endpoint grants no route, callback, device or DMA ownership. /// @@ -206,159 +326,308 @@ pub unsafe trait ParentMask: Send + Sync { fn mask(&self) -> Result<(), IrqError>; } -/// Acknowledged retirement of one registered route. Only the canonical -/// registry constructs this non-cloneable, CPU-affine receipt after hardware, -/// callback and work drain. It proves no device DMA/domain/BM retirement. +/// Exact IRQ-action CPU/EOI/callback/service/thread/work join, not all-issued +/// MSI completion or engine/payload/DMA detach. pub struct RetiredRoute { - vector: u8, + id: RouteId, + msi: Option, + line_domain: ManuallyDrop>>, owner_cpu: PhantomData<*mut ()>, } impl RetiredRoute { pub fn vector(&self) -> u8 { - self.vector + self.id.target().vector + } + pub(crate) fn id(&self) -> &RouteId { + &self.id + } + pub fn requester(&self) -> Option<&RequesterId> { + self.id.0.requester.as_ref() + } + pub fn validate(&self) -> Result<(), IrqError> { + self.id.check_process()?; + if let Some(msi) = &self.msi { + msi.validate().map_err(IrqError::Delivery)?; + } + if let Some(domain) = self.line_domain.as_ref() { + domain.check().map_err(IrqError::Delivery)?; + } + Ok(()) + } + pub(crate) fn validate_requester(&self, requester: &RequesterId) -> Result<(), IrqError> { + if !self + .requester() + .is_some_and(|own| own.same_requester(requester)) + { + return Err(IrqError::Route); + } + self.validate() + } + pub fn release_endpoint( + &mut self, + detached: &DetachedRequester, + ) -> Result<(), posted_msi::Error> { + self.msi + .as_mut() + .ok_or(posted_msi::Error::WrongRequester)? + .release(&self.id, detached) + } + pub(crate) fn join_action(&mut self, requester: &RequesterId) -> Result<(), IrqError> { + self.validate_requester(requester)?; + self.msi + .as_mut() + .ok_or(IrqError::Route)? + .join_action(requester, &self.id) + .map_err(IrqError::Delivery) + } + + /// Release only the original bounded no-native-pin diagnostic/model route. + /// A native attached or unavailable route cannot use this transition and + /// it supplies no DetachedRequester or reset-coordinator proof. + pub fn release_unattached_fixture(&mut self) -> Result<(), IrqError> { + self.id.check_process()?; + #[cfg(any(test, feature = "test-support", feature = "irq-diagnostics"))] + if let Some(msi) = &mut self.msi { + return msi.release_fixture(&self.id).map_err(IrqError::Delivery); + } + Err(IrqError::Unsupported) } } - -/// The original source and callback owner after acknowledged route retirement. -/// Source field order preserves final release while its callback context is -/// still held. This owner remains process/deferred and CPU-affine. +impl Drop for RetiredRoute { + fn drop(&mut self) { + // The affine MSI provider has its own conservative checked Drop. Line + // notification metadata likewise cannot end on a foreign CPU/epoch. + if self.validate().is_ok() { + // SAFETY: original checked process/domain, no active old action; + // no controller or source hardware is released by metadata Drop. + unsafe { ManuallyDrop::drop(&mut self.line_domain) }; + } + } +} +/// The original source/handler/root owner after canonical route retirement. +/// Default Drop retains every field; extraction is explicit and checked. +#[must_use = "retired owners must be explicitly extracted or intentionally retained"] pub struct RetiredSource { - source: Box, - handler: Arc, - route: RetiredRoute, + source: ManuallyDrop>, + handler: ManuallyDrop>, + route: ManuallyDrop, } impl RetiredSource { pub fn route(&self) -> &RetiredRoute { &self.route } - - /// Extract the original source, callback and route receipt. - /// /// # Safety - /// Stay on the checked process CPU. Keep `handler` until `source` has - /// been consumed/released, including any source-destructor dependency on - /// callback-owned context, and until all independently required device/DMA - /// completion for callback-owned resources is acknowledged. Config/root release still - /// requires its stop and completion proofs; route drain alone does - /// not grant them. A failed extraction must keep the original owners. - pub unsafe fn into_parts(self) -> (Box, Arc, RetiredRoute) { - (self.source, self.handler, self.route) + /// Keep handler until source and its independent device/DMA users have + /// retired. The route alone cannot end native config/root pins. + #[expect( + clippy::type_complexity, + reason = "explicit source/handler/route transfer preserves the checked extraction contract" + )] + pub unsafe fn into_parts( + mut self, + ) -> Result<(Box, Arc, RetiredRoute), ExtractionFailure> { + if let Err(error) = self.route.validate() { + return Err(ExtractionFailure { + error, + retained: self, + }); + } + // SAFETY: exact checked route and unique fields, each taken once. The + // ManuallyDrop fields remain untouched on every refusal/abandonment. + Ok(unsafe { + ( + ManuallyDrop::take(&mut self.source), + ManuallyDrop::take(&mut self.handler), + ManuallyDrop::take(&mut self.route), + ) + }) } } +/// An original immutable IRQ-chip EOI endpoint, never the affine Source. +/// # Safety +/// Prepared from the same real controller/pin/epoch and checked CpuTarget; +/// IRQ-safe, no allocation/blocking/foreign !Send access. Revalidate original +/// mode/route on every call, preserve mask state, and contain failures through +/// the actual parent. Slot inflight keeps it through local and chip EOI. Drop +/// cannot tear down a live pin or release native custody in a foreign context; +/// refused prepublication/unwind paths retain any unresolved physical owner. +pub unsafe trait ChipEoi: Send + Sync { + fn after_local_eoi(&self, observed: Trigger) -> Result<(), IrqError>; +} -/// Fast hard-IRQ callback. Acknowledge owned real causes before returning, or -/// mask a deferred source under its work owner. The platform -/// emits EOI afterwards. A bounded diagnostic may leave a level -/// asserted once to observe EOI/retrigger behavior. No blocking, allocation or final heap/Arc -/// release is permitted. Defer work through the device's work owner. +/// An ordinary notification is a hint, never a device completion receipt. +/// Check this action's current status/rings before reporting or freeing payload. +/// The original Source/domain must retain every physical resource reachable by +/// this handler; CPU callback ownership alone is not a device DMA exclusion. pub trait Handler: Send + Sync { fn handle(&self) -> Disposition; } - -/// Exclusive real device/interrupt source kept by its registration. +/// Exclusive device stop/program/work owner, separate from root route fencing. /// /// # Safety -/// The source initially owns an inactive route, with no old firmware/driver -/// callback or unresolved alias. `mask` disables interrupt generation -/// and observes the device's acknowledgement. `quiesce` stops submissions and -/// device DMA/posted interrupt writes, cancels/drains queued workers/timers -/// and acknowledges pending causes. It excludes future device delivery/work -/// until explicit `unmask`; the registry invokes it again after callback drain -/// for work from a formerly in-flight callback. Both calls must keep every -/// callback-reachable context, BO, reservation, pin and CPU/DMA lease until -/// registration retirement finishes; quiescence alone never authorizes their -/// release or skips a hardware fence/IOTLB acknowledgement. -/// `program` installs exactly the supplied typed route while masked; -/// `unmask` enables only this route. Errors must never free hardware-reachable -/// state. These process/deferred methods and final Drop are never ISR-safe. -/// A source may be CPU-affine and !Send. Only its checked owning -/// CPU's process registration accesses or finally releases it; IRQ dispatch -/// sees the separately Send+Sync handler only. +/// Own the inactive original source/config/reset epoch and complete admitted +/// route/alias set. mask observes real device acknowledgement; quiesce stops +/// this owned IRQ action's producers and accounts for its old pending causes +/// without freeing reachable state. Other endpoint DMA may remain active when +/// the actual source protocol permits it; engine/payload/unmap/detach proof is +/// separate terminal endpoint ownership. The original notification domain remains retained independently. program +/// verifies the exact allocated requester and programs only its admitted data +/// while masked; unmask cannot enable alternatives. synchronize completes real +/// controller/post-callback work after CPU drain. Failure/panic/Drop retains +/// uncertain resources; all calls/final release require original process CPU. pub unsafe trait Source { + fn route_kind(&self) -> RouteKind; + fn requester(&self) -> Option<&RequesterId>; + /// Line routes require an actual original controller/root notification + /// domain; a missing witness is explicit unavailable admission. + fn notification_domain(&self) -> Result, IrqError> { + Err(IrqError::Unsupported) + } + /// Process-only immutable endpoint capture, before native publication. + /// None is valid only where no chip-specific level EOI is needed. + fn eoi_endpoint( + &mut self, + _target: &CpuTarget<'_>, + ) -> Result>, IrqError> { + Ok(None) + } fn mask(&mut self) -> Result<(), IrqError>; fn quiesce(&mut self) -> Result<(), IrqError>; - fn route(&self) -> RouteRequest; /// # Safety - /// The route is owned by the registry on its checked CPU, matches this - /// source's request, and its callback is published before unmask. - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError>; + /// Registry retains this exact route/CPU/source/callback while masked. + unsafe fn program(&mut self, route: &AllocatedRoute<'_>) -> Result<(), IrqError>; /// # Safety - /// A live registry keeps the programmed route and every callback owner. + /// Exact route and LIVE callback are retained by Registry. unsafe fn unmask(&mut self) -> Result<(), IrqError>; - /// Called after source quiescence, CPU IRR/ISR drain and callback EOI. - /// Check route-controller completion (including level Remote IRR) - /// and drain work queued by any formerly in-flight callback. An error - /// keeps the complete registration; it never authorizes route reuse. /// # Safety - /// The owned source is stopped, CPU IRR/ISR and all in-flight callbacks - /// have drained. No future callback can begin while synchronization runs. + /// This old action is CLOSING; its callback cannot begin again and CPU + /// IRR/ISR/inflight/EOI have joined. Join every captured service/thread/work + /// producer before releasing old reachable state. This is not fabric or DMA + /// completion; a later ordinary notification may reach a new valid action. unsafe fn synchronize(&mut self) -> Result<(), IrqError>; } - -/// Existing CPU/interrupt controller adapter, never a second IDT/APIC owner. +/// Existing checked CPU/controller adapter, never a second vector/root owner. /// /// # Safety -/// Save/disable and restore operate on this same CPU; their memory clobbers -/// order the critical region. `check_cpu` refuses migration/unavailable state. -/// Routing, pending IRR/ISR reads and EOI have their controller effects. -/// `interrupt_window` admits queued IRQs and returns with local IRQs disabled; -/// it is called outside registry locks only. The clock advances during drain. -/// Vector ownership remains exclusive for the registry lifetime; another CPU -/// cannot dispatch a route assigned to this registry's CPU. +/// Actual CPU, IRQ save/restore, pending, target and EOI effects belong to the +/// retained canonical controller. check_process additionally refuses ISR, +/// foreign root and unavailable native execution scope. compatibility_message +/// interrupt_window admits queued delivery only outside Registry/resource locks. pub unsafe trait Platform: Send + Sync { fn check_cpu(&self) -> Result<(), IrqError>; + fn check_process(&self) -> Result<(), IrqError>; fn save_and_disable(&self) -> u64; /// # Safety - /// `saved` is this CPU's immediately enclosing save/disable state. + /// saved is the immediately enclosing same-CPU disable state. unsafe fn restore(&self, saved: u64); fn target(&self, vector: u8) -> Result; fn pending(&self, vector: u8) -> Result; - fn eoi(&self); + /// Snapshot this vector's actual TMR BEFORE local EOI, then acknowledge it. + fn eoi(&self, vector: u8) -> Result; fn ticks(&self) -> u64; fn timeout_ticks(&self) -> u64; /// # Safety - /// No registry lock or non-IRQ-safe resource lock is held; IRQs are off. + /// IRQs are disabled; no Registry/resource lock is held. unsafe fn interrupt_window(&self); } - +fn encode_error(error: IrqError) -> u8 { + match error { + IrqError::Unavailable => 1, + IrqError::WrongCpu => 2, + IrqError::Exhausted => 3, + IrqError::Unsupported => 4, + IrqError::FailedRead => 5, + IrqError::Mask => 6, + IrqError::Quiesce => 7, + IrqError::Route => 8, + IrqError::Drain => 9, + IrqError::Unregistered => 10, + IrqError::Delivery(error) => { + 16 + match error { + posted_msi::Error::RootUnavailable => 0, + posted_msi::Error::Unsupported => 1, + posted_msi::Error::RootFailed => 2, + posted_msi::Error::Unbound => 3, + posted_msi::Error::AlreadyBound => 4, + posted_msi::Error::WrongRequester => 5, + posted_msi::Error::Context => 6, + posted_msi::Error::NotRetired => 7, + } + } + } +} +fn decode_error(code: u8) -> Option { + Some(match code { + 0 => return None, + 1 => IrqError::Unavailable, + 2 => IrqError::WrongCpu, + 3 => IrqError::Exhausted, + 4 => IrqError::Unsupported, + 5 => IrqError::FailedRead, + 6 => IrqError::Mask, + 7 => IrqError::Quiesce, + 8 => IrqError::Route, + 9 => IrqError::Drain, + 10 => IrqError::Unregistered, + 16 => IrqError::Delivery(posted_msi::Error::RootUnavailable), + 17 => IrqError::Delivery(posted_msi::Error::Unsupported), + 18 => IrqError::Delivery(posted_msi::Error::RootFailed), + 19 => IrqError::Delivery(posted_msi::Error::Unbound), + 20 => IrqError::Delivery(posted_msi::Error::AlreadyBound), + 21 => IrqError::Delivery(posted_msi::Error::WrongRequester), + 22 => IrqError::Delivery(posted_msi::Error::Context), + 23 => IrqError::Delivery(posted_msi::Error::NotRetired), + _ => IrqError::Drain, + }) +} struct Slot { - // Release the stopped source while its callback context is still held. source: core::cell::UnsafeCell>, handler: Arc, + domain: Option>, + chip: Option>, + fault: AtomicU8, + routing: core::cell::UnsafeCell, + id: RouteId, + programming: Option, state: AtomicU8, inflight: AtomicUsize, handled: AtomicU64, } - -/// Admission owns these bytes from its first instruction. Every early error -/// keeps them observably without allocating or releasing on an unknown CPU. struct Pending<'a, P: Platform> { registry: &'a Registry

, - source: ManuallyDrop>, - handler: ManuallyDrop>, - published: bool, + request: ManuallyDrop>>, + transferred: bool, } -impl Pending<'_, P> { - /// The unpublished owners, back to the caller on this checked CPU. - fn give_back(mut self) -> (Box, Arc) { - self.published = true; - // SAFETY: this consumes the unique unpublished owners exactly once. - unsafe { - ( - ManuallyDrop::take(&mut self.source), - ManuallyDrop::take(&mut self.handler), - ) +impl Pending<'static, P> { + fn returned(mut self) -> UnregisteredSource { + self.transferred = true; + // SAFETY: unique untouched request after checked prepublication refusal. + let request = unsafe { ManuallyDrop::take(&mut self.request) }; + UnregisteredSource { + request: ManuallyDrop::new(request), + platform: &self.registry.platform, + owner_cpu: PhantomData, } } - - fn into_slot(mut self) -> Slot { - self.published = true; - // SAFETY: this consumes the unique unpublished owners exactly once. + fn slot( + mut self, + id: RouteId, + programming: Option, + domain: Option>, + chip: Option>, + ) -> Slot { + self.transferred = true; + // SAFETY: all original fields move once; Pending no longer retains them. + let request = unsafe { ManuallyDrop::take(&mut self.request) }; Slot { - // SAFETY: taken exactly once; `published` stops Drop from dropping it again. - source: core::cell::UnsafeCell::new(unsafe { ManuallyDrop::take(&mut self.source) }), - // SAFETY: taken exactly once; `published` stops Drop from dropping it again. - handler: unsafe { ManuallyDrop::take(&mut self.handler) }, + source: core::cell::UnsafeCell::new(request.source), + handler: request.handler, + domain, + chip, + fault: AtomicU8::new(0), + routing: core::cell::UnsafeCell::new(request.routing), + id, + programming, state: AtomicU8::new(ARMING), inflight: AtomicUsize::new(0), handled: AtomicU64::new(0), @@ -367,54 +636,106 @@ impl Pending<'_, P> { } impl Drop for Pending<'_, P> { fn drop(&mut self) { - if !self.published { + if !self.transferred { + self.registry.count_quarantine(); + } + } +} +struct Reservation<'a, P: Platform> { + registry: &'a Registry

, + index: usize, + id: RouteId, + transferred: bool, +} +impl Reservation<'_, P> { + fn release(mut self) -> Result<(), IrqError> { + self.registry.platform.check_process()?; + let guard = self.registry.lock(); + self.registry + .reserved + .fetch_and(!(1usize << self.index), Ordering::Release); + self.id.0.reserved.store(false, Ordering::Release); + self.transferred = true; + drop(guard); + Ok(()) + } +} +impl Drop for Reservation<'_, P> { + fn drop(&mut self) { + if !self.transferred { self.registry.count_quarantine(); - // The real Box/Arc allocations remain held. No source access - // or final Drop is checked by a failed admission/CPU check. } } } - impl IrqController for Registry

{ fn request( &'static self, - source: Box, - handler: Arc, - ) -> Result, IrqError> { - // A refusal's returned owners are released here, on the checked CPU. - Registry::request(self, source, handler) - .map(|registration| Box::new(registration) as Box) - .map_err(|refusal| refusal.error) + request: Request>, + ) -> Result, RequestError> { + Registry::request(self, request).map(|r| Box::new(r) as Box) } fn quarantine_count(&self) -> u64 { Registry::quarantine_count(self) } } - -/// One platform-owned vector inventory. Allocations, source operations and -/// **final release**, including callback-owned state, require process/deferred -/// context. Dispatch never clones/drops an Arc or allocates/frees memory. +/// Opaque provenance of the actual permanently retained Registry allocation. +/// This is metadata only, never a CPU reservation or a native root grant. The +/// private non-zero-sized lock address cannot alias a replacement: issuing this +/// token requires a static Registry that is never reclaimed or reconstructed. +#[derive(Clone, Copy)] +pub struct RegistryIdentity { + held: &'static AtomicBool, + fault: &'static AtomicU8, +} +impl RegistryIdentity { + pub fn same(self, other: Self) -> bool { + core::ptr::eq(self.held, other.held) + } +} +/// The one permanently retained CPU-vector/dispatch inventory. pub struct Registry { platform: P, slots: [AtomicPtr; VECTOR_COUNT], + reserved: AtomicUsize, held: AtomicBool, quarantined: AtomicU64, + controller_fault: AtomicU8, } - impl Registry

{ pub const fn new(platform: P) -> Self { Self { platform, slots: [const { AtomicPtr::new(core::ptr::null_mut()) }; VECTOR_COUNT], + reserved: AtomicUsize::new(0), held: AtomicBool::new(false), quarantined: AtomicU64::new(0), + controller_fault: AtomicU8::new(0), } } - + pub fn identity(&'static self) -> RegistryIdentity { + RegistryIdentity { + held: &self.held, + fault: &self.controller_fault, + } + } + /// Latched original controller acknowledgement failure. A true dispatch + /// return means vector ownership only; it never certifies successful EOI. + pub fn controller_failure(&self) -> Option { + decode_error(self.controller_fault.load(Ordering::Acquire)) + } + fn check_controller(&self) -> Result<(), IrqError> { + self.controller_failure().map_or(Ok(()), Err) + } pub fn quarantine_count(&self) -> u64 { self.quarantined.load(Ordering::Relaxed) } - + fn count_quarantine(&self) { + let _ = self + .quarantined + .try_update(Ordering::Relaxed, Ordering::Relaxed, |v| { + Some(v.saturating_add(1)) + }); + } fn lock(&self) -> Guard<'_, P> { let saved = self.platform.save_and_disable(); while self @@ -429,146 +750,22 @@ impl Registry

{ saved, } } - - /// Publish the handler before enabling the source. Any - /// uncertain arming failure keeps source/handler and quarantines vector, - /// as does a wrong-CPU check. Vector exhaustion and target or route - /// refusals give both owners back. - pub fn request( - &'static self, - source: Box, - handler: Arc, - ) -> Result, RequestError> { - // Keep both owners if CPU validation fails before - // publication: this consuming API cannot return a failed source to - // its original CPU, and must never run a !Send source's Drop here. - let pending = Pending { - registry: self, - source: ManuallyDrop::new(source), - handler: ManuallyDrop::new(handler), - published: false, - }; - self.platform.check_cpu()?; - let guard = self.lock(); - let admitted = self - .slots - .iter() - .position(|slot| slot.load(Ordering::Relaxed).is_null()) - .ok_or(IrqError::Exhausted) - .and_then(|index| { - let vector = FIRST_VECTOR + index as u8; - let target = self.platform.target(vector)?; - match target.vector == vector && target.destination != 255 { - true => Ok((index, vector, target)), - false => Err(IrqError::Route), - } - }); - let (index, vector, target) = match admitted { - Ok(admitted) => admitted, - Err(error) => { - drop(guard); - return Err(RequestError { - error, - returned: Some(pending.give_back()), - }); - } - }; - let route = match pending.source.route() { - RouteRequest::Msi => Route::Msi(MsiMessage { - address: 0xfee00000 | u64::from(target.destination) << 12, - data: u32::from(vector), - }), - RouteRequest::Line(line) => Route::Line { target, line }, - }; - let slot = NonNull::from(Box::leak(Box::new(pending.into_slot()))); - self.slots[index].store(slot.as_ptr(), Ordering::Release); - drop(guard); - // SAFETY: the process owner is unique; dispatch never accesses source. - let source = unsafe { &mut *slot.as_ref().source.get() }; - let armed = source - .mask() - .and_then(|()| source.quiesce()) - .and_then(|()| { - // SAFETY: checked target, kept ARMING slot, mask and stop. - unsafe { source.program(route) } - }); - if let Err(error) = armed { - self.quarantine(slot); - return Err(error.into()); - } - // SAFETY: The slot is already fully kept; a delivery during unmask sees - // the real handler. No new submission precedes source configuration. - unsafe { slot.as_ref() } - .state - .store(LIVE, Ordering::Release); - // SAFETY: the complete owned route and LIVE callback are published. - if let Err(error) = unsafe { source.unmask() } { - self.quarantine(slot); - let _ = source.mask(); - return Err(error.into()); - } - Ok(Registration { - registry: self, - slot, - vector, - active: true, - owner_cpu: PhantomData, - }) - } - - /// Preserve the concrete source type through canonical IRQ retirement. - /// This returns the original PCI/config/root owner, never a clone. - pub fn request_owned( - &'static self, - source: S, - handler: Arc, - ) -> Result, OwnedRequestError> { - self.request(Box::new(source), handler) - .map(|registration| OwnedRegistration { - registration, - source: PhantomData, - }) - .map_err(|refusal| OwnedRequestError { - error: refusal.error, - returned: refusal.returned.map(|(source, handler)| { - // SAFETY: this same private request_owned call erased the - // original Box; Registry never replaces its source. - let source = unsafe { Box::from_raw(Box::into_raw(source) as *mut S) }; - UnregisteredSource { - source, - handler, - owner_cpu: PhantomData, - } - }), - owner_cpu: PhantomData, - }) - } - fn quarantine(&self, slot: NonNull) { - // SAFETY: a quarantined slot is never detached or freed. - let previous = unsafe { slot.as_ref() } + // SAFETY: every exposed slot is permanently kept until successful + // detach; quarantine only touches its CPU-independent atomic state. + if unsafe { slot.as_ref() } .state - .swap(QUARANTINED, Ordering::AcqRel); - if previous != QUARANTINED { + .swap(QUARANTINED, Ordering::AcqRel) + != QUARANTINED + { self.count_quarantine(); } } - - fn count_quarantine(&self) { - let _ = self - .quarantined - .try_update(Ordering::Relaxed, Ordering::Relaxed, |count| { - Some(count.saturating_add(1)) - }); - } - - /// Called by the existing IDT dispatcher with local IRQs off. Returns - /// true for a route, including closing/quarantined tombstones. pub fn dispatch(&self, vector: u8) -> bool { let Some(index) = vector .checked_sub(FIRST_VECTOR) .map(usize::from) - .filter(|index| *index < VECTOR_COUNT) + .filter(|i| *i < VECTOR_COUNT) else { return false; }; @@ -576,24 +773,397 @@ impl Registry

{ return false; } let guard = self.lock(); - let Some(slot) = NonNull::new(self.slots[index].load(Ordering::Acquire)) else { - return false; - }; - // SAFETY: lock protects pointer acquisition; inflight prevents release - // until after EOI, even if removal closes the route meanwhile. - let slot = unsafe { slot.as_ref() }; - slot.inflight.fetch_add(1, Ordering::AcqRel); - let live = slot.state.load(Ordering::Acquire) == LIVE; - drop(guard); - if live && slot.handler.handle() == Disposition::Handled { - slot.handled.fetch_add(1, Ordering::Relaxed); + let slot = NonNull::new(self.slots[index].load(Ordering::Acquire)); + let pointer = slot; + // SAFETY: lock protects acquisition; inflight includes handler + all EOI. + let slot = slot.map(|slot| unsafe { slot.as_ref() }); + if let Some(slot) = slot { + slot.inflight.fetch_add(1, Ordering::AcqRel); } - self.platform.eoi(); - slot.inflight.fetch_sub(1, Ordering::Release); + let mut unwind = DispatchUnwind { + registry: self, + slot: pointer, + completed: false, + }; + let controller_error = self.controller_failure(); + let state = slot.map(|slot| slot.state.load(Ordering::Acquire)); + let live = controller_error.is_none() && state == Some(LIVE); + drop(guard); + let mut error = controller_error; + if let Some(slot) = slot + && live + { + let valid = slot + .domain + .as_ref() + .ok_or(posted_msi::Error::RootUnavailable) + .and_then(|domain| domain.check()); + match valid { + Ok(()) => { + if slot.handler.handle() == Disposition::Handled { + slot.handled.fetch_add(1, Ordering::Relaxed); + } + } + Err(cause) => error = Some(IrqError::Delivery(cause)), + } + } + // The entire reserved range belongs to this original controller. + // An ordinary late/unbound notification still needs local EOI. + match self.platform.eoi(vector) { + Ok(observed) => { + // An old ordinary edge packet may reach the reserved vector + // before the masked Source is programmed. No new owned level + // source is enabled in ARMING, so only local EOI is needed; + // the captured chip endpoint is not a programmed pin yet. + if let Some(slot) = slot.filter(|_| state != Some(ARMING)) + && let Some(chip) = &slot.chip + && let Err(cause) = chip.after_local_eoi(observed) + { + error.get_or_insert(cause); + } + } + Err(cause) => { + // No Slot may exist for a delayed notification. Preserve the + // actual controller failure canonically before allowing any + // replacement admission or callback, rather than losing it. + let _ = self.controller_fault.compare_exchange( + 0, + encode_error(cause), + Ordering::AcqRel, + Ordering::Acquire, + ); + error.get_or_insert(cause); + } + } + if let Some(slot) = slot { + if let Some(error) = error { + let _ = slot.fault.compare_exchange( + 0, + encode_error(error), + Ordering::AcqRel, + Ordering::Acquire, + ); + if slot.state.swap(QUARANTINED, Ordering::AcqRel) != QUARANTINED { + self.count_quarantine(); + } + } + slot.inflight.fetch_sub(1, Ordering::Release); + } + unwind.completed = true; true } } - +impl Registry

{ + fn reserve( + &'static self, + requester: Option, + ) -> Result, IrqError> { + self.platform.check_process()?; + let guard = self.lock(); + let used = self.reserved.load(Ordering::Relaxed); + let index = (0..VECTOR_COUNT) + .find(|i| used & (1usize << i) == 0) + .ok_or(IrqError::Exhausted)?; + let vector = FIRST_VECTOR + index as u8; + let target = self.platform.target(vector)?; + if target.vector != vector || target.destination == 255 { + return Err(IrqError::Route); + } + self.reserved.fetch_or(1usize << index, Ordering::Release); + drop(guard); + // Heap allocation is outside IF-disabled Registry exclusion. + let id = RouteId(Arc::new(RouteIdentity { + platform: &self.platform, + target, + requester, + reserved: AtomicBool::new(true), + registry: self.identity(), + })); + Ok(Reservation { + registry: self, + index, + id, + transferred: false, + }) + } + #[expect( + clippy::result_large_err, + reason = "return original owners inline without allocation after context or publication refusal" + )] + pub fn request( + &'static self, + request: Request>, + ) -> Result, RequestError> { + let mut pending = Pending { + registry: self, + request: ManuallyDrop::new(request), + transferred: false, + }; + self.platform.check_process()?; + if let Err(error) = self.check_controller() { + return Err(RequestError { + error, + returned: Some(pending.returned()), + }); + } + let kind = pending.request.source.route_kind(); + if !matches!( + (&pending.request.routing, kind), + (RouteRequest::Msi(_), RouteKind::Msi) | (RouteRequest::Line(_), RouteKind::Line) + ) { + return Err(RequestError { + error: IrqError::Route, + returned: Some(pending.returned()), + }); + } + let requester = pending.request.source.requester().cloned(); + if let RouteRequest::Msi(route) = &pending.request.routing { + let matches = match (route.requester(), requester.as_ref()) { + (None, None) => true, + (Some(a), Some(b)) => a.same_requester(b), + _ => false, + }; + if !matches { + return Err(RequestError { + error: IrqError::Route, + returned: Some(pending.returned()), + }); + } + } + let mut reservation = match self.reserve(requester) { + Ok(value) => value, + Err(error) => { + let returned = if self.platform.check_process().is_ok() { + Some(pending.returned()) + } else { + None + }; + return Err(RequestError { error, returned }); + } + }; + let target = CpuTarget { + id: &reservation.id, + }; + let chip = match pending.request.source.eoi_endpoint(&target) { + Ok(chip) => chip, + Err(error) => { + reservation.release()?; + return Err(RequestError { + error, + returned: Some(pending.returned()), + }); + } + }; + if matches!( + &pending.request.routing, + RouteRequest::Line(LineRoute { + trigger: Trigger::Level, + .. + }) + ) && chip.is_none() + { + reservation.release()?; + return Err(RequestError { + error: IrqError::Unsupported, + returned: Some(pending.returned()), + }); + } + let line_domain = if matches!(&pending.request.routing, RouteRequest::Line(_)) { + match pending.request.source.notification_domain() { + Ok(domain) => { + if let Err(error) = domain.check() { + reservation.release()?; + return Err(RequestError { + error: IrqError::Delivery(error), + returned: Some(pending.returned()), + }); + } + Some(domain) + } + Err(error) => { + reservation.release()?; + return Err(RequestError { + error, + returned: Some(pending.returned()), + }); + } + } + } else { + None + }; + let allocated = match &mut pending.request.routing { + RouteRequest::Msi(route) => route.allocation(&target).map(Route::Msi), + RouteRequest::Line(line) => Ok(Route::Line { + target: target.descriptor(), + line: *line, + }), + }; + let programming = match allocated { + Ok(data) => Some(data), + Err(error) if error.untouched() && self.platform.check_process().is_ok() => { + reservation.release()?; + return Err(RequestError { + error: IrqError::Delivery(error.error()), + returned: Some(pending.returned()), + }); + } + Err(error) => { + let slot = NonNull::from(Box::leak(Box::new(pending.slot( + reservation.id.clone(), + None, + None, + chip, + )))); + self.slots[reservation.index].store(slot.as_ptr(), Ordering::Release); + reservation.transferred = true; + self.quarantine(slot); + return Err(IrqError::Delivery(error.error()).into()); + } + }; + let domain = match &pending.request.routing { + RouteRequest::Msi(route) => match route.domain() { + Ok(domain) => Some(domain), + Err(error) => { + let slot = NonNull::from(Box::leak(Box::new(pending.slot( + reservation.id.clone(), + programming, + None, + chip, + )))); + self.slots[reservation.index].store(slot.as_ptr(), Ordering::Release); + reservation.transferred = true; + self.quarantine(slot); + return Err(IrqError::Delivery(error).into()); + } + }, + RouteRequest::Line(_) => line_domain, + }; + let slot = NonNull::from(Box::leak(Box::new(pending.slot( + reservation.id.clone(), + programming, + domain, + chip, + )))); + self.slots[reservation.index].store(slot.as_ptr(), Ordering::Release); + reservation.transferred = true; + let vector = reservation.id.target().vector; + // SAFETY: this process owner alone accesses affine source and route; + // dispatch sees only separately retained immutable handler/atomics. + let stored = unsafe { slot.as_ref() }; + // After publication Drop performs only atomic quarantine, including + // an unwinding source callback; no hardware retry runs during Drop. + let registration = Registration { + registry: self, + slot, + vector, + active: true, + owner_cpu: PhantomData, + }; + // SAFETY: unique checked process owner as above. + let source = unsafe { &mut *stored.source.get() }; + let armed = self + .check_controller() + .and_then(|()| source.mask()) + .and_then(|()| source.quiesce()) + .and_then(|()| { + self.platform.check_process()?; + self.check_controller()?; + stored + .domain + .as_ref() + .ok_or(IrqError::Delivery(posted_msi::Error::RootUnavailable))? + .check() + .map_err(IrqError::Delivery)?; + // SAFETY: exclusive same-process route ownership, never ISR access. + if let RouteRequest::Msi(route) = unsafe { &mut *stored.routing.get() } { + route.programming().map_err(IrqError::Delivery)?; + } + let route = AllocatedRoute { + id: Some(&stored.id), + programming: stored.programming.ok_or(IrqError::Route)?, + }; + // SAFETY: exact target/root/source, kept ARMING handler and real mask/stop. + unsafe { source.program(&route) }?; + self.platform.check_process()?; + self.check_controller()?; + stored + .domain + .as_ref() + .ok_or(IrqError::Delivery(posted_msi::Error::RootUnavailable))? + .check() + .map_err(IrqError::Delivery) + }); + if let Err(error) = armed { + self.quarantine(slot); + return Err(error.into()); + } + if stored.fault.load(Ordering::Acquire) != 0 + || stored + .state + .compare_exchange(ARMING, LIVE, Ordering::AcqRel, Ordering::Acquire) + .is_err() + { + return Err(decode_error(stored.fault.load(Ordering::Acquire)) + .unwrap_or(IrqError::Drain) + .into()); + } + // SAFETY: published LIVE callback and exact original route stay retained. + if let Err(error) = unsafe { source.unmask() } { + self.quarantine(slot); + let _ = source.mask(); + return Err(error.into()); + } + self.check_controller()?; + if stored.state.load(Ordering::Acquire) != LIVE { + return Err(decode_error(stored.fault.load(Ordering::Acquire)) + .unwrap_or(IrqError::Drain) + .into()); + } + Ok(registration) + } + #[expect( + clippy::result_large_err, + reason = "return original owners inline without allocation after context or publication refusal" + )] + pub fn request_owned( + &'static self, + request: Request, + ) -> Result, OwnedRequestError> { + let Request { + source, + handler, + routing, + } = request; + self.request(Request { + source: Box::new(source), + handler, + routing, + }) + .map(|registration| OwnedRegistration { + registration, + source: PhantomData, + }) + .map_err(|refusal| OwnedRequestError { + error: refusal.error, + owner_cpu: PhantomData, + returned: refusal.returned.map(|mut untouched| { + // SAFETY: only this request erased Box; no source can be + // replaced before clean prepublication return. No callback. + let erased = unsafe { ManuallyDrop::take(&mut untouched.request) }; + UnregisteredSource { + request: ManuallyDrop::new(Request { + // SAFETY: unique original allocation/type, as above. + source: unsafe { Box::from_raw(Box::into_raw(erased.source) as *mut S) }, + handler: erased.handler, + routing: erased.routing, + }), + platform: untouched.platform, + owner_cpu: PhantomData, + } + }), + }) + } +} struct Guard<'a, P: Platform> { registry: &'a Registry

, saved: u64, @@ -601,14 +1171,74 @@ struct Guard<'a, P: Platform> { impl Drop for Guard<'_, P> { fn drop(&mut self) { self.registry.held.store(false, Ordering::Release); - // SAFETY: same CPU, exactly this guard's saved interrupt state. + // SAFETY: exact immediately enclosing same-CPU interrupt state. unsafe { self.registry.platform.restore(self.saved) }; } } - -/// Unique CPU-affine owner, neither Send nor Sync. Keeps the -/// source/handler until mask/quiescence, dispatch and IRR/ISR drain. -/// Drop and every method require process/deferred context; never an ISR. +/// Restores the immediately enclosing original CPU state even if a pending, +/// clock, or delivery-window callback unwinds. It owns no device/root lock. +struct SavedInterrupts<'a, P: Platform> { + platform: &'a P, + saved: u64, +} +impl<'a, P: Platform> SavedInterrupts<'a, P> { + fn new(platform: &'a P) -> Self { + Self { + platform, + saved: platform.save_and_disable(), + } + } +} +impl Drop for SavedInterrupts<'_, P> { + fn drop(&mut self) { + // SAFETY: Platform's exact same-CPU window contract forbids migration; + // this guard uniquely owns this immediately enclosing saved IRQ state. + unsafe { self.platform.restore(self.saved) }; + } +} +/// Callback/EOI unwind cannot leave an apparently LIVE action or admit a +/// replacement after an unacknowledged interrupt. Drop is atomic-only and +/// retains the inflight claim; it does not invent CPU/EOI completion. +struct DispatchUnwind<'a, P: Platform> { + registry: &'a Registry

, + slot: Option>, + completed: bool, +} +impl Drop for DispatchUnwind<'_, P> { + fn drop(&mut self) { + if self.completed { + return; + } + let code = encode_error(IrqError::Drain); + let _ = self.registry.controller_fault.compare_exchange( + 0, + code, + Ordering::AcqRel, + Ordering::Acquire, + ); + if let Some(slot) = self.slot { + // SAFETY: lock-protected acquisition retained an inflight claim; + // no successful retirement can free this actual allocation. + let stored = unsafe { slot.as_ref() }; + let _ = stored + .fault + .compare_exchange(0, code, Ordering::AcqRel, Ordering::Acquire); + self.registry.quarantine(slot); + } + } +} +struct RetirementUnwind<'a, P: Platform> { + registry: &'a Registry

, + slot: NonNull, + completed: bool, +} +impl Drop for RetirementUnwind<'_, P> { + fn drop(&mut self) { + if !self.completed { + self.registry.quarantine(self.slot); + } + } +} pub struct Registration<'a, P: Platform> { registry: &'a Registry

, slot: NonNull, @@ -616,7 +1246,6 @@ pub struct Registration<'a, P: Platform> { active: bool, owner_cpu: PhantomData<*mut ()>, } - impl Registration<'_, P> { pub fn vector(&self) -> u8 { self.vector @@ -625,98 +1254,172 @@ impl Registration<'_, P> { if !self.active { return Err(IrqError::Unregistered); } - // SAFETY: this unique registration keeps its slot until retirement. + // SAFETY: this unique registration retains its exact slot. Ok(unsafe { self.slot.as_ref() } .handled .load(Ordering::Relaxed)) } - - /// A failed stop/drain keeps the complete registration for retry; no - /// vector/context or callback-owned pages can be reused by that failure. - pub fn retire(&mut self) -> Result<(), IrqError> { - // Slot field order releases source while the callback is held. - drop(self.detach()?); - Ok(()) - } - - /// Return the source only after final controller and callback drain. - pub fn retire_source(&mut self) -> Result, IrqError> { - let retired = self.detach()?; - let Slot { - source, handler, .. - } = *retired; - let source = source.into_inner(); - Ok(RetiredSource { - source, - handler, - route: RetiredRoute { - vector: self.vector, - owner_cpu: PhantomData, - }, - }) - } - - fn detach(&mut self) -> Result, IrqError> { + pub fn mask(&mut self) -> Result<(), IrqError> { + self.registry.platform.check_process()?; + self.registry.check_controller()?; if !self.active { return Err(IrqError::Unregistered); } - self.registry.platform.check_cpu()?; - let guard = self.registry.lock(); - // SAFETY: unique process owner, protected against dispatch - // pointer acquisition; handler borrow remains guarded by inflight. + // SAFETY: this registration keeps its exact live source allocation. let slot = unsafe { self.slot.as_ref() }; - slot.state.store(CLOSING, Ordering::Release); - drop(guard); - // SAFETY: no other process owner accesses this source. ISR does not. - let source = unsafe { &mut *slot.source.get() }; - source.mask()?; - source.quiesce()?; - let saved = self.registry.platform.save_and_disable(); - let start = self.registry.platform.ticks(); - let drained = loop { - let pending = match self.registry.platform.pending(self.vector) { - Ok(pending) => pending, - Err(error) => break Err(error), - }; - if !pending && slot.inflight.load(Ordering::Acquire) == 0 { - break Ok(()); - } - if self.registry.platform.ticks().wrapping_sub(start) - >= self.registry.platform.timeout_ticks() - { - break Err(IrqError::Drain); - } - // SAFETY: no registry/resource lock held; source stopped and - // tombstone kept, so pending delivery only drains/EOIs it. - unsafe { self.registry.platform.interrupt_window() }; - }; - // SAFETY: restore exactly the immediately enclosing same-CPU state. - unsafe { self.registry.platform.restore(saved) }; - drained?; - // A callback that was already in flight when closing began may have - // queued work before its final EOI. Drain/cancel that work only after - // the callback lifetime has ended as well as before hardware draining. - // SAFETY: source stop, CPU pending and in-flight callbacks have drained. - unsafe { source.synchronize() }?; - self.registry.platform.check_cpu()?; - let guard = self.registry.lock(); - if slot.inflight.load(Ordering::Acquire) != 0 - || self.registry.platform.pending(self.vector)? - { + if slot.state.load(Ordering::Acquire) != LIVE { return Err(IrqError::Drain); } - self.registry.slots[usize::from(self.vector - FIRST_VECTOR)] - .store(core::ptr::null_mut(), Ordering::Release); - self.active = false; - drop(guard); - // SAFETY: real source quiescence excludes any future delivery/work, - // and locked final IRR/ISR/inflight checks establish no remaining user. - Ok(unsafe { Box::from_raw(self.slot.as_ptr()) }) + // SAFETY: only this original process owner touches the affine source. + unsafe { &mut *slot.source.get() }.mask() + } + pub fn unmask(&mut self) -> Result<(), IrqError> { + self.registry.platform.check_process()?; + self.registry.check_controller()?; + if !self.active { + return Err(IrqError::Unregistered); + } + // SAFETY: same retained live registration; no ISR touches source/route. + let slot = unsafe { self.slot.as_ref() }; + if slot.state.load(Ordering::Acquire) != LIVE { + return Err(IrqError::Drain); + } + // SAFETY: same unique original process owner as above. + if let RouteRequest::Msi(route) = unsafe { &*slot.routing.get() } { + route.check_rearm().map_err(IrqError::Delivery)?; + } + slot.domain + .as_ref() + .ok_or(IrqError::Delivery(posted_msi::Error::RootUnavailable))? + .check() + .map_err(IrqError::Delivery)?; + // SAFETY: the same exact LIVE callback and checked root route remain. + unsafe { (&mut *slot.source.get()).unmask() } + } + pub fn retire(&mut self) -> Result, IrqError> { + if !self.active { + return Err(IrqError::Unregistered); + } + // SAFETY: this active registration retains its exact live Slot; + // atomic-only inspection is valid even if original context is refused. + if unsafe { self.slot.as_ref() }.state.load(Ordering::Acquire) == QUARANTINED { + // SAFETY: active registration retains this exact slot and atomics. + return Err( + decode_error(unsafe { self.slot.as_ref() }.fault.load(Ordering::Acquire)) + .unwrap_or(IrqError::Drain), + ); + } + let mut poison = RetirementUnwind { + registry: self.registry, + slot: self.slot, + completed: false, + }; + let result = (|| { + self.registry.platform.check_process()?; + self.registry.check_controller()?; + let guard = self.registry.lock(); + // SAFETY: registration keeps the slot, while lock excludes acquisition. + let slot = unsafe { self.slot.as_ref() }; + slot.state.store(CLOSING, Ordering::Release); + drop(guard); + // SAFETY: only this unique checked process owner touches source/route. + let source = unsafe { &mut *slot.source.get() }; + source.mask()?; + source.quiesce()?; + // Notification-domain validation is not fabric completion. The + // source action is closed; old ordinary packets may notify a valid + // current handler after exact CPU/service/thread/work retirement. + if let Some(domain) = &slot.domain { + domain.check().map_err(IrqError::Delivery)?; + } else { + return Err(IrqError::Delivery(posted_msi::Error::RootUnavailable)); + } + let saved = SavedInterrupts::new(&self.registry.platform); + let start = self.registry.platform.ticks(); + let drained = loop { + let pending = match self.registry.platform.pending(self.vector) { + Ok(p) => p, + Err(e) => break Err(e), + }; + if !pending && slot.inflight.load(Ordering::Acquire) == 0 { + break Ok(()); + } + if self.registry.platform.ticks().wrapping_sub(start) + >= self.registry.platform.timeout_ticks() + { + break Err(IrqError::Drain); + } + // SAFETY: no Registry/resource lock; retained CLOSING slot + // acknowledges pending delivery/EOI without entering old callbacks. + unsafe { self.registry.platform.interrupt_window() }; + }; + drop(saved); + drained?; + // SAFETY: CLOSING excludes old callbacks after CPU/EOI drain. Keep + // all source memory through actual captured work/controller joins. + unsafe { source.synchronize() }?; + self.registry.platform.check_process()?; + self.registry.check_controller()?; + slot.domain + .as_ref() + .ok_or(IrqError::Delivery(posted_msi::Error::RootUnavailable))? + .check() + .map_err(IrqError::Delivery)?; + // SAFETY: same exclusive process route access after work synchronization. + if let RouteRequest::Msi(route) = unsafe { &mut *slot.routing.get() } { + route.cpu_retired().map_err(IrqError::Delivery)?; + } + let guard = self.registry.lock(); + self.registry.check_controller()?; + if slot.state.load(Ordering::Acquire) != CLOSING { + return Err( + decode_error(slot.fault.load(Ordering::Acquire)).unwrap_or(IrqError::Drain) + ); + } + if slot.inflight.load(Ordering::Acquire) != 0 + || self.registry.platform.pending(self.vector)? + { + return Err(IrqError::Drain); + } + let index = usize::from(self.vector - FIRST_VECTOR); + self.registry.slots[index].store(core::ptr::null_mut(), Ordering::Release); + self.registry + .reserved + .fetch_and(!(1usize << index), Ordering::Release); + slot.id.0.reserved.store(false, Ordering::Release); + self.active = false; + drop(guard); + poison.completed = true; + // SAFETY: source/CPU/work and locked final check excluded old action users; + // this unique owner reclaims the original slot allocation exactly once. + let retired_slot = unsafe { Box::from_raw(self.slot.as_ptr()) }; + let Slot { + source, + handler, + routing, + id, + domain, + .. + } = *retired_slot; + let (msi, line_domain) = match routing.into_inner() { + RouteRequest::Msi(msi) => (Some(msi), None), + RouteRequest::Line(_) => (None, domain), + }; + Ok(RetiredSource { + source: ManuallyDrop::new(source.into_inner()), + handler: ManuallyDrop::new(handler), + route: ManuallyDrop::new(RetiredRoute { + id, + msi, + line_domain: ManuallyDrop::new(line_domain), + owner_cpu: PhantomData, + }), + }) + })(); + poison.completed = true; + result } } - -/// Concrete-source registration with the same process/CPU affinity. Private -/// construction proves the type of its erased, uniquely kept source. pub struct OwnedRegistration<'a, P: Platform, S: Source + 'static> { registration: Registration<'a, P>, source: PhantomData, @@ -729,44 +1432,47 @@ impl OwnedRegistration<'_, P, S> { self.registration.handled() } pub fn retire(&mut self) -> Result, IrqError> { - let RetiredSource { - source, - handler, - route, - } = self.registration.retire_source()?; + let mut erased = self.registration.retire()?; + // SAFETY: request_owned alone erased this unique Box; Registry never + // replaces it. Move all retained fields, without foreign callbacks. + let (source, handler, route) = unsafe { + ( + ManuallyDrop::take(&mut erased.source), + ManuallyDrop::take(&mut erased.handler), + ManuallyDrop::take(&mut erased.route), + ) + }; Ok(RetiredSource { - // SAFETY: request_owned alone constructs this wrapper from Box; - // Registry never replaces it. Retirement uniquely returns that - // allocation after controller/callback/work drain. - source: unsafe { Box::from_raw(Box::into_raw(source) as *mut S) }, - handler, - route, + // SAFETY: exact allocation/type established by request_owned. + source: ManuallyDrop::new(unsafe { Box::from_raw(Box::into_raw(source) as *mut S) }), + handler: ManuallyDrop::new(handler), + route: ManuallyDrop::new(route), }) } } - impl Drop for Registration<'_, P> { fn drop(&mut self) { - if self.active && self.retire().is_err() { + if self.active { self.registry.quarantine(self.slot); } } } - impl IrqRegistration for Registration<'_, P> { fn vector(&self) -> u8 { - Registration::vector(self) + self.vector() } fn handled(&self) -> Result { - Registration::handled(self) + self.handled() } - fn retire(&mut self) -> Result<(), IrqError> { - Registration::retire(self) + fn mask(&mut self) -> Result<(), IrqError> { + self.mask() } - fn retire_source(&mut self) -> Result, IrqError> { - Registration::retire_source(self) + fn unmask(&mut self) -> Result<(), IrqError> { + self.unmask() + } + fn retire(&mut self) -> Result, IrqError> { + self.retire() } } - #[cfg(test)] mod tests; diff --git a/crates/stela-driver-base/src/bus/irq/posted_msi.rs b/crates/stela-driver-base/src/bus/irq/posted_msi.rs index e888bb9de7..7274073fcb 100644 --- a/crates/stela-driver-base/src/bus/irq/posted_msi.rs +++ b/crates/stela-driver-base/src/bus/irq/posted_msi.rs @@ -1,220 +1,433 @@ -// SPDX-License-Identifier: MIT -// Copyright (c) 2026 Stela contributors -//! Root and route completion for posted MSI/MSI-X, separate from payload DMA. -use super::MsiMessage; -use alloc::boxed::Box; -use core::cell::Cell; +//! Original requester/root route ownership, distinct from payload and CPU drain. +use super::{CpuTarget, MsiMessage, RouteId}; +use crate::bus::pci::requester::{RequesterId, preparation::DetachedRequester}; +use alloc::{boxed::Box, sync::Arc}; +use core::{marker::PhantomData, mem::ManuallyDrop}; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Error { RootUnavailable, + Unsupported, RootFailed, Unbound, - AlreadyBound { - original: MsiMessage, - attempted: MsiMessage, - }, + AlreadyBound, + WrongRequester, + Context, + NotRetired, } -/// The consumed requester/root epoch and its exclusively allocated route. -/// -/// # Safety -/// Bind only this owner's original root and the registry's allocated message. -/// Numeric addresses/BDFs alone grant no permission. Keep delivery/remapping -/// resources through completed drain/release or quarantine. `drain_posted_msi` -/// completes every issued MSI/MSI-X on that path independently of payload -/// IOTLB drain, reset, elapsed time and CPU IRR/ISR. Check the original epoch -/// and process context on every operation. Failure/Drop retains uncertain roots. -pub unsafe trait DeliveryOwner { - fn bind_route(&mut self, message: MsiMessage) -> Result<(), Error>; - /// # Safety - /// This original source cannot issue further payload or interrupts: - /// device stop/reset is acknowledged, every route is masked and translated - /// payload writes drained. Keep configuration, DMA and root owners. - unsafe fn drain_posted_msi(&self) -> Result<(), Error>; +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AllocationError { + Unexposed(Error), + Uncertain(Error), } -/// No native producer exists until the common root delivery adapter is supplied -/// (host-driver requirement 9.2). An unavailable capability permits attachment -/// but refuses armed route retirement. Model construction is host-test-only. -pub struct MsiCompletion { - owner: Option>, - message: Option, - binding_error: Option, - drained: Cell, -} -impl MsiCompletion { - pub fn unavailable() -> Self { - Self { - owner: None, - message: None, - binding_error: None, - drained: Cell::new(false), +impl AllocationError { + pub fn error(self) -> Error { + match self { + Self::Unexposed(e) | Self::Uncertain(e) => e, } } - #[cfg(all(any(test, feature = "test-support"), unix, target_arch = "x86_64"))] - pub fn model(owner: Box) -> Self { - let mut completion = Self::unavailable(); - completion.owner = Some(owner); - completion - } - /// # Safety - /// This is the original registry's exclusively allocated route for this - /// requester/root owner. Keep it through source/CPU/work retirement. - pub unsafe fn bind_route(&mut self, message: MsiMessage) -> Result<(), Error> { - if let Some(original) = self.message { - return Err(Error::AlreadyBound { - original, - attempted: message, - }); - } - self.message = Some(message); - if let Some(owner) = &mut self.owner - && let Err(error) = owner.bind_route(message) - { - self.binding_error = Some(error); - return Err(error); - } - Ok(()) - } - /// # Safety - /// The bound source cannot resume; all routes are masked, device stop/reset - /// and translated payload completion are acknowledged. All original owners - /// remain held through this independent completion and later CPU/work drain. - pub unsafe fn drain(&self) -> Result<(), Error> { - if self.message.is_none() { - return Err(Error::Unbound); - } - if let Some(error) = self.binding_error { - return Err(error); - } - let owner = self.owner.as_ref().ok_or(Error::RootUnavailable)?; - if !self.drained.get() { - // SAFETY: caller supplies terminal source/payload ownership; this - // owner independently acknowledges the bound posted-interrupt path. - unsafe { owner.drain_posted_msi() }?; - self.drained.set(true); - } - Ok(()) - } -} -impl Drop for MsiCompletion { - fn drop(&mut self) { - if self.message.is_some() && !self.drained.get() { - core::mem::forget(self.owner.take()); - } + pub(crate) fn untouched(self) -> bool { + matches!(self, Self::Unexposed(_)) } } -#[cfg(all(test, unix, target_arch = "x86_64"))] -mod tests { - use super::*; - use alloc::sync::Arc; - use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - const MESSAGE: MsiMessage = MsiMessage { - address: 0xfee00000, - data: 0x51, - }; - #[derive(Default)] - struct State { - binds: AtomicUsize, - drains: AtomicUsize, - drops: AtomicUsize, - fail_bind: AtomicBool, - fail_drain: AtomicBool, +/// Original stable CPU/root/format and live resource guard for ordinary IRQ +/// notification. This is not all-issued MSI completion or a DMA drain. +/// # Safety +/// Construct only from actual retained original ownership. check is IRQ-safe, +/// allocation-free/nonblocking and checks original immutable/atomic scope +/// before locks or native I/O. No number or mutable !Send Source substitutes +/// for the real root/format and source-resource lifetime. Old ordinary messages +/// may notify a current valid handler; every handler checks its own state/rings. +/// Format/root/CPU ownership stays frozen for that admitted notification domain. +/// Endpoint-specific pins belong only to per-action leaves and end in the +/// actual checked action/endpoint teardown; global root domains do not pin them. +/// Dropping a guard is not permission for hardware teardown. Any physical owner +/// retained by a guard must conservatively retain on foreign context or an +/// unresolved epoch, including refused prepublication return and unwind. +pub unsafe trait NotificationDomain: Send + Sync { + fn check(&self) -> Result<(), Error>; +} + +/// An original attached root/source grant, never a numeric message owner. +/// +/// # Safety +/// Allocation joins only the supplied checked Registry reservation and this +/// exact original configuration/root/reset/source identity. Unexposed errors +/// return that grant without any possible hardware publication. Every method +/// checks actual process/root/source epochs. notification_domain is genuine +/// original ordinary fixed/edge admission, never fabric completion. Strong +/// Intel fencing remains separate optional evidence. Existing index/root ledger +/// obligations are retained independently; notification does not reclaim them. release_endpoint consumes the exact higher retirement proof before +/// ending its source/config pin. The terminal root ledger must survive final +/// owner Drop; failed/abandoned state retains every uncertain native owner. +/// No borrowed native entered permit may escape or span a blocking operation. +pub unsafe trait RouteOwner { + fn allocate(&mut self, target: &CpuTarget<'_>) -> Result; + fn validate(&self) -> Result<(), Error>; + /// Original process-mode checks plus a retained IRQ-safe notification guard. + /// Missing root/source/format admission is an error, never None-as-success. + fn notification_domain(&self) -> Result, Error>; + /// Optional stronger original fabric fence, distinct from generic action + /// notification retirement. No all-issued proof is invented by the default. + /// # Safety + /// This actual original route is masked and its admitted source/pending + /// cause protocol is quiescent; all covered native owners stay retained. + unsafe fn strong_fence(&mut self) -> Result<(), Error> { + Err(Error::Unsupported) } - struct Root(Arc); - // SAFETY: isolated original-route peer; it has no hardware, IRQ, work or - // payload users and records independent root completion/refusal events. - unsafe impl DeliveryOwner for Root { - fn bind_route(&mut self, message: MsiMessage) -> Result<(), Error> { - assert_eq!(message, MESSAGE); - self.0.binds.fetch_add(1, Ordering::Relaxed); - if self.0.fail_bind.load(Ordering::Relaxed) { - Err(Error::RootFailed) - } else { - Ok(()) + /// # Safety + /// The private proof names this exact route after CPU/callback/work + /// retirement and, for native endpoints, actual DMA unmap/requester detach. + unsafe fn release_endpoint(&mut self, proof: &EndpointRetirement<'_>) -> Result<(), Error>; +} + +/// Borrowed proof constructed only by the canonical retirement transitions. +/// It supplies no independent native entered permission. +pub struct EndpointRetirement<'a> { + pub(crate) route: &'a RouteId, + pub(crate) detached: Option<&'a DetachedRequester>, +} +impl EndpointRetirement<'_> { + pub fn requester(&self) -> Option<&RequesterId> { + self.detached.map(DetachedRequester::requester) + } + pub fn vector(&self) -> u8 { + self.route.target().vector + } +} + +enum Origin { + Unavailable, + Attached, + #[cfg(any(test, feature = "test-support", feature = "irq-diagnostics"))] + BoundedFixture, +} +/// One affine IRQ route: original grant, notification admission and explicit endpoint +/// pin release. Registry owns it through source/CPU/work retirement. +pub struct MsiRoute { + owner: ManuallyDrop>>, + origin: Origin, + requester: Option, + action_joined: bool, + route: Option, + message: Option, + published: bool, + domain: ManuallyDrop>>, + cpu_retired: bool, + released: bool, + local: PhantomData<*mut ()>, +} +impl MsiRoute { + pub fn unavailable() -> Self { + Self { + owner: ManuallyDrop::new(None), + origin: Origin::Unavailable, + requester: None, + action_joined: false, + route: None, + message: None, + published: false, + domain: ManuallyDrop::new(None), + cpu_retired: false, + released: false, + local: PhantomData, + } + } + pub(crate) fn attached( + requester: RequesterId, + owner: Option>, + ) -> Result { + let mut route = Self::unavailable(); + *route.owner = owner; + requester.issue().map_err(|_| Error::WrongRequester)?; + route.requester = Some(requester); + route.origin = Origin::Attached; + Ok(route) + } + /// Construct only the explicit synchronous diagnostic/model peer. + /// + /// # Safety + /// Provider owns/validates the exact bounded fixture route and context. + /// It carries NO native requester/configuration pin, cannot satisfy native + /// Attachment detach/reset and is never a NativeServices capability. + #[cfg(any(test, feature = "test-support", feature = "irq-diagnostics"))] + pub unsafe fn bounded_fixture(owner: Box) -> Self { + let mut route = Self::unavailable(); + *route.owner = Some(owner); + route.origin = Origin::BoundedFixture; + route + } + pub fn requester(&self) -> Option<&RequesterId> { + self.requester.as_ref() + } + pub fn is_unavailable(&self) -> bool { + self.owner.is_none() + } + pub fn belongs_to(&self, requester: &RequesterId) -> bool { + self.requester + .as_ref() + .is_some_and(|own| own.same_requester(requester)) + } + /// Cancel an unattached unavailable/fixture request before allocation. + /// This performs no hardware drain and cannot acknowledge a native endpoint. + pub fn cancel_unattached(mut self) -> Result<(), (Error, Self)> { + let result = (|| { + if self.requester.is_some() || self.route.is_some() || self.published { + return Err(Error::AlreadyBound); } - } - unsafe fn drain_posted_msi(&self) -> Result<(), Error> { - self.0.drains.fetch_add(1, Ordering::Relaxed); - if self.0.fail_drain.load(Ordering::Relaxed) { - Err(Error::RootFailed) - } else { - Ok(()) + if let Some(owner) = self.owner.as_ref() { + owner.validate()?; } + drop(self.owner.take()); + self.released = true; + Ok(()) + })(); + match result { + Ok(()) => Ok(()), + Err(error) => Err((error, self)), } } - impl Drop for Root { - fn drop(&mut self) { - self.0.drops.fetch_add(1, Ordering::Relaxed); + + pub(crate) fn check_unpublished(&self) -> Result<(), Error> { + if self.published || self.route.is_some() { + return Err(Error::AlreadyBound); + } + if let Some(owner) = self.owner.as_ref() { + owner.validate()?; + } + Ok(()) + } + pub(crate) fn allocation( + &mut self, + target: &CpuTarget<'_>, + ) -> Result { + if self.route.is_some() { + return Err(AllocationError::Unexposed(Error::AlreadyBound)); + } + target + .check_current() + .map_err(|_| AllocationError::Unexposed(Error::Context))?; + if self + .requester + .as_ref() + .is_some_and(|id| !target.matches_requester(id)) + { + return Err(AllocationError::Unexposed(Error::WrongRequester)); + } + if let Some(owner) = self.owner.as_mut() { + owner.validate().map_err(AllocationError::Unexposed)?; + let domain = owner + .notification_domain() + .map_err(AllocationError::Unexposed)?; + domain.check().map_err(AllocationError::Unexposed)?; + *self.domain = Some(domain); + let message = match owner.allocate(target) { + Ok(message) => message, + Err(error) => { + if !error.untouched() { + self.route = Some(target.id().clone()); + } + return Err(error); + } + }; + self.route = Some(target.id().clone()); + self.message = Some(message); + self.published = true; + owner.validate().map_err(AllocationError::Uncertain)?; + target + .check_current() + .map_err(|_| AllocationError::Uncertain(Error::Context))?; + Ok(message) + } else { + Err(AllocationError::Unexposed(Error::RootUnavailable)) } } - fn bind(completion: &mut MsiCompletion) -> Result<(), Error> { - // SAFETY: this synchronous peer owns the one symbolic allocated route. - unsafe { completion.bind_route(MESSAGE) } + pub(crate) fn domain(&self) -> Result, Error> { + let domain = self.domain.as_ref().ok_or(Error::RootUnavailable)?; + domain.check()?; + Ok(domain.clone()) } - fn drain(completion: &MsiCompletion) -> Result<(), Error> { - // SAFETY: no model source or asynchronous user can issue traffic; all - // original symbolic resources remain kept by this completion owner. - unsafe { completion.drain() } + + pub(crate) fn programming(&mut self) -> Result<(), Error> { + let route = self.route.as_ref().ok_or(Error::Unbound)?; + route.check_process().map_err(|_| Error::Context)?; + self.owner + .as_ref() + .ok_or(Error::RootUnavailable)? + .validate()?; + self.domain + .as_ref() + .ok_or(Error::RootUnavailable)? + .check()?; + self.published = true; + Ok(()) } - #[test] - fn unavailable_root_refuses_even_a_bound_route() { - let mut c = MsiCompletion::unavailable(); - assert_eq!(drain(&c), Err(Error::Unbound)); - bind(&mut c).unwrap(); - assert_eq!(drain(&c), Err(Error::RootUnavailable)); - assert_eq!(drain(&c), Err(Error::RootUnavailable)); + pub(crate) fn check_rearm(&self) -> Result<(), Error> { + let id = self.route.as_ref().ok_or(Error::Unbound)?; + id.check_process().map_err(|_| Error::Context)?; + if self.cpu_retired || self.released { + return Err(Error::NotRetired); + } + self.owner + .as_ref() + .ok_or(Error::RootUnavailable)? + .validate()?; + self.domain.as_ref().ok_or(Error::RootUnavailable)?.check() } - #[test] - fn exact_route_completion_is_one_shot_and_cannot_bind_another_message() { - let state = Arc::new(State::default()); - let mut c = MsiCompletion::model(Box::new(Root(state.clone()))); - assert_eq!(drain(&c), Err(Error::Unbound)); - bind(&mut c).unwrap(); - let attempted = MsiMessage { - data: 0x52, - ..MESSAGE + + pub(crate) fn validate(&self) -> Result<(), Error> { + self.route + .as_ref() + .ok_or(Error::Unbound)? + .check_process() + .map_err(|_| Error::Context)?; + self.owner + .as_ref() + .ok_or(Error::RootUnavailable)? + .validate() + } + pub(crate) fn cpu_retired(&mut self) -> Result<(), Error> { + self.validate()?; + self.domain + .as_ref() + .ok_or(Error::RootUnavailable)? + .check()?; + self.cpu_retired = true; + // Same checked process context after the actual old action join. Slot + // retains its own immutable guard until final locked withdrawal. + drop(self.domain.take()); + Ok(()) + } + pub(crate) fn join_action( + &mut self, + requester: &RequesterId, + route: &RouteId, + ) -> Result<(), Error> { + if self.action_joined + || !self.cpu_retired + || !self.route.as_ref().is_some_and(|own| own.same(route)) + || !self.belongs_to(requester) + { + return Err(Error::NotRetired); + } + self.validate()?; + requester + .complete_action() + .map_err(|_| Error::WrongRequester)?; + self.action_joined = true; + Ok(()) + } + pub(crate) fn release( + &mut self, + route: &RouteId, + detached: &DetachedRequester, + ) -> Result<(), Error> { + if !self.cpu_retired + || !self.action_joined + || !self.route.as_ref().is_some_and(|own| own.same(route)) + { + return Err(Error::NotRetired); + } + if !self + .requester + .as_ref() + .is_some_and(|own| own.same_requester(detached.requester())) + || !detached.matches_route(route) + { + return Err(Error::WrongRequester); + } + if self.released { + return self.validate(); + } + self.validate()?; + let proof = EndpointRetirement { + route, + detached: Some(detached), }; - assert_eq!( - // SAFETY: this isolated fixture owns the second symbolic route; - // the completion must refuse replacing its first bound route. - unsafe { c.bind_route(attempted) }, - Err(Error::AlreadyBound { - original: MESSAGE, - attempted - }) - ); - drain(&c).unwrap(); - drain(&c).unwrap(); - drop(c); - assert_eq!(state.binds.load(Ordering::Relaxed), 1); - assert_eq!(state.drains.load(Ordering::Relaxed), 1); - assert_eq!(state.drops.load(Ordering::Relaxed), 1); + // SAFETY: exact private route/requester proof and acknowledged detach + // follow real action/CPU/work retirement; source pin is still retained. + unsafe { + self.owner + .as_mut() + .ok_or(Error::RootUnavailable)? + .release_endpoint(&proof) + }?; + self.released = true; + Ok(()) } - #[test] - fn failed_binding_is_sticky_and_keeps_the_root_without_drain() { - let state = Arc::new(State::default()); - state.fail_bind.store(true, Ordering::Relaxed); - let mut c = MsiCompletion::model(Box::new(Root(state.clone()))); - assert_eq!(bind(&mut c), Err(Error::RootFailed)); - state.fail_bind.store(false, Ordering::Relaxed); - assert_eq!(drain(&c), Err(Error::RootFailed)); - drop(c); - assert_eq!(state.drains.load(Ordering::Relaxed), 0); - assert_eq!(state.drops.load(Ordering::Relaxed), 0); + #[cfg(any(test, feature = "test-support", feature = "irq-diagnostics"))] + pub(crate) fn release_fixture(&mut self, route: &RouteId) -> Result<(), Error> { + if !matches!(self.origin, Origin::BoundedFixture) + || self.requester.is_some() + || !self.cpu_retired + || self.released + || !self.route.as_ref().is_some_and(|own| own.same(route)) + { + return Err(Error::NotRetired); + } + self.validate()?; + let proof = EndpointRetirement { + route, + detached: None, + }; + // SAFETY: this constructor is scoped to an explicit no-native-pin + // fixture provider, with exact action/CPU/work retirement, not a native + // requester/DMA detach or a successful empty endpoint resource. + unsafe { + self.owner + .as_mut() + .ok_or(Error::RootUnavailable)? + .release_endpoint(&proof) + }?; + self.released = true; + Ok(()) } - #[test] - fn abandoned_or_failed_completion_keeps_the_original_root() { - for failed in [false, true] { - let state = Arc::new(State::default()); - let mut c = MsiCompletion::model(Box::new(Root(state.clone()))); - bind(&mut c).unwrap(); - if failed { - state.fail_drain.store(true, Ordering::Relaxed); - assert_eq!(drain(&c), Err(Error::RootFailed)); + pub(crate) fn cancel(mut self, requester: &RequesterId) -> Result<(), (Error, Self)> { + let result = (|| { + if self.published + || self.route.is_some() + || !self + .requester + .as_ref() + .is_some_and(|own| own.same_requester(requester)) + { + return Err(Error::WrongRequester); } - drop(c); - assert_eq!(state.drops.load(Ordering::Relaxed), 0); + if let Some(owner) = self.owner.as_ref() { + owner.validate()?; + } + // The original Attachment checked its live native context before + // this explicit prepublication cancellation. No hardware was armed. + drop(self.owner.take()); + requester + .complete_action() + .map_err(|_| Error::WrongRequester)?; + self.released = true; + Ok(()) + })(); + match result { + Ok(()) => Ok(()), + Err(error) => Err((error, self)), } } } +impl Drop for MsiRoute { + fn drop(&mut self) { + if self.released + && self + .owner + .as_ref() + .is_none_or(|owner| owner.validate().is_ok()) + { + // SAFETY: explicit checked release already ended any config pin; + // the provider now owns only terminal observation whose Drop must + // leave the canonical root ledger and blocking resources retained. + unsafe { + ManuallyDrop::drop(&mut self.owner); + ManuallyDrop::drop(&mut self.domain); + }; + } + // Every other path retains the actual Box, even after action join. + } +} diff --git a/crates/stela-driver-base/src/bus/irq/tests.rs b/crates/stela-driver-base/src/bus/irq/tests.rs index 02e90ecc61..b44cac1a6f 100644 --- a/crates/stela-driver-base/src/bus/irq/tests.rs +++ b/crates/stela-driver-base/src/bus/irq/tests.rs @@ -1,11 +1,25 @@ use super::*; +use posted_msi::RouteOwner; extern crate std; struct Model { ticks: AtomicU64, pending: AtomicBool, fail_pending: AtomicBool, + fail_eoi: AtomicBool, + dispatch_on_program: AtomicBool, + dispatch_on_unmask: AtomicBool, + panic_unmask: AtomicBool, + panic_pending: AtomicBool, + panic_window: AtomicBool, + irq_enabled: AtomicBool, + root_epoch: AtomicU64, fail_mask: AtomicBool, + panic_mask: AtomicBool, + panic_sync: AtomicBool, + root_pending: AtomicBool, + root_checks: AtomicUsize, + root_fences: AtomicUsize, wrong_cpu: AtomicBool, fail_target: AtomicBool, invalid_target: AtomicBool, @@ -25,7 +39,20 @@ impl Model { ticks: AtomicU64::new(0), pending: AtomicBool::new(false), fail_pending: AtomicBool::new(false), + fail_eoi: AtomicBool::new(false), + dispatch_on_program: AtomicBool::new(false), + dispatch_on_unmask: AtomicBool::new(false), + panic_unmask: AtomicBool::new(false), + panic_pending: AtomicBool::new(false), + panic_window: AtomicBool::new(false), + irq_enabled: AtomicBool::new(true), + root_epoch: AtomicU64::new(1), fail_mask: AtomicBool::new(false), + panic_mask: AtomicBool::new(false), + panic_sync: AtomicBool::new(false), + root_pending: AtomicBool::new(false), + root_checks: AtomicUsize::new(0), + root_fences: AtomicUsize::new(0), wrong_cpu: AtomicBool::new(false), fail_target: AtomicBool::new(false), invalid_target: AtomicBool::new(false), @@ -53,11 +80,15 @@ unsafe impl Platform for ModelPlatform { Ok(()) } } + fn check_process(&self) -> Result<(), crate::bus::irq::IrqError> { + self.check_cpu() + } fn save_and_disable(&self) -> u64 { - 0 + u64::from(self.0.irq_enabled.swap(false, Ordering::AcqRel)) } unsafe fn restore(&self, saved: u64) { - assert_eq!(saved, 0); + assert!(saved <= 1); + self.0.irq_enabled.store(saved != 0, Ordering::Release); } fn target(&self, vector: u8) -> Result { if self.0.fail_target.load(Ordering::Relaxed) { @@ -74,15 +105,23 @@ unsafe impl Platform for ModelPlatform { }) } fn pending(&self, _: u8) -> Result { + assert!( + !self.0.panic_pending.load(Ordering::Relaxed), + "injected pending unwind" + ); if self.0.fail_pending.load(Ordering::Relaxed) { Err(IrqError::FailedRead) } else { Ok(self.0.pending.load(Ordering::Relaxed)) } } - fn eoi(&self) { + fn eoi(&self, _vector: u8) -> Result { self.0.eois.fetch_add(1, Ordering::Relaxed); + if self.0.fail_eoi.load(Ordering::Acquire) { + return Err(IrqError::FailedRead); + } self.0.pending.store(false, Ordering::Relaxed); + Ok(crate::bus::irq::Trigger::Edge) } fn ticks(&self) -> u64 { self.0.ticks.fetch_add(1, Ordering::Relaxed) @@ -91,6 +130,10 @@ unsafe impl Platform for ModelPlatform { 8 } unsafe fn interrupt_window(&self) { + assert!( + !self.0.panic_window.load(Ordering::Relaxed), + "injected window unwind" + ); if self.0.admit_irq.load(Ordering::Relaxed) && self.0.pending.load(Ordering::Relaxed) { // SAFETY: the model registry is leaked/stable, and closing // keeps its source/context for this pending delivery. @@ -99,11 +142,118 @@ unsafe impl Platform for ModelPlatform { } } } + +struct ModelDomain { + model: Arc, + epoch: u64, +} +// SAFETY: same explicit controller/source model and its actual epoch/CPU state; +// no native permission or physical source is fabricated by this fixture. +unsafe impl posted_msi::NotificationDomain for ModelDomain { + fn check(&self) -> Result<(), posted_msi::Error> { + if self.model.wrong_cpu.load(Ordering::Acquire) { + return Err(posted_msi::Error::Context); + } + if self.model.root_epoch.load(Ordering::Acquire) != self.epoch { + return Err(posted_msi::Error::RootFailed); + } + Ok(()) + } +} +struct DeliveryPeer { + model: Arc, + allocated: bool, + epoch: u64, +} +// SAFETY: explicit isolated no-native-pin route peer. Its independent pending +// state is not source stop, payload, CPU IRR/ISR or a native delivery receipt. +unsafe impl posted_msi::RouteOwner for DeliveryPeer { + fn allocate( + &mut self, + target: &CpuTarget<'_>, + ) -> Result { + target + .check_current() + .map_err(|_| posted_msi::AllocationError::Unexposed(posted_msi::Error::Context))?; + if self.allocated { + return Err(posted_msi::AllocationError::Unexposed( + posted_msi::Error::AlreadyBound, + )); + } + self.allocated = true; + let target = target.descriptor(); + Ok(MsiMessage { + address: 0xfee0_0000 | u64::from(target.destination) << 12, + data: u32::from(target.vector), + }) + } + fn validate(&self) -> Result<(), posted_msi::Error> { + self.model.root_checks.fetch_add(1, Ordering::Relaxed); + if self.model.root_epoch.load(Ordering::Acquire) != self.epoch { + return Err(posted_msi::Error::RootFailed); + } + if self.model.wrong_cpu.load(Ordering::Relaxed) { + Err(posted_msi::Error::Context) + } else { + Ok(()) + } + } + fn notification_domain( + &self, + ) -> Result, posted_msi::Error> { + self.validate()?; + Ok(Arc::new(ModelDomain { + model: self.model.clone(), + epoch: self.epoch, + })) + } + unsafe fn strong_fence(&mut self) -> Result<(), posted_msi::Error> { + self.validate()?; + if self.model.root_pending.load(Ordering::Relaxed) { + return Err(posted_msi::Error::RootFailed); + } + self.model.root_fences.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + unsafe fn release_endpoint( + &mut self, + proof: &posted_msi::EndpointRetirement<'_>, + ) -> Result<(), posted_msi::Error> { + self.validate()?; + assert!(proof.requester().is_none()); + Ok(()) + } +} +fn fixture_route(model: &Arc) -> RouteRequest { + // SAFETY: this original synchronous model carries no native config pin; + // private Registry target joins it, and its independent root state fences. + RouteRequest::Msi(unsafe { + posted_msi::MsiRoute::bounded_fixture(Box::new(DeliveryPeer { + model: model.clone(), + allocated: false, + epoch: model.root_epoch.load(Ordering::Acquire), + })) + }) +} +fn finish(retired: RetiredSource) { + // SAFETY: these fixture sources have no DMA-dependent release users; keep + // the original callback through explicit source release on the checked CPU. + let (source, handler, mut route) = + unsafe { retired.into_parts() }.unwrap_or_else(|_| panic!("checked retired fixture")); + route.release_unattached_fixture().unwrap(); + drop(source); + drop(handler); +} + struct ModelSource(Arc); // SAFETY: explicit stopped-source model with injected mask failures and // controller delivery. Quiesce represents device/work completion. unsafe impl Source for ModelSource { fn mask(&mut self) -> Result<(), IrqError> { + assert!( + !self.0.panic_mask.load(Ordering::Relaxed), + "injected source unwind" + ); if self.0.fail_mask.load(Ordering::Relaxed) { Err(IrqError::Mask) } else { @@ -114,11 +264,17 @@ unsafe impl Source for ModelSource { self.0.quiesces.fetch_add(1, Ordering::Relaxed); Ok(()) } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> crate::bus::irq::RouteKind { + crate::bus::irq::RouteKind::Msi } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { - let Route::Msi(message) = route else { + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + None + } + unsafe fn program( + &mut self, + route: &crate::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { + let Route::Msi(message) = route.programming() else { return Err(IrqError::Route); }; assert_eq!(message.address, 0xfee00000); @@ -126,9 +282,24 @@ unsafe impl Source for ModelSource { message.data, u32::from(self.0.vector.load(Ordering::Relaxed)) ); + if self.0.dispatch_on_program.swap(false, Ordering::AcqRel) { + // SAFETY: exact permanently retained model Registry; this models + // an old ordinary packet during masked new source programming. + let registry = unsafe { &*self.0.registry.load(Ordering::Acquire) }; + assert!(registry.dispatch(self.0.vector.load(Ordering::Acquire))); + } Ok(()) } unsafe fn unmask(&mut self) -> Result<(), IrqError> { + if self.0.dispatch_on_unmask.swap(false, Ordering::AcqRel) { + // SAFETY: exact retained synchronous model original controller. + let registry = unsafe { &*self.0.registry.load(Ordering::Acquire) }; + assert!(registry.dispatch(self.0.vector.load(Ordering::Acquire))); + } + assert!( + !self.0.panic_unmask.load(Ordering::Acquire), + "post-LIVE enable panic" + ); Ok(()) } unsafe fn synchronize(&mut self) -> Result<(), IrqError> { @@ -137,6 +308,10 @@ unsafe impl Source for ModelSource { } impl ModelSource { fn synchronized(&mut self) -> Result<(), IrqError> { + assert!( + !self.0.panic_sync.load(Ordering::Relaxed), + "injected work unwind" + ); self.quiesce() } } @@ -167,10 +342,11 @@ fn request( model: &Arc, ) -> Registration<'static, ModelPlatform> { registry - .request( - Box::new(ModelSource(model.clone())), - Arc::new(ModelHandler(model.clone())), - ) + .request(Request { + source: Box::new(ModelSource(model.clone())), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(model), + }) .unwrap() } @@ -190,10 +366,16 @@ unsafe impl Source for LocalSource { fn quiesce(&mut self) -> Result<(), IrqError> { self.inner.quiesce() } - fn route(&self) -> RouteRequest { - self.inner.route() + fn route_kind(&self) -> crate::bus::irq::RouteKind { + self.inner.route_kind() } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + self.inner.requester() + } + unsafe fn program( + &mut self, + route: &crate::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { // SAFETY: forwards the wrapped source's own call under the same contract. unsafe { self.inner.program(route) } } @@ -238,18 +420,19 @@ fn local_source_releases_before_handler_only_on_checked_cpu() { let registry = registry(model.clone()); let token = std::rc::Rc::new(core::cell::Cell::new(0)); let mut registration = registry - .request( - local_source(&model, token.clone()), - Arc::new(ModelHandler(model.clone())), - ) + .request(Request { + source: local_source(&model, token.clone()), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) .unwrap(); model.migrate_on_sync.store(true, Ordering::Relaxed); - assert_eq!(registration.retire(), Err(IrqError::WrongCpu)); + assert!(matches!(registration.retire(), Err(IrqError::WrongCpu))); assert_eq!(token.get(), 0); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); model.migrate_on_sync.store(false, Ordering::Relaxed); model.wrong_cpu.store(false, Ordering::Relaxed); - registration.retire().unwrap(); + finish(registration.retire().unwrap()); assert_eq!(token.get(), 1); assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 1); @@ -260,40 +443,43 @@ fn returned_local_source_keeps_callback_context_through_its_final_release() { let registry = registry(model.clone()); let token = std::rc::Rc::new(core::cell::Cell::new(0)); let mut registration = registry - .request( - local_source(&model, token.clone()), - Arc::new(ModelHandler(model.clone())), - ) + .request(Request { + source: local_source(&model, token.clone()), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) .unwrap(); - let retired = registration.retire_source().unwrap(); + let retired = registration.retire().unwrap(); assert_eq!(token.get(), 0); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); - drop(retired); + finish(retired); assert_eq!(token.get(), 1); assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 1); } #[test] -fn untouched_typed_refusal_keeps_affine_source_and_callback_bound_for_default_drop() { +fn untouched_typed_refusal_retains_affine_source_and_callback_on_abandonment() { let model = Model::new(); let registry = registry(model.clone()); let token = std::rc::Rc::new(core::cell::Cell::new(0)); model.fail_target.store(true, Ordering::Relaxed); - let Err(refusal) = registry.request_owned( - LocalSource { - inner: ModelSource(model.clone()), - token: token.clone(), - owner: std::thread::current().id(), - }, - Arc::new(ModelHandler(model.clone())), - ) else { - panic!("failed target registered") - }; - assert!(refusal.returned.is_some()); + { + let Err(refusal) = registry.request_owned(Request { + source: LocalSource { + inner: ModelSource(model.clone()), + token: token.clone(), + owner: std::thread::current().id(), + }, + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) else { + panic!("failed target registered") + }; + assert!(refusal.returned.is_some()); + assert_eq!(token.get(), 0); + } assert_eq!(token.get(), 0); - drop(refusal); - assert_eq!(token.get(), 1); - assert_eq!(model.handler_drops.load(Ordering::Relaxed), 1); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); } #[test] fn all_early_admission_errors_keep_affine_source_and_callback_owner() { @@ -310,34 +496,36 @@ fn all_early_admission_errors_keep_affine_source_and_callback_owner() { model.fail_target.store(case == 1, Ordering::Relaxed); model.invalid_target.store(case == 2, Ordering::Relaxed); let token = std::rc::Rc::new(core::cell::Cell::new(0)); - let result = registry.request( - local_source(&model, token.clone()), - Arc::new(ModelHandler(model.clone())), - ); - let Err(refusal) = result else { - panic!("an inadmissible request registered"); - }; - assert_eq!( - refusal.error, - [ - IrqError::WrongCpu, - IrqError::Route, - IrqError::Route, - IrqError::Exhausted - ][case] - ); - assert_eq!(token.get(), 0); - assert_eq!(std::rc::Rc::strong_count(&token), 2); - assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); - assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); - // Only a wrong-CPU refusal keeps the owners; the others return - // them untouched for the driver to keep polling with. - assert_eq!(refusal.returned.is_some(), case != 0); - assert_eq!(registry.quarantine_count(), u64::from(case == 0)); - drop(refusal); + { + let result = registry.request(Request { + source: local_source(&model, token.clone()), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }); + let Err(refusal) = result else { + panic!("an inadmissible request registered"); + }; + assert_eq!( + refusal.error, + [ + IrqError::WrongCpu, + IrqError::Route, + IrqError::Route, + IrqError::Exhausted + ][case] + ); + assert_eq!(token.get(), 0); + assert_eq!(std::rc::Rc::strong_count(&token), 2); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); + // Only a wrong-CPU refusal keeps the owners; the others return + // them untouched for the driver to keep polling with. + assert_eq!(refusal.returned.is_some(), case != 0); + assert_eq!(registry.quarantine_count(), u64::from(case == 0)); + } model.wrong_cpu.store(false, Ordering::Relaxed); for mut registered in occupied { - registered.retire().unwrap(); + finish(registered.retire().unwrap()); } } } @@ -352,10 +540,11 @@ fn foreign_thread_admission_and_abandoned_migration_never_drop_local_owner() { let other = model.clone(); std::thread::spawn(move || { let token = std::rc::Rc::new(core::cell::Cell::new(0)); - let result = registry.request( - local_source(&other, token.clone()), - Arc::new(ModelHandler(other.clone())), - ); + let result = registry.request(Request { + source: local_source(&other, token.clone()), + handler: Arc::new(ModelHandler(other.clone())), + routing: fixture_route(&other), + }); assert!(matches!( result, Err(RequestError { @@ -371,10 +560,11 @@ fn foreign_thread_admission_and_abandoned_migration_never_drop_local_owner() { assert_eq!(registry.quarantine_count(), 1); let token = std::rc::Rc::new(core::cell::Cell::new(0)); let registration = registry - .request( - local_source(&model, token.clone()), - Arc::new(ModelHandler(model.clone())), - ) + .request(Request { + source: local_source(&model, token.clone()), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) .unwrap(); model.wrong_cpu.store(true, Ordering::Relaxed); drop(registration); @@ -410,11 +600,17 @@ fn immutable_sharing_invokes_all_members_and_preserves_unclaimed_status() { assert_eq!(Arc::strong_count(&a), 2); let model = Model::new(); let r = registry(model.clone()); - let mut registration = r.request(Box::new(ModelSource(model.clone())), a).unwrap(); + let mut registration = r + .request(Request { + source: Box::new(ModelSource(model.clone())), + handler: a, + routing: fixture_route(&model), + }) + .unwrap(); assert!(r.dispatch(registration.vector())); assert_eq!(registration.handled(), Ok(0)); assert_eq!(model.eois.load(Ordering::Relaxed), 1); - registration.retire().unwrap(); + finish(registration.retire().unwrap()); } #[test] @@ -430,14 +626,14 @@ fn real_registration_lifetime_drains_pending_delivery_before_final_release_and_r assert_eq!(model.eois.load(Ordering::Relaxed), 1); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); model.pending.store(true, Ordering::Relaxed); - registration.retire().unwrap(); - assert!(!registry.dispatch(vector)); + finish(registration.retire().unwrap()); + assert!(registry.dispatch(vector)); assert_eq!( model.callbacks.load(Ordering::Relaxed), 1, "closing IRQ must not enter the detached device callback" ); - assert_eq!(model.eois.load(Ordering::Relaxed), 2); + assert_eq!(model.eois.load(Ordering::Relaxed), 3); assert_eq!( model.quiesces.load(Ordering::Relaxed), 3, @@ -447,7 +643,7 @@ fn real_registration_lifetime_drains_pending_delivery_before_final_release_and_r assert_eq!(model.handler_drops.load(Ordering::Relaxed), 1); let mut reused = request(registry, &model); assert_eq!(reused.vector(), vector); - reused.retire().unwrap(); + finish(reused.retire().unwrap()); } #[test] @@ -455,10 +651,11 @@ fn concrete_source_handoff_returns_original_owner_only_after_acknowledged_drain( let model = Model::new(); let registry = registry(model.clone()); let mut registration = registry - .request_owned( - ModelSource(model.clone()), - Arc::new(ModelHandler(model.clone())), - ) + .request_owned(Request { + source: ModelSource(model.clone()), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) .unwrap(); let vector = registration.vector(); model.pending.store(true, Ordering::Relaxed); @@ -471,20 +668,22 @@ fn concrete_source_handoff_returns_original_owner_only_after_acknowledged_drain( assert_eq!(retired.route().vector(), vector); // SAFETY: this concrete modeled source has no release dependency; // keep its callback until after explicit source destruction. - let (source, handler, route) = unsafe { retired.into_parts() }; + let (source, handler, mut route) = + unsafe { retired.into_parts() }.unwrap_or_else(|_| panic!("checked retired owner")); assert!(Arc::ptr_eq(&source.0, &model)); assert_eq!(route.vector(), vector); assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); assert_eq!(model.eois.load(Ordering::Relaxed), 1); - assert!(!registry.dispatch(vector)); + assert!(registry.dispatch(vector)); assert!(matches!(registration.retire(), Err(IrqError::Unregistered))); + route.release_unattached_fixture().unwrap(); drop(source); drop(handler); assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); let mut reused = request(registry, &model); assert_eq!(reused.vector(), vector); - reused.retire().unwrap(); + finish(reused.retire().unwrap()); } #[test] @@ -492,23 +691,31 @@ fn typed_early_refusal_preserves_original_source_for_untouched_retry() { let model = Model::new(); let registry = registry(model.clone()); model.fail_target.store(true, Ordering::Relaxed); - let Err(refusal) = registry.request_owned( - ModelSource(model.clone()), - Arc::new(ModelHandler(model.clone())), - ) else { + let Err(refusal) = registry.request_owned(Request { + source: ModelSource(model.clone()), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) else { panic!("failed target registered") }; assert_eq!(refusal.error, IrqError::Route); // SAFETY: preserve the original CPU and callback through source // retry below; the refused request has not changed either owner. - let (source, handler) = unsafe { refusal.returned.unwrap().into_parts() }; + let (source, handler, routing) = unsafe { refusal.returned.unwrap().into_parts() } + .unwrap_or_else(|_| panic!("checked untouched owner")); assert!(Arc::ptr_eq(&source.0, &model)); assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); model.fail_target.store(false, Ordering::Relaxed); - let mut registration = registry.request_owned(*source, handler).unwrap(); + let mut registration = registry + .request_owned(Request { + source: *source, + handler, + routing, + }) + .unwrap(); assert_eq!(registry.quarantine_count(), 0); - drop(registration.retire().unwrap()); + finish(registration.retire().unwrap()); assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 1); } @@ -519,15 +726,15 @@ fn failed_pending_read_and_timeout_keep_for_retry_without_vector_reuse() { let registry = registry(model.clone()); let mut registration = request(registry, &model); model.fail_pending.store(true, Ordering::Relaxed); - assert_eq!(registration.retire(), Err(IrqError::FailedRead)); + assert!(matches!(registration.retire(), Err(IrqError::FailedRead))); assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); model.fail_pending.store(false, Ordering::Relaxed); model.pending.store(true, Ordering::Relaxed); model.admit_irq.store(false, Ordering::Relaxed); - assert_eq!(registration.retire(), Err(IrqError::Drain)); + assert!(matches!(registration.retire(), Err(IrqError::Drain))); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); model.admit_irq.store(true, Ordering::Relaxed); - registration.retire().unwrap(); + finish(registration.retire().unwrap()); assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); } @@ -545,10 +752,11 @@ fn failed_teardown_or_arming_quarantines_the_source() { assert!(registry.dispatch(vector)); assert_eq!(model.callbacks.load(Ordering::Relaxed), 0); assert!(matches!( - registry.request( - Box::new(ModelSource(model.clone())), - Arc::new(ModelHandler(model.clone())) - ), + registry.request(Request { + source: Box::new(ModelSource(model.clone())), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model) + }), Err(RequestError { error: IrqError::Mask, returned: None @@ -586,14 +794,18 @@ fn callback_borrow_outlives_failed_removal_without_arc_clone_or_early_release() model: model.clone(), }); let mut registration = registry - .request(Box::new(ModelSource(model.clone())), handler.clone()) + .request(Request { + source: Box::new(ModelSource(model.clone())), + handler: handler.clone(), + routing: fixture_route(&model), + }) .unwrap(); let vector = registration.vector(); // Concurrent model interleaving stresses the reader/remove lifetime; // the native adapter remains confined to its one owning BSP. let irq = std::thread::spawn(move || assert!(registry.dispatch(vector))); handler.entered.wait(); - assert_eq!(registration.retire(), Err(IrqError::Drain)); + assert!(matches!(registration.retire(), Err(IrqError::Drain))); assert_eq!( Arc::strong_count(&handler), 2, @@ -602,10 +814,388 @@ fn callback_borrow_outlives_failed_removal_without_arc_clone_or_early_release() assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); handler.release.wait(); irq.join().unwrap(); - registration.retire().unwrap(); + finish(registration.retire().unwrap()); assert_eq!(Arc::strong_count(&handler), 1); assert_eq!(model.eois.load(Ordering::Relaxed), 1); assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); drop(handler); assert_eq!(model.handler_drops.load(Ordering::Relaxed), 1); } + +#[test] +fn notification_action_join_does_not_claim_optional_fabric_completion() { + let model = Model::new(); + let registry = registry(model.clone()); + let mut registration = request(registry, &model); + model.root_pending.store(true, Ordering::Relaxed); + let mut stronger = DeliveryPeer { + model: model.clone(), + allocated: true, + epoch: 1, + }; + assert_eq!( + // SAFETY: independent explicit model source is masked; this optional peer + // refuses its stronger proof while notification/action retirement can join. + unsafe { stronger.strong_fence() }, + Err(posted_msi::Error::RootFailed) + ); + let retired = registration.retire().unwrap(); + assert_eq!(model.root_fences.load(Ordering::Relaxed), 0); + model.wrong_cpu.store(true, Ordering::Relaxed); + assert_eq!(retired.route().validate(), Err(IrqError::WrongCpu)); + model.wrong_cpu.store(false, Ordering::Relaxed); + finish(retired); +} +#[test] +fn domain_loss_and_eoi_failure_preserve_exact_error_and_old_owners() { + for root_loss in [false, true] { + let model = Model::new(); + let registry = registry(model.clone()); + let mut registration = request(registry, &model); + if root_loss { + model.root_epoch.store(2, Ordering::Release); + } else { + model.fail_eoi.store(true, Ordering::Release); + } + assert!(registry.dispatch(registration.vector())); + assert_eq!( + model.callbacks.load(Ordering::Relaxed), + usize::from(!root_loss) + ); + let expected = if root_loss { + IrqError::Delivery(posted_msi::Error::RootFailed) + } else { + IrqError::FailedRead + }; + assert!(matches!(registration.retire(),Err(error) if error==expected)); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); + } +} +#[test] +fn delayed_ordinary_notification_enters_only_current_valid_status_handler() { + struct StatusHandler { + cause: AtomicBool, + completions: AtomicUsize, + entries: AtomicUsize, + } + impl Handler for StatusHandler { + fn handle(&self) -> Disposition { + self.entries.fetch_add(1, Ordering::Relaxed); + if self.cause.swap(false, Ordering::AcqRel) { + self.completions.fetch_add(1, Ordering::Relaxed); + Disposition::Handled + } else { + Disposition::NotMine + } + } + } + let model = Model::new(); + let registry = registry(model.clone()); + let mut old = request(registry, &model); + let vector = old.vector(); + model.root_pending.store(true, Ordering::Release); // unrelated old ordinary packet + finish(old.retire().unwrap()); + let current = Arc::new(StatusHandler { + cause: AtomicBool::new(false), + completions: AtomicUsize::new(0), + entries: AtomicUsize::new(0), + }); + let mut new = registry + .request(Request { + source: Box::new(ModelSource(model.clone())), + handler: current.clone(), + routing: fixture_route(&model), + }) + .unwrap(); + assert_eq!(new.vector(), vector); + assert!(registry.dispatch(vector)); // late old packet: no current cause + assert_eq!(current.completions.load(Ordering::Relaxed), 0); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 0); + current.cause.store(true, Ordering::Release); + assert!(registry.dispatch(vector)); + assert_eq!(current.completions.load(Ordering::Relaxed), 1); + assert_eq!(current.entries.load(Ordering::Relaxed), 2); + finish(new.retire().unwrap()); +} +#[test] +fn abandoned_successful_retirement_does_not_drop_original_source_or_handler() { + let model = Model::new(); + let registry = registry(model.clone()); + let mut registration = request(registry, &model); + drop(registration.retire().unwrap()); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); +} + +#[test] +fn exact_route_identity_rejects_a_later_registration_reusing_the_same_vector() { + let model = Model::new(); + let registry = registry(model.clone()); + let mut first = request(registry, &model); + let old = first.retire().unwrap(); + let mut second = request(registry, &model); + let replacement = second.retire().unwrap(); + assert_eq!(old.route().vector(), replacement.route().vector()); + assert!(!old.route().id().same(replacement.route().id())); + finish(old); + finish(replacement); +} + +#[test] +fn unavailable_notification_refuses_before_programming_and_returns_exact_grant() { + struct AttachedModel(ModelSource, RequesterId); + // SAFETY: this isolated source peer contains no native owner; only the + // actual symbolic Registry route can reach its programming callbacks. + unsafe impl Source for AttachedModel { + fn route_kind(&self) -> RouteKind { + RouteKind::Msi + } + fn requester(&self) -> Option<&RequesterId> { + Some(&self.1) + } + fn mask(&mut self) -> Result<(), IrqError> { + self.0.mask() + } + fn quiesce(&mut self) -> Result<(), IrqError> { + self.0.quiesce() + } + unsafe fn program(&mut self, route: &AllocatedRoute<'_>) -> Result<(), IrqError> { + assert!(route.matches_requester(&self.1)); + // SAFETY: forwards the same symbolic Registry programming view. + unsafe { self.0.program(route) } + } + unsafe fn unmask(&mut self) -> Result<(), IrqError> { + // SAFETY: forwards the same retained model callback obligation. + unsafe { self.0.unmask() } + } + unsafe fn synchronize(&mut self) -> Result<(), IrqError> { + // SAFETY: Registry must establish exact model retirement first. + unsafe { self.0.synchronize() } + } + } + let model = Model::new(); + let registry = registry(model.clone()); + let requester = RequesterId::new(); + let grant = posted_msi::MsiRoute::attached(requester.clone(), None) + .unwrap_or_else(|_| panic!("idle model key")); + let refusal = registry + .request(Request { + source: Box::new(AttachedModel(ModelSource(model.clone()), requester.clone())), + handler: Arc::new(ModelHandler(model.clone())), + routing: RouteRequest::Msi(grant), + }) + .err() + .expect("unavailable notification cannot arm"); + assert_eq!( + refusal.error, + IrqError::Delivery(posted_msi::Error::RootUnavailable) + ); + assert!( + requester.check_detach().is_err(), + "issuance stays outstanding until exact cancellation" + ); + assert_eq!(model.quiesces.load(Ordering::Relaxed), 0); + // SAFETY: exact original untouched model owner and current context. + let (source, handler, routing) = unsafe { refusal.returned.unwrap().into_parts() } + .unwrap_or_else(|_| panic!("untouched exact owners")); + let RouteRequest::Msi(grant) = routing else { + panic!("MSI grant") + }; + grant + .cancel(&requester) + .unwrap_or_else(|_| panic!("exact unpublished cancellation")); + assert!(requester.check_detach().is_ok()); + drop(source); + drop(handler); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 1); +} + +#[test] +fn source_callback_unwind_poison_retains_without_hardware_retry_on_drop() { + let model = Model::new(); + let registry = registry(model.clone()); + model.panic_mask.store(true, Ordering::Relaxed); + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| request(registry, &model))) + .is_err() + ); + assert_eq!(registry.quarantine_count(), 1); + assert!(registry.dispatch(FIRST_VECTOR)); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 0); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + model.panic_mask.store(false, Ordering::Relaxed); + let mut registration = request(registry, &model); + model.panic_sync.store(true, Ordering::Relaxed); + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| registration.retire())).is_err() + ); + let fences = model.root_fences.load(Ordering::Relaxed); + model.panic_sync.store(false, Ordering::Relaxed); + assert!(matches!(registration.retire(), Err(IrqError::Drain))); + drop(registration); + assert_eq!(model.root_fences.load(Ordering::Relaxed), fences); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(registry.quarantine_count(), 2); +} + +#[test] +fn pending_and_delivery_window_unwind_restore_the_exact_original_irq_state() { + for window in [false, true] { + let model = Model::new(); + let registry = registry(model.clone()); + let mut registration = request(registry, &model); + model.pending.store(true, Ordering::Release); + if window { + model.panic_window.store(true, Ordering::Release); + } else { + model.panic_pending.store(true, Ordering::Release); + } + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| registration.retire())) + .is_err() + ); + assert!(model.irq_enabled.load(Ordering::Acquire)); + assert_eq!(registry.quarantine_count(), 1); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + let fences = model.root_fences.load(Ordering::Relaxed); + drop(registration); + assert_eq!(model.root_fences.load(Ordering::Relaxed), fences); + } +} +#[test] +fn extraction_preserves_exact_root_epoch_error_and_retains_original_owners() { + let model = Model::new(); + let registry = registry(model.clone()); + let mut registration = request(registry, &model); + let retired = registration.retire().unwrap(); + model.root_epoch.fetch_add(1, Ordering::AcqRel); + { + // SAFETY: this negative test attempts extraction through the actual + // original receipt; epoch mismatch must refuse before moving any owner. + let refusal = match unsafe { retired.into_parts() } { + Ok(_) => panic!("stale root extracted"), + Err(refusal) => refusal, + }; + assert_eq!( + refusal.error, + IrqError::Delivery(posted_msi::Error::RootFailed) + ); + } + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); +} + +#[test] +fn unbound_delayed_eoi_failure_poison_is_not_lost_before_replacement_admission() { + let model = Model::new(); + let registry = registry(model.clone()); + let mut old = request(registry, &model); + let vector = old.vector(); + finish(old.retire().unwrap()); + model.fail_eoi.store(true, Ordering::Release); + assert!(registry.dispatch(vector)); // owns vector, not successful EOI + assert_eq!(registry.controller_failure(), Some(IrqError::FailedRead)); + model.fail_eoi.store(false, Ordering::Release); // cannot erase uncertain effect + let quiesces = model.quiesces.load(Ordering::Relaxed); + let refusal = registry + .request(Request { + source: Box::new(ModelSource(model.clone())), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }) + .err() + .unwrap(); + assert_eq!(refusal.error, IrqError::FailedRead); + assert!(refusal.returned.is_some()); + assert_eq!(model.quiesces.load(Ordering::Relaxed), quiesces); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 0); +} + +#[test] +fn arming_notification_never_enters_new_handler_or_overwrites_eoi_quarantine() { + for failed_eoi in [false, true] { + let model = Model::new(); + let registry = registry(model.clone()); + model.dispatch_on_program.store(true, Ordering::Release); + model.fail_eoi.store(failed_eoi, Ordering::Release); + let result = registry.request(Request { + source: Box::new(ModelSource(model.clone())), + handler: Arc::new(ModelHandler(model.clone())), + routing: fixture_route(&model), + }); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 0); + assert_eq!(model.eois.load(Ordering::Relaxed), 1); + if failed_eoi { + let refusal = result.err().unwrap(); + assert_eq!(refusal.error, IrqError::FailedRead); + assert!(refusal.returned.is_none()); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); + } else { + let mut registration = result.unwrap(); + assert!(registry.dispatch(registration.vector())); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 1); + finish(registration.retire().unwrap()); + } + } +} + +#[test] +fn post_live_delivery_then_enable_panic_never_returns_unexposed_owners() { + let model = Model::new(); + let registry = registry(model.clone()); + model.dispatch_on_unmask.store(true, Ordering::Release); + model.panic_unmask.store(true, Ordering::Release); + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| request(registry, &model))) + .is_err() + ); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 1); + assert_eq!(registry.quarantine_count(), 1); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); + let old = model.vector.load(Ordering::Acquire); + assert!(registry.dispatch(old)); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 1); + model.panic_unmask.store(false, Ordering::Release); + let mut next = request(registry, &model); + assert_ne!(next.vector(), old); + finish(next.retire().unwrap()); +} + +#[test] +fn handler_unwind_poison_retains_inflight_owners_and_never_reenters_callback() { + struct PanicHandler(Arc); + impl Handler for PanicHandler { + fn handle(&self) -> Disposition { + self.0.callbacks.fetch_add(1, Ordering::Relaxed); + panic!("actual handler unwind"); + } + } + impl Drop for PanicHandler { + fn drop(&mut self) { + self.0.handler_drops.fetch_add(1, Ordering::Relaxed); + } + } + let model = Model::new(); + let registry = registry(model.clone()); + let mut registration = registry + .request(Request { + source: Box::new(ModelSource(model.clone())), + handler: Arc::new(PanicHandler(model.clone())), + routing: fixture_route(&model), + }) + .unwrap(); + let vector = registration.vector(); + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| registry.dispatch(vector))) + .is_err() + ); + assert_eq!(registry.controller_failure(), Some(IrqError::Drain)); + assert!(registry.dispatch(vector)); + assert_eq!(model.callbacks.load(Ordering::Relaxed), 1); + assert!(matches!(registration.retire(), Err(IrqError::Drain))); + assert_eq!(model.source_drops.load(Ordering::Relaxed), 0); + assert_eq!(model.handler_drops.load(Ordering::Relaxed), 0); +} diff --git a/crates/stela-driver-base/src/bus/mmio/owned/registry.rs b/crates/stela-driver-base/src/bus/mmio/owned/registry.rs index 638dbdc90f..a1e377ca61 100644 --- a/crates/stela-driver-base/src/bus/mmio/owned/registry.rs +++ b/crates/stela-driver-base/src/bus/mmio/owned/registry.rs @@ -859,6 +859,14 @@ pub struct MappingView { range: Range, } impl MappingView { + /// Compare the actual original installed mapping lease in current scope. + /// Different bounded ranges may share that lease. This supplies no writer, + /// device, root route, reset or completion permission from pointer values. + pub fn shares_mapping(&self, other: &Self) -> Result { + self.check_current()?; + other.check_current()?; + Ok(Shared::ptr_eq(&self.lease, &other.lease)) + } /// Pure current-context/lifetime observation of this exact view. pub fn check_current(&self) -> Result<(), Error> { self.lease diff --git a/crates/stela-driver-base/src/bus/pci/msi.rs b/crates/stela-driver-base/src/bus/pci/msi.rs index ca4e4a92a6..68deea5aa9 100644 --- a/crates/stela-driver-base/src/bus/pci/msi.rs +++ b/crates/stela-driver-base/src/bus/pci/msi.rs @@ -202,9 +202,12 @@ impl MsiConfig { /// dummy token. This keeps the real mapped configuration transport even /// if abandoned. Native config accesses and every source/worker/reset are /// serialized; no firmware/alias/other CPU can reconfigure or revoke it. - /// Old MSI/INTx delivery, callbacks and device work have drained; - /// initially disabled MSI alone does not establish this. The platform has - /// checked MSI routing. No vector or requester-coherency grant is created. + /// Old source actions, CPU/EOI/callbacks and captured service/work have + /// joined under the actual stable notification domain; any old device + /// cause remains owned. A delayed ordinary fixed/edge packet may notify a + /// current valid status-checking handler. Unknown format/root handover needs + /// its independent real completion proof. Initially disabled MSI proves + /// none of this. No vector, domain or requester-coherency grant is created. /// Errors return both owners without modifying configuration. pub unsafe fn new( mut function: Function, @@ -297,11 +300,13 @@ impl MsiConfig { /// /// # Safety /// This typed message belongs to the registry's checked route; - /// every callback/resource remains held. Reprogramming requires real - /// source/callback/posted-write drain; masking alone is insufficient. + /// every callback/resource remains held. Reprogramming requires actual old + /// source/pending-cause closure plus CPU/EOI/captured service/work joins + /// under the same retained notification domain. This is not an all-issued + /// MSI or payload completion receipt; masking alone is insufficient. pub unsafe fn program(&mut self, message: MsiMessage) -> Result<(), MsiError> { self.normal()?; - if message.address & 3 != 0 + if !message.valid_pci_format() || message.data > u32::from(u16::MAX) || (!self.layout.wide() && message.address > u64::from(u32::MAX)) { @@ -356,10 +361,12 @@ impl MsiConfig { /// Return the owners only after independent source/IRQ/work drain. /// /// # Safety - /// The device is stopped, posted MSI writes/CPU pending vectors, - /// callbacks and all deferred/timer/reset users have drained and cannot - /// restart. Every DMA lease/fence/IOTLB obligation remains independently - /// owned until completed; this helper does not prove any of them. + /// Device engines are stopped and old IRQ actions have joined their + /// CPU/EOI/callbacks and captured service/thread/work; former reset users + /// cannot restart. Stable CPU/root/format ownership remains retained for + /// delayed ordinary notifications; this is not all-issued MSI completion. + /// Every payload/DMA lease/fence/IOTLB obligation stays independently owned + /// until completed; returning config owners proves none of them. pub unsafe fn release(&mut self) -> Result, MsiError> { self.disable()?; self.owner.take().ok_or(MsiError::Released) diff --git a/crates/stela-driver-base/src/bus/pci/msi/retirement.rs b/crates/stela-driver-base/src/bus/pci/msi/retirement.rs index 01a0bc8b26..efd46ec4e5 100644 --- a/crates/stela-driver-base/src/bus/pci/msi/retirement.rs +++ b/crates/stela-driver-base/src/bus/pci/msi/retirement.rs @@ -58,9 +58,12 @@ impl DisabledMsiConfig { /// reset configuration space. This does not infer stop from scoped access. /// /// # Safety - /// The source and its DMA/posted writes are stopped/drained. The - /// real registry has subsequently drained pending CPU vectors, callbacks - /// and deferred/timer/reset users, and none can restart. Every mapping, + /// Source engines and their DMA/payload writes are stopped/drained. The + /// exact old IRQ action has joined CPU/EOI/callbacks and captured + /// service/thread/work; former reset users cannot restart. Original stable + /// root/CPU/format ownership remains retained for delayed ordinary fixed/ + /// edge notifications to current valid handlers. This does not establish + /// all-issued MSI completion or reclaim a stronger root ledger. Every mapping, /// cache, domain and IOTLB retirement obligation remains owned until its /// completion. An out-of-band stop can establish these facts without /// using with_device_stop; the presence of an attempt proves none of them. diff --git a/crates/stela-driver-base/src/bus/pci/msi/tests/programming.rs b/crates/stela-driver-base/src/bus/pci/msi/tests/programming.rs index 5e8952fd8b..f50942eed7 100644 --- a/crates/stela-driver-base/src/bus/pci/msi/tests/programming.rs +++ b/crates/stela-driver-base/src/bus/pci/msi/tests/programming.rs @@ -147,3 +147,79 @@ fn message_and_authorization_preflight() { unsafe { helper.release() }.unwrap(), ); } + +#[test] +fn remappable_message_keeps_zero_data_index_bits_widths_and_masks() { + for wide in [false, true] { + for index in [0u64, 1, 0x7fff, 0x8000, 0xffff] { + let message = MsiMessage { + address: 0xfee0_0010 | (index & 0x7fff) << 5 | (index >> 15) << 2, + data: 0, + }; + let (mut helper, model) = attach(fixture(wide, true)); + // SAFETY: exact isolated PCI programming peer only; no native root grant. + unsafe { helper.program(message) }.unwrap(); + { + let m = model.lock().unwrap(); + assert_eq!(m.get(0x54, 4), message.address as u32); + assert_eq!(m.get(if wide { 0x5c } else { 0x58 }, 2), 0); + assert_eq!(m.get(if wide { 0x5e } else { 0x5a }, 2), 0x5a5a); + assert_eq!(m.get(if wide { 0x60 } else { 0x5c }, 4), 0xa5a5_0003); + } + // SAFETY: synchronous original RAM peer only. + drop(unsafe { helper.release() }.unwrap()); + } + } + for message in [ + MsiMessage { + address: 0xfee0_0018, + data: 0, + }, + MsiMessage { + address: 0xfee0_0010, + data: 0x50, + }, + ] { + let (mut helper, model) = attach(fixture(true, true)); + assert_eq!( + // SAFETY: invalid data in an isolated before-effect negative test. + unsafe { helper.program(message) }, + Err(MsiError::InvalidMessage) + ); + assert!( + !model + .lock() + .unwrap() + .events + .iter() + .any(|e| matches!(e, Event::Write(..))) + ); + // SAFETY: never programmed fixture with no asynchronous users. + drop(unsafe { helper.release() }.unwrap()); + } +} + +#[test] +fn remappable_message_does_not_bypass_independent_address_readback() { + let (mut helper, model) = attach(fixture(true, true)); + model.lock().unwrap().block_write = Some((0x54, 4)); + let message = MsiMessage { + address: 0xfeef_fff4, + data: 0, + }; + assert_eq!( + // SAFETY: independent RAM peer deliberately refuses the actual address store. + unsafe { helper.program(message) }, + Err(MsiError::Readback { offset: 0x54 }) + ); + assert!( + model + .lock() + .unwrap() + .events + .iter() + .any(|e| matches!(e, Event::Write(0x54, 4, 0xfeef_fff4))) + ); + // Failure must retain the original owners rather than mint retirement. + drop(helper); +} diff --git a/crates/stela-driver-base/src/bus/pci/msix.rs b/crates/stela-driver-base/src/bus/pci/msix.rs index 80aa63b87c..925dd79b50 100644 --- a/crates/stela-driver-base/src/bus/pci/msix.rs +++ b/crates/stela-driver-base/src/bus/pci/msix.rs @@ -122,14 +122,31 @@ pub struct MsixConfig open: bool, poisoned: bool, } +impl MsixConfig { + /// Retain the actual unique configuration allocation owned by this table. + /// This is read-only lifetime/provenance, never a second config writer or + /// entry/root authorization; current original context is rechecked. + pub fn retain_config_epoch(&self) -> Result { + self.owners + .as_ref() + .ok_or(Error::Released)? + .0 + .config + .retain_epoch() + .map_err(|_| Error::Mapping) + } +} impl MsixConfig { /// # Safety /// Own the unique function/config/root/reset epoch and BAR resources, /// with memory decoding already enabled. BAR array indices are hardware /// BIRs. Ownership must be genuine, not an inert numeric token. - /// Old MSI/MSI-X/INTx sources, callbacks, CPU pending/posted messages - /// and work have drained. MSI-X disabled alone does not prove that. Native - /// MSI routing must be checked separately. Process/deferred context only. + /// Old source actions, CPU/EOI/callbacks and captured service/work have + /// joined under actual stable notification ownership; pending device/PBA + /// causes stay owned. Later ordinary packets may notify a current valid + /// status-checking handler. Unknown root/format handover needs independent + /// real completion, never disabled bits. Native domain/entry authority is + /// checked separately. Process/deferred context only. /// No hardware writes occur on constructor errors; all owners are returned. pub unsafe fn new( function: Function, @@ -348,7 +365,7 @@ impl MsixConfig { message: MsiMessage, legacy: bool, ) -> Result<(), Error> { - if message.address & 3 != 0 { + if !message.valid_pci_format() { return Err(Error::InvalidMessage); } if self.poisoned { @@ -412,10 +429,11 @@ impl MsixConfig { /// # Safety /// Message belongs to the checked IRQ registry/route for this /// function/root epoch, including any real interrupt-remapping permission. - /// The whole affected source set, old posted messages, callbacks and work - /// have drained before this legacy all-mask transition. Masking alone is - /// insufficient. Keep all DMA/IRQ owners kept. Process/deferred - /// context only; this primitive does not validate route authorization. + /// The whole affected source set has closed its old actions and joined + /// CPU/EOI/callbacks plus captured service/work before this all-mask change. + /// Actual pending-cause/PBA semantics and stable notification domain stay + /// owned; this is not all-issued MSI completion. Keep independent DMA/IRQ + /// owners. Process context only; this primitive grants no route authority. pub unsafe fn program(&mut self, message: MsiMessage) -> Result<(), Error> { self.program_entry(0, message, true) } @@ -426,9 +444,11 @@ impl MsixConfig { /// # Safety /// Keep the uniquely owned function/reset/root and checked route /// for the full message, without guessing remapped-address encodings. The - /// target's source, posted messages, callbacks and work are stopped - /// and drained before retargeting; other live routes/callbacks stay held - /// and published throughout. No concurrent table/config/reset access. + /// target entry's old action has joined CPU/EOI/callbacks and captured + /// service/work, with its actual source/pending-cause/PBA semantics owned. + /// Other live routes/callbacks stay held and published throughout. Ordinary + /// delayed notification is not payload completion. No concurrent shared + /// function-control/table/config/reset access or overlapping entry owner. /// Process/deferred context only; masking never proves retirement. pub unsafe fn program_indexed(&mut self, index: u16, message: MsiMessage) -> Result<(), Error> { self.program_entry(index, message, false) @@ -470,10 +490,11 @@ impl MsixConfig { } /// Activate only entry zero and invalidate all nonzero replay messages. /// # Safety - /// The callback/route is installed and published. Any nonzero live - /// sources, pending/posted messages, callbacks and work are stopped/drained - /// before changing to this legacy set. Keep all requester, source/work, - /// reset/DMA and interrupt-controller owners. Process/deferred context only. + /// The callback/route and genuine stable domain are installed. Removed + /// entries have closed their source action and joined CPU/EOI/callbacks and + /// captured service/work; actual pending causes stay owned. This is not + /// all-issued or DMA completion. Keep original requester/source/reset/DMA + /// and controller owners. Process/deferred context only. pub unsafe fn unmask(&mut self) -> Result<(), Error> { self.unmask_entries(&[0], true) } @@ -483,8 +504,9 @@ impl MsixConfig { /// masked. This allocates nothing and never writes device-owned PBA state. /// # Safety /// Every selected entry has an authorized route and already - /// published callback. Removed entries have independently stopped/drained - /// source, posted messages, CPU pending/inflight callbacks and deferred work. + /// published callback and stable notification domain. Removed entries have + /// closed their actual source/pending-cause protocol and independently + /// joined old CPU/EOI/callbacks and captured service/thread/work. /// Keep the real function/reset/root, DMA and interrupt-controller owners; /// no concurrent table/config/reset access. Process/deferred context only. pub unsafe fn unmask_indices(&mut self, indices: &[u16]) -> Result<(), Error> { @@ -492,9 +514,11 @@ impl MsixConfig { } /// Return owners only after independent real source/IRQ/work drain. /// # Safety - /// Device is stopped across ALL table entries; old pending/posted MSI-X - /// writes, callbacks and all deferred/reset/timer users have drained and cannot restart. DMA lease, - /// fence, coherency and IOMMU retirement remain independently owned. Mapped + /// Device engines are stopped across ALL table entries; every old action + /// has joined CPU/EOI/callbacks and captured service/thread/work. Former reset + /// users cannot restart. Stable root/CPU/format custody remains for delayed + /// ordinary notifications, without claiming all-issued MSI-X completion. + /// Payload/DMA lease, fence, coherency and IOMMU retirement stay independent. Mapped /// BARs must be explicitly retired by their owner after this return. pub unsafe fn release(&mut self) -> Result, Error> { self.disable()?; diff --git a/crates/stela-driver-base/src/bus/pci/msix/tests.rs b/crates/stela-driver-base/src/bus/pci/msix/tests.rs index 1402ba721d..48e679d10d 100644 --- a/crates/stela-driver-base/src/bus/pci/msix/tests.rs +++ b/crates/stela-driver-base/src/bus/pci/msix/tests.rs @@ -551,8 +551,12 @@ mod original { } fn message(index: u16) -> MsiMessage { + // Keep the direct-format low word unchanged. A DWORD stride would set + // the remappable-format bit for some indices. Distinct high words and + // data still exercise every indexed entry's full message readback. + // These software wire values grant no native routing permission. MsiMessage { - address: MESSAGE.address + u64::from(index) * 4, + address: MESSAGE.address + (u64::from(index) << 32), data: MESSAGE.data ^ (u32::from(index) << 16), } } @@ -683,15 +687,53 @@ fn metadata_allocation_failure() { let before = m.lock().unwrap().memory.clone(); let config = m.lock().unwrap().config; let events = m.lock().unwrap().events.len(); + let live = owner.live.0; + let control_state = (owner.initialized, owner.open, owner.poisoned); + let indexed_message = message(2047); + assert!(indexed_message.valid_pci_format()); + assert_eq!(owner.messages.capacity(), 0); + let (emitted, delivered, callback_calls) = { + let model = m.lock().unwrap(); + assert!(model.routes[2047].is_none()); + ( + model.emitted.len(), + model.delivered_entries.len(), + model.routes[0] + .as_ref() + .unwrap() + .calls + .load(Ordering::Relaxed), + ) + }; allocation::arm(); // SAFETY: Config and Bar keep the same mutex-protected peripheral. Live route // callbacks stay held; table writes and message emission run synchronously. - let result = unsafe { owner.program_indexed(2047, message(2047)) }; + let result = unsafe { owner.program_indexed(2047, indexed_message) }; let attempts = allocation::disarm(); assert_eq!(result, Err(Error::Allocation)); assert_eq!(attempts, 1); assert!(owner.messages.is_empty() && owner.message == Some(MESSAGE) && owner.live.contains(0)); assert!(!owner.needs_reset()); + assert_eq!(owner.messages.capacity(), 0); + assert_eq!(owner.live.0, live); + assert_eq!( + (owner.initialized, owner.open, owner.poisoned), + control_state + ); + { + let model = m.lock().unwrap(); + assert!(model.routes[2047].is_none()); + assert_eq!(model.emitted.len(), emitted); + assert_eq!(model.delivered_entries.len(), delivered); + assert_eq!( + model.routes[0] + .as_ref() + .unwrap() + .calls + .load(Ordering::Relaxed), + callback_calls + ); + } assert_eq!(m.lock().unwrap().events.len(), events); assert_eq!(m.lock().unwrap().memory, before); assert_eq!(m.lock().unwrap().config, config); @@ -740,3 +782,59 @@ mod legacy; mod mapped; mod indexed; + +#[test] +fn remapped_index_format_preserves_entry_masks_and_full_readback() { + for index in [0u64, 1, 0x7fff, 0x8000, 0xffff] { + let (mut helper, model) = attach(fixture(4)); + let message = MsiMessage { + address: 0xfee0_0010 | (index & 0x7fff) << 5 | (index >> 15) << 2, + data: 0, + }; + // SAFETY: exact isolated RAM table/source fixture, no native route grant. + unsafe { helper.program_indexed(2, message) }.unwrap(); + let m = model.lock().unwrap(); + assert_eq!( + m.memory[((TABLE + 32) / 4) as usize], + message.address as u32 + ); + assert_eq!(m.memory[((TABLE + 36) / 4) as usize], 0); + assert_eq!(m.memory[((TABLE + 40) / 4) as usize], 0); + assert_ne!(m.memory[((TABLE + 44) / 4) as usize] & 1, 0); + drop(m); + // SAFETY: original synchronous peer has no pending callback or payload. + drop(unsafe { helper.release() }.unwrap()); + } +} + +#[test] +fn remapped_msix_address_readback_failure_quarantines_original_owners() { + let message = MsiMessage { + address: 0xfeef_fff4, + data: 0, + }; + let (mut successful, trace) = attach(fixture(4)); + // SAFETY: exact isolated RAM source/table owner. + unsafe { successful.program_indexed(2, message) }.unwrap(); + let readback = trace + .lock() + .unwrap() + .events + .iter() + .rposition(|e| *e == Event::BarRead(TABLE + 32)) + .unwrap() + + 1; + // SAFETY: synchronous model has no asynchronous users. + drop(unsafe { successful.release() }.unwrap()); + let (mut helper, peer) = attach(fixture(4)); + peer.lock().unwrap().fail = Some(readback); + // SAFETY: independent peer refuses the real post-store address readback. + assert!(unsafe { helper.program_indexed(2, message) }.is_err()); + assert_eq!( + peer.lock().unwrap().events[readback - 1], + Event::BarRead(TABLE + 32) + ); + // SAFETY: isolated peer has no asynchronous users; uncertain readback must + // retain the original owners rather than permit a successful release. + assert!(unsafe { helper.release() }.is_err()); +} diff --git a/crates/stela-driver-base/src/bus/pci/owned.rs b/crates/stela-driver-base/src/bus/pci/owned.rs index 9c7f3ada81..89678910c5 100644 --- a/crates/stela-driver-base/src/bus/pci/owned.rs +++ b/crates/stela-driver-base/src/bus/pci/owned.rs @@ -47,6 +47,26 @@ impl ConfigRetention { self.view.check_current() } + /// Retain another view of this same original mapping in its checked + /// context. This supplies no second writer or new reset/root permission. + pub fn retain_epoch(&self) -> Result { + self.check_live()?; + Ok(Self { + view: self.view.clone(), + }) + } + + /// Compare this actual original configuration allocation/epoch, never + /// equal BDFs, resource numbers or merely a shared mapping platform. + pub fn same_allocation(&self, other: &Self) -> Result { + self.view.shares_mapping(&other.view) + } + + /// Compare actual installed mapping-platform provenance only. This + /// establishes no endpoint/BAR, I/O, writer, stop or completion permission. + pub fn shares_authority(&self, mapping: &Mapping) -> Result { + mapping.shares_authority(&self.view) + } /// Compare kept permissions, never caller-supplied numeric IDs. pub fn matches_mapping(&self, mapping: &Mapping) -> Result { mapping.shares_mapping(&self.view) diff --git a/crates/stela-driver-base/src/bus/pci/requester.rs b/crates/stela-driver-base/src/bus/pci/requester.rs index 28b07ca061..6174fee427 100644 --- a/crates/stela-driver-base/src/bus/pci/requester.rs +++ b/crates/stela-driver-base/src/bus/pci/requester.rs @@ -15,6 +15,8 @@ use super::{ }; use crate::bus::mmio::owned::{Error as MappingError, Mapping}; +mod irq_identity; +pub use irq_identity::RequesterId; pub mod preparation; pub mod roles; diff --git a/crates/stela-driver-base/src/bus/pci/requester/irq_identity.rs b/crates/stela-driver-base/src/bus/pci/requester/irq_identity.rs new file mode 100644 index 0000000000..cfb1a43397 --- /dev/null +++ b/crates/stela-driver-base/src/bus/pci/requester/irq_identity.rs @@ -0,0 +1,57 @@ +//! Stable opaque identity for one original attachment/configuration epoch. +use crate::bus::irq::IrqError; +use alloc::sync::Arc; +use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +/// Metadata only; no config writer, native context or numeric source grant. +#[derive(Clone)] +pub struct RequesterId(Arc); +struct Identity { + outstanding: AtomicUsize, + detached: AtomicBool, +} +impl RequesterId { + pub(crate) fn new() -> Self { + Self(Arc::new(Identity { + outstanding: AtomicUsize::new(0), + detached: AtomicBool::new(false), + })) + } + pub fn same_requester(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub(crate) fn issue(&self) -> Result<(), IrqError> { + if self.0.detached.load(Ordering::Acquire) { + return Err(IrqError::Unregistered); + } + self.0 + .outstanding + .try_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_add(1)) + .map_err(|_| IrqError::Exhausted)?; + Ok(()) + } + /// Invoked once by that affine grant's cancellation or exact action join. + /// Unreturned/abandoned grants deliberately keep the count outstanding. + pub(crate) fn complete_action(&self) -> Result<(), IrqError> { + self.0 + .outstanding + .try_update(Ordering::AcqRel, Ordering::Acquire, |n| n.checked_sub(1)) + .map_err(|_| IrqError::Unregistered)?; + Ok(()) + } + pub(crate) fn check_detach(&self) -> Result<(), IrqError> { + if self.0.detached.load(Ordering::Acquire) + || self.0.outstanding.load(Ordering::Acquire) != 0 + { + return Err(IrqError::Drain); + } + Ok(()) + } + pub(crate) fn detached(&self) -> Result<(), IrqError> { + self.check_detach()?; + self.0 + .detached + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .map_err(|_| IrqError::Unregistered)?; + Ok(()) + } +} diff --git a/crates/stela-driver-base/src/bus/pci/requester/preparation.rs b/crates/stela-driver-base/src/bus/pci/requester/preparation.rs index 4d0e74ffd3..28471a0bd1 100644 --- a/crates/stela-driver-base/src/bus/pci/requester/preparation.rs +++ b/crates/stela-driver-base/src/bus/pci/requester/preparation.rs @@ -3,6 +3,23 @@ use super::*; use crate::bus::dma::mapping::{DmaDomain, DmaError}; use alloc::{boxed::Box, sync::Arc}; +mod attachment; +pub use attachment::{ + Attachment, CancelFailure, DetachedRequester, PinReleaseFailure, RetainActionFailure, +}; + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DetachError { + /// Audited refusal before hardware publication or binding release. + Unexposed(DmaError), + /// Hardware/ownership transition may have begun; retain and do not retry. + Uncertain(DmaError), +} +impl From for DetachError { + fn from(error: DmaError) -> Self { + Self::Uncertain(error) + } +} #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Error { @@ -21,16 +38,33 @@ pub enum Error { /// sync operations and cannot reach a replacement generation. Failure/unwind /// and Drop without acknowledged detach retain uncertain roots, bindings, /// reservations and pins. Every method observes the owner's execution context. -pub unsafe trait Attachment { +pub unsafe trait AttachmentBackend { fn domain(&self) -> Arc; + /// Construct an unused grant from this exact original root/configuration. + /// The borrowed identity comes from this same concrete Attachment; use it + /// with the backend's actual retained original config/root, never a lookup. + /// No route or endpoint is programmed here. None explicitly reports missing + /// notification admission; it is not successful empty completion. + fn irq_owner( + &mut self, + _requester: &crate::bus::pci::requester::RequesterId, + _config: Option<&crate::bus::pci::owned::ConfigRetention>, + ) -> Result>, DmaError> { + Ok(None) + } /// # Safety /// This exact original requester is stopped and cannot resume. Payload, - /// posted MSI/bypass/IRQ/work users are drained, and its paired - /// configuration/BAR/root owners stay kept through detach and subsequent + /// bypass and former callback/work users are drained. Every old action has + /// joined while its original stable CPU/root/format notification ownership + /// remains retained; late ordinary fixed/edge packets may notify only a + /// current valid status-checking handler. This is not all-issued completion + /// or permission to change that CPU/root/format. Strong root ledgers and + /// their tombstones are never reclaimed by endpoint detach. + /// Paired configuration/BAR/root owners stay kept through detach and subsequent /// retirement. Remaining mapped leases cause refusal before hardware /// retirement; they must be quiescently unmapped for success. No reset/reassignment /// changes that epoch. This is not a stop or drain request to the driver. - unsafe fn detach(&mut self) -> Result<(), DmaError>; + unsafe fn detach(&mut self) -> Result<(), DetachError>; } /// The original root path, before the requester gets its private domain. @@ -52,7 +86,10 @@ pub unsafe trait Root { /// The original paired requester is currently quiescent, this root's /// drain completed, and its configuration/reset/routing epoch cannot change /// before attachment finishes. The original owners remain kept throughout. - unsafe fn bind(&self, binding: RequesterBinding) -> Result, DmaError>; + unsafe fn bind( + &self, + binding: RequesterBinding, + ) -> Result, DmaError>; } struct Resources { @@ -110,7 +147,7 @@ pub struct Failure { /// A stopped original requester with its newly attached domain. pub struct BoundRequester { pub requester: StoppedRequester, - pub attachment: Box, + pub attachment: Attachment, } impl PreparingRequester { @@ -201,16 +238,31 @@ impl QuiescenceReceipt { .config() .retain_epoch() .map_err(|error| Error::Claim(ClaimError::Mapping(error)))?; - // SAFETY: the consumed driver receipt excludes new producers; - // the original configuration seal still matches, its root drain - // completed, and all owners stay in this attempt until success. - unsafe { - resources.root.bind(RequesterBinding { - address: resources.address, - retention: retained, - }) - } - .map_err(Error::Dma) + let irq_retained = function + .config() + .retain_epoch() + .map_err(|error| Error::Claim(ClaimError::Mapping(error)))?; + // Keep the returned affine backend before any later context check. + let mut backend = core::mem::ManuallyDrop::new( + // SAFETY: the consumed driver receipt excludes new producers; + // the original configuration seal still matches, its root drain + // completed, and all owners stay in this attempt until success. + unsafe { + resources.root.bind(RequesterBinding { + address: resources.address, + retention: retained, + }) + } + .map_err(Error::Dma)?, + ); + irq_retained + .check_live() + .map_err(|error| Error::Claim(ClaimError::Mapping(error)))?; + // SAFETY: the same consumed binding/root produced this backend; + // the original configuration's context/epoch was checked again. + Ok(unsafe { + Attachment::new(core::mem::ManuallyDrop::take(&mut backend), irq_retained) + }) })(); match result { Ok(attachment) => { diff --git a/crates/stela-driver-base/src/bus/pci/requester/preparation/attachment.rs b/crates/stela-driver-base/src/bus/pci/requester/preparation/attachment.rs new file mode 100644 index 0000000000..f0015cb103 --- /dev/null +++ b/crates/stela-driver-base/src/bus/pci/requester/preparation/attachment.rs @@ -0,0 +1,299 @@ +//! Unique attachment control and receipts from its actual native backend. +use super::{AttachmentBackend, ConfigRetention, DetachError, DmaDomain, DmaError}; +use crate::bus::{ + irq::{RetiredRoute, RouteId, posted_msi::MsiRoute}, + pci::requester::RequesterId, +}; +use alloc::{boxed::Box, sync::Arc, vec::Vec}; +use core::{marker::PhantomData, mem::ManuallyDrop}; +#[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] +extern crate std; +enum Retention { + Native(ConfigRetention), + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + SynchronousModel(std::thread::ThreadId), +} +impl Retention { + fn check(&self) -> Result<(), DmaError> { + match self { + Self::Native(retained) => retained.check_live().map_err(|_| DmaError::MappingFailed), + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + Self::SynchronousModel(thread) if *thread == std::thread::current().id() => Ok(()), + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + Self::SynchronousModel(_) => Err(DmaError::MappingFailed), + } + } +} + +/// Acknowledged detach of this exact requester and registered route, if any. +/// It carries no configuration writer, mapping pin or replacement permission. +pub struct DetachedRequester { + requester: RequesterId, + routes: Vec, + local: PhantomData<*mut ()>, +} +impl DetachedRequester { + pub fn requester(&self) -> &RequesterId { + &self.requester + } + pub(crate) fn matches_route(&self, route: &RouteId) -> bool { + self.routes.iter().any(|own| own.same(route)) + } +} +pub struct RetainActionFailure { + pub error: crate::bus::irq::IrqError, + pub retired: RetiredRoute, +} +pub struct PinReleaseFailure { + pub error: crate::bus::irq::IrqError, + pub detached: DetachedRequester, +} +pub struct CancelFailure { + pub error: DmaError, + pub grant: MsiRoute, +} +/// The original native backend, with one generic IRQ-publication/detach owner. +/// Original Root::bind creates its backend; only this wrapper mints receipts. +pub struct Attachment { + backend: ManuallyDrop>>, + retention: ManuallyDrop>, + domain: ManuallyDrop>, + requester: RequesterId, + retired: ManuallyDrop>, + detached: bool, + poisoned: bool, + local: PhantomData<*mut ()>, +} +impl Attachment { + /// # Safety + /// backend is the unique attached control produced for this exact original + /// configuration/root/reset epoch. Its real methods and Drop obey the + /// AttachmentBackend contract. retained was checked in actual original + /// process context after binding; it introduces no second config writer. + pub unsafe fn new(backend: Box, retained: ConfigRetention) -> Self { + // Keep affine inputs before the external domain callback can unwind. + let backend = ManuallyDrop::new(Some(backend)); + let retention = ManuallyDrop::new(Some(Retention::Native(retained))); + let domain = backend.as_ref().expect("new attachment backend").domain(); + Self { + backend, + retention, + domain: ManuallyDrop::new(domain), + requester: RequesterId::new(), + retired: ManuallyDrop::new(Vec::new()), + detached: false, + poisoned: false, + local: PhantomData, + } + } + /// Construct only the original isolated RAM attachment peer. + /// + /// # Safety + /// backend owns actual fixture translation/lease/stop state, performs its + /// real modeled detach and contains no native root/configuration resource. + /// This current-thread scope is not a native process or device grant. + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + pub unsafe fn bounded_fixture(backend: Box) -> Self { + let backend = ManuallyDrop::new(Some(backend)); + let domain = backend.as_ref().expect("model attachment backend").domain(); + Self { + backend, + retention: ManuallyDrop::new(Some(Retention::SynchronousModel( + std::thread::current().id(), + ))), + domain: ManuallyDrop::new(domain), + requester: RequesterId::new(), + retired: ManuallyDrop::new(Vec::new()), + detached: false, + poisoned: false, + local: PhantomData, + } + } + fn check(&self) -> Result<(), DmaError> { + if self.detached || self.poisoned { + return Err(DmaError::Unmapped); + } + self.retention.as_ref().ok_or(DmaError::Unmapped)?.check() + } + /// Compare actual original configuration allocation/epoch, never BDF. + /// This grants no access, writer or root permission to the caller. + pub fn matches_config( + &self, + config: &crate::bus::pci::owned::OwnedConfig, + ) -> Result { + self.check()?; + match self.retention.as_ref().ok_or(DmaError::Unmapped)? { + Retention::Native(retained) => config + .matches_retention(retained) + .map_err(|_| DmaError::MappingFailed), + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + Retention::SynchronousModel(_) => Ok(false), + } + } + /// Compare an actual source's retained native configuration allocation. + /// No I/O, entry or root permission is issued; model-only custody cannot + /// match a native source by metadata or equal addresses. + pub fn matches_retention(&self, source: &ConfigRetention) -> Result { + self.check()?; + match self.retention.as_ref().ok_or(DmaError::Unmapped)? { + Retention::Native(retained) => retained + .same_allocation(source) + .map_err(|_| DmaError::MappingFailed), + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + Retention::SynchronousModel(_) => Ok(false), + } + } + pub fn domain(&self) -> Arc { + Arc::clone(&self.domain) + } + pub fn requester(&self) -> &RequesterId { + &self.requester + } + pub fn irq_route(&mut self) -> Result { + self.check()?; + let config = match self.retention.as_ref().ok_or(DmaError::Unmapped)? { + Retention::Native(config) => Some(config), + #[cfg(all(any(test, feature = "test-support"), not(target_os = "uefi")))] + Retention::SynchronousModel(_) => None, + }; + let mut owner = ManuallyDrop::new( + self.backend + .as_mut() + .ok_or(DmaError::Unmapped)? + .irq_owner(&self.requester, config)?, + ); + self.check()?; + // SAFETY: no affine owner is extracted before the repeated original + // native context/epoch check; attached preserves it on every refusal. + MsiRoute::attached(self.requester.clone(), unsafe { + ManuallyDrop::take(&mut owner) + }) + .map_err(|_| DmaError::DrainUnavailable) + } + pub fn cancel_unpublished_irq(&mut self, grant: MsiRoute) -> Result<(), CancelFailure> { + if let Err(error) = self.check() { + return Err(CancelFailure { error, grant }); + } + grant + .cancel(&self.requester) + .map_err(|(_, grant)| CancelFailure { + error: DmaError::MappingFailed, + grant, + }) + } + /// Adopt the exact joined action while retaining its old root/config pin. + /// This permits another action in the same original ownership epoch; it + /// supplies no engine/payload/DMA detach or native replacement permission. + pub fn retain_irq_action( + &mut self, + mut retired: RetiredRoute, + ) -> Result<(), RetainActionFailure> { + let result = (|| { + self.check() + .map_err(|_| crate::bus::irq::IrqError::WrongCpu)?; + retired.validate_requester(&self.requester)?; + self.retired + .try_reserve(1) + .map_err(|_| crate::bus::irq::IrqError::Exhausted)?; + retired.join_action(&self.requester)?; + Ok(()) + })(); + match result { + // Capacity is reserved; no callback or allocation follows join. + Ok(()) => { + self.retired.push(retired); + Ok(()) + } + Err(error) => Err(RetainActionFailure { error, retired }), + } + } + pub fn validate_irq_actions(&self) -> Result<(), crate::bus::irq::IrqError> { + for route in self.retired.iter() { + route.validate()?; + } + Ok(()) + } + /// Release old-action pins only after actual all-actions plus + /// engine/payload/DMA-unmap/detach, keeping root terminal metadata. + pub fn release_irq_pins( + &mut self, + detached: DetachedRequester, + ) -> Result<(), PinReleaseFailure> { + let result = (|| { + if !self.detached || !self.requester.same_requester(detached.requester()) { + return Err(crate::bus::irq::IrqError::Route); + } + for route in self.retired.iter_mut() { + route.validate()?; + route + .release_endpoint(&detached) + .map_err(crate::bus::irq::IrqError::Delivery)?; + } + Ok(()) + })(); + result.map_err(|error| PinReleaseFailure { error, detached }) + } + /// # Safety + /// This original requester is stopped and cannot resume. Own payload and + /// bypass users are drained, all DMA leases quiescently unmapped, and paired + /// configuration/BAR/root owners remain held. Every issued grant must be + /// explicitly canceled or its exact independently joined action adopted. + /// Source/entry non-overlap and engine stop remain independent obligations. + pub unsafe fn detach(&mut self) -> Result { + self.check()?; + self.validate_irq_actions() + .map_err(|_| DmaError::DrainUnavailable)?; + self.requester + .check_detach() + .map_err(|_| DmaError::DrainUnavailable)?; + let routes: Vec = self + .retired + .iter() + .map(|route| route.id().clone()) + .collect(); + // A callback panic/error after this point cannot expose a retryable or + // detached success. Backend failure retains its uncertain native graph. + self.poisoned = true; + // SAFETY: caller supplies original engine/payload/unmap exclusions; + // exact route checks above supply the separate interrupt boundary. + match unsafe { self.backend.as_mut().ok_or(DmaError::Unmapped)?.detach() } { + Ok(()) => {} + Err(DetachError::Unexposed(error)) => { + // A typed before-effect refusal is retryable only after the + // actual original process/configuration epoch still checks. + self.retention.as_ref().ok_or(DmaError::Unmapped)?.check()?; + self.poisoned = false; + return Err(error); + } + Err(DetachError::Uncertain(error)) => return Err(error), + } + self.retention.as_ref().ok_or(DmaError::Unmapped)?.check()?; + self.requester + .detached() + .map_err(|_| DmaError::DrainUnavailable)?; + // Release native control only here in the checked acknowledged context. + // Later stale Domain Arc drops remain governed by DmaDomain's contract. + drop(self.backend.take()); + drop(self.retention.take()); + self.detached = true; + self.poisoned = false; + Ok(DetachedRequester { + requester: self.requester.clone(), + routes, + local: PhantomData, + }) + } +} +impl Drop for Attachment { + fn drop(&mut self) { + if self.detached && self.validate_irq_actions().is_ok() { + // SAFETY: actual detach released the unique affine backend/pin in + // its checked context. Only a Send+Sync stale domain view remains. + unsafe { + ManuallyDrop::drop(&mut self.domain); + ManuallyDrop::drop(&mut self.retired); + }; + } + // Unclosed/uncertain backend, domain and original seal stay retained. + } +} diff --git a/crates/stela-driver-base/src/bus/pci/requester/preparation/tests.rs b/crates/stela-driver-base/src/bus/pci/requester/preparation/tests.rs index 038df00a09..80567c1bfd 100644 --- a/crates/stela-driver-base/src/bus/pci/requester/preparation/tests.rs +++ b/crates/stela-driver-base/src/bus/pci/requester/preparation/tests.rs @@ -11,7 +11,7 @@ use crate::bus::{ use alloc::vec::Vec; use core::{ ops::Range, - sync::atomic::{AtomicBool, AtomicUsize, Ordering}, + sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, }; use std::sync::Mutex; @@ -28,6 +28,11 @@ struct State { panic_drain: AtomicBool, detach_error: AtomicBool, detachments: AtomicUsize, + action_delivery: AtomicBool, + action_epoch: AtomicU64, + action_entries: Mutex>, + action_records: Mutex>, + action_pins_released: AtomicUsize, } struct RootOwner(Arc); impl Drop for RootOwner { @@ -65,7 +70,10 @@ unsafe impl Root for OldRoot { Ok(()) } } - unsafe fn bind(&self, binding: RequesterBinding) -> Result, DmaError> { + unsafe fn bind( + &self, + binding: RequesterBinding, + ) -> Result, DmaError> { assert_eq!(binding.address(), ADDRESS); binding.check_live().unwrap(); self.owner @@ -100,16 +108,34 @@ impl Drop for Control { // SAFETY: this synchronous fixture has no hardware or active mappings. // Its unique control retains the original binding on failure and makes // every old domain reference stale before releasing configuration pins. -unsafe impl Attachment for Control { +unsafe impl crate::bus::pci::requester::preparation::AttachmentBackend for Control { fn domain(&self) -> Arc { self.domain.clone() } - unsafe fn detach(&mut self) -> Result<(), DmaError> { + fn irq_owner( + &mut self, + _requester: &crate::bus::pci::requester::RequesterId, + _config: Option<&crate::bus::pci::owned::ConfigRetention>, + ) -> Result>, DmaError> { + if !self.domain._owner.0.action_delivery.load(Ordering::Acquire) { + return Ok(None); + } + irq_actions::owner(self.domain.clone()).map(Some) + } + unsafe fn detach( + &mut self, + ) -> Result<(), crate::bus::pci::requester::preparation::DetachError> { if self.detached { - return Err(DmaError::Unmapped); + return Err( + crate::bus::pci::requester::preparation::DetachError::Uncertain(DmaError::Unmapped), + ); } if self.domain._owner.0.detach_error.load(Ordering::Relaxed) { - return Err(DmaError::InvalidationFailed); + return Err( + crate::bus::pci::requester::preparation::DetachError::Uncertain( + DmaError::InvalidationFailed, + ), + ); } self.domain.binding.lock().unwrap().take(); self.domain @@ -297,7 +323,7 @@ fn failed_or_abandoned_detach_keeps_the_binding_and_original_root() { state.detach_error.store(true, Ordering::Relaxed); // SAFETY: same stopped fixture; inject failure before any binding release. let detached = unsafe { bound.attachment.detach() }; - assert_eq!(detached, Err(DmaError::InvalidationFailed)); + assert!(matches!(detached, Err(DmaError::InvalidationFailed))); } let mut mapping = bound.requester.into_function().into_config().into_mapping(); drop(bound.attachment); @@ -307,3 +333,38 @@ fn failed_or_abandoned_detach_keeps_the_binding_and_original_root() { assert_eq!(state.detachments.load(Ordering::Relaxed), 0); } } + +#[test] +fn issuing_an_unused_grant_can_cancel_but_abandonment_cannot_fake_no_route() { + for abandon in [false, true] { + let (prepared, state) = preparing(false, false); + // SAFETY: exact original synchronous idle config/root peer. + let mut bound = unsafe { prepared.acknowledge_quiescence() } + .finalize() + .unwrap_or_else(|e| panic!("{:?}", e.error)); + let grant = bound.attachment.irq_route().unwrap(); + assert!(grant.is_unavailable()); + assert!(grant.belongs_to(bound.attachment.requester())); + // Merely issued ownership is not publication. Explicit checked return + // permits detach; abandoning the grant cannot fabricate the return. + if abandon { + drop(grant); + } else { + bound + .attachment + .cancel_unpublished_irq(grant) + .unwrap_or_else(|_| panic!("original unused grant")); + } + // SAFETY: exact idle fixture and no real IRQ programmer exists. + let result = unsafe { bound.attachment.detach() }; + if abandon { + assert!(matches!(result, Err(DmaError::DrainUnavailable))); + assert_eq!(state.detachments.load(Ordering::Relaxed), 0); + } else { + assert!(result.is_ok()); + assert_eq!(state.detachments.load(Ordering::Relaxed), 1); + } + } +} + +mod irq_actions; diff --git a/crates/stela-driver-base/src/bus/pci/requester/preparation/tests/irq_actions.rs b/crates/stela-driver-base/src/bus/pci/requester/preparation/tests/irq_actions.rs new file mode 100644 index 0000000000..5658a63816 --- /dev/null +++ b/crates/stela-driver-base/src/bus/pci/requester/preparation/tests/irq_actions.rs @@ -0,0 +1,371 @@ +//! Bounded entry/source peer: actual config pins and independent action joins. +//! This model neither maps DMA nor qualifies native MSI-X entry authority. +use super::*; +use crate::bus::irq::{self, Handler, Platform, Request, RouteRequest, Source}; +pub(super) struct Entry { + number: u8, + vector: Option, + masked: bool, + cause: bool, + fenced: bool, + joined: bool, +} +struct ActionDomain { + pin: ConfigRetention, + domain: Arc, + epoch: u64, + thread: std::thread::ThreadId, +} +// SAFETY: bounded actual original RAM config/source custody and epoch only. +unsafe impl irq::posted_msi::NotificationDomain for ActionDomain { + fn check(&self) -> Result<(), irq::posted_msi::Error> { + if self.thread != std::thread::current().id() + || self.epoch != self.domain._owner.0.action_epoch.load(Ordering::Acquire) + { + return Err(irq::posted_msi::Error::Context); + } + self.pin + .check_live() + .map_err(|_| irq::posted_msi::Error::Context) + } +} +struct Action { + domain: Arc, + pin: Option, + epoch: u64, + thread: std::thread::ThreadId, + vector: Option, +} +pub(super) fn owner(domain: Arc) -> Result, DmaError> { + let pin = domain + .binding + .lock() + .unwrap() + .as_ref() + .ok_or(DmaError::Unmapped)? + .retention + .retain_epoch() + .map_err(|_| DmaError::MappingFailed)?; + Ok(Box::new(Action { + epoch: domain._owner.0.action_epoch.load(Ordering::Acquire), + domain, + pin: Some(pin), + thread: std::thread::current().id(), + vector: None, + })) +} +// SAFETY: original synchronous test source/domain/config custody only. Every +// fence consults its actual masked/pending source record. No native I/O exists. +unsafe impl irq::posted_msi::RouteOwner for Action { + fn allocate( + &mut self, + target: &irq::CpuTarget<'_>, + ) -> Result { + self.validate() + .map_err(irq::posted_msi::AllocationError::Unexposed)?; + target.check_current().map_err(|_| { + irq::posted_msi::AllocationError::Unexposed(irq::posted_msi::Error::Context) + })?; + if self.vector.is_some() { + return Err(irq::posted_msi::AllocationError::Unexposed( + irq::posted_msi::Error::AlreadyBound, + )); + } + let target = target.descriptor(); + self.domain + ._owner + .0 + .action_records + .lock() + .unwrap() + .push(target.vector); + self.vector = Some(target.vector); + Ok(irq::MsiMessage { + address: 0xfee0_0000 | u64::from(target.destination) << 12, + data: u32::from(target.vector), + }) + } + fn validate(&self) -> Result<(), irq::posted_msi::Error> { + if self.thread != std::thread::current().id() + || self.epoch != self.domain._owner.0.action_epoch.load(Ordering::Acquire) + { + return Err(irq::posted_msi::Error::Context); + } + if let Some(pin) = &self.pin { + pin.check_live() + .map_err(|_| irq::posted_msi::Error::Context)?; + } + Ok(()) + } + fn notification_domain( + &self, + ) -> Result, irq::posted_msi::Error> { + self.validate()?; + let pin = self + .pin + .as_ref() + .ok_or(irq::posted_msi::Error::Unbound)? + .retain_epoch() + .map_err(|_| irq::posted_msi::Error::Context)?; + Ok(Arc::new(ActionDomain { + pin, + domain: self.domain.clone(), + epoch: self.epoch, + thread: self.thread, + })) + } + unsafe fn strong_fence(&mut self) -> Result<(), irq::posted_msi::Error> { + self.validate()?; + let mut entries = self.domain._owner.0.action_entries.lock().unwrap(); + let entry = entries + .iter_mut() + .find(|entry| entry.vector == self.vector && self.vector.is_some()) + .ok_or(irq::posted_msi::Error::Unbound)?; + if !entry.masked || entry.cause { + return Err(irq::posted_msi::Error::RootFailed); + } + entry.fenced = true; + Ok(()) + } + unsafe fn release_endpoint( + &mut self, + proof: &irq::posted_msi::EndpointRetirement<'_>, + ) -> Result<(), irq::posted_msi::Error> { + self.validate()?; + assert!(proof.requester().is_some()); + assert!(self.domain.binding.lock().unwrap().is_none()); + self.pin.take(); + self.domain + ._owner + .0 + .action_pins_released + .fetch_add(1, Ordering::Relaxed); + Ok(()) + } +} +struct Cpu { + thread: std::thread::ThreadId, +} +// SAFETY: bounded synchronous source peer, no native interrupt producer. +unsafe impl Platform for Cpu { + fn check_cpu(&self) -> Result<(), irq::IrqError> { + if self.thread == std::thread::current().id() { + Ok(()) + } else { + Err(irq::IrqError::WrongCpu) + } + } + fn check_process(&self) -> Result<(), irq::IrqError> { + self.check_cpu() + } + fn save_and_disable(&self) -> u64 { + 0 + } + unsafe fn restore(&self, saved: u64) { + assert_eq!(saved, 0); + } + fn target(&self, vector: u8) -> Result { + self.check_cpu()?; + Ok(irq::Target { + destination: 0, + vector, + }) + } + fn pending(&self, _: u8) -> Result { + self.check_cpu()?; + Ok(false) + } + fn eoi(&self, _vector: u8) -> Result { + Ok(crate::bus::irq::Trigger::Edge) + } + fn ticks(&self) -> u64 { + 0 + } + fn timeout_ticks(&self) -> u64 { + 1 + } + unsafe fn interrupt_window(&self) { + panic!("no asynchronous producer in this bounded source fixture") + } +} +struct Callback; +impl Handler for Callback { + fn handle(&self) -> irq::Disposition { + panic!("no native dispatch in this entry ownership fixture") + } +} +struct EntrySource { + state: Arc, + requester: RequesterId, + number: u8, +} +impl EntrySource { + fn new(state: Arc, requester: RequesterId, number: u8) -> Self { + { + let mut entries = state.action_entries.lock().unwrap(); + assert!(!entries.iter().any(|entry| entry.number == number)); + entries.push(Entry { + number, + vector: None, + masked: true, + cause: false, + fenced: false, + joined: false, + }); + } + Self { + state, + requester, + number, + } + } + fn entry( + &self, + body: impl FnOnce(&mut Entry) -> Result<(), irq::IrqError>, + ) -> Result<(), irq::IrqError> { + let mut entries = self.state.action_entries.lock().unwrap(); + body( + entries + .iter_mut() + .find(|entry| entry.number == self.number) + .unwrap(), + ) + } +} +// SAFETY: owns the actual unique model entry; pending causes are checked and +// source reuse is possible only after original Source return/join and Drop. +unsafe impl Source for EntrySource { + fn route_kind(&self) -> irq::RouteKind { + irq::RouteKind::Msi + } + fn requester(&self) -> Option<&RequesterId> { + Some(&self.requester) + } + fn mask(&mut self) -> Result<(), irq::IrqError> { + self.entry(|entry| { + entry.masked = true; + Ok(()) + }) + } + fn quiesce(&mut self) -> Result<(), irq::IrqError> { + self.entry(|entry| { + if entry.masked && !entry.cause { + Ok(()) + } else { + Err(irq::IrqError::Quiesce) + } + }) + } + unsafe fn program(&mut self, route: &irq::AllocatedRoute<'_>) -> Result<(), irq::IrqError> { + assert!(route.matches_requester(&self.requester)); + let irq::Route::Msi(message) = route.programming() else { + return Err(irq::IrqError::Route); + }; + self.entry(|entry| { + assert!(entry.masked); + entry.vector = Some(message.data.try_into().unwrap()); + Ok(()) + }) + } + unsafe fn unmask(&mut self) -> Result<(), irq::IrqError> { + self.entry(|entry| { + assert!(entry.vector.is_some()); + entry.masked = false; + Ok(()) + }) + } + unsafe fn synchronize(&mut self) -> Result<(), irq::IrqError> { + self.entry(|entry| { + assert!(entry.masked && !entry.cause); + entry.joined = true; + Ok(()) + }) + } +} +impl Drop for EntrySource { + fn drop(&mut self) { + let mut entries = self.state.action_entries.lock().unwrap(); + let i = entries + .iter() + .position(|entry| entry.number == self.number) + .unwrap(); + assert!(entries[i].joined || entries[i].vector.is_none()); + entries.remove(i); + } +} +fn adopt(attachment: &mut Attachment, retired: irq::RetiredSource) { + // SAFETY: bounded source and original root/CPU/action work join completed. + let (source, callback, route) = + unsafe { retired.into_parts() }.unwrap_or_else(|failure| panic!("{:?}", failure.error)); + drop(source); + drop(callback); + attachment + .retain_irq_action(route) + .unwrap_or_else(|failure| panic!("{:?}", failure.error)); +} +#[test] +fn multiple_entries_and_same_epoch_rerequest_retain_old_pins_until_endpoint_detach() { + let (prepared, state) = preparing(false, false); + state.action_delivery.store(true, Ordering::Release); + // SAFETY: original cold source fixture has no prior producer or DMA. + let mut bound = unsafe { prepared.acknowledge_quiescence() } + .finalize() + .unwrap_or_else(|failure| panic!("{:?}", failure.error)); + let key = bound.attachment.requester().clone(); + let registry = Box::leak(Box::new(irq::Registry::new(Cpu { + thread: std::thread::current().id(), + }))); + let mut first = registry + .request_owned(Request { + source: EntrySource::new(state.clone(), key.clone(), 0), + handler: Arc::new(Callback), + routing: RouteRequest::Msi(bound.attachment.irq_route().unwrap()), + }) + .unwrap(); + let mut other = registry + .request_owned(Request { + source: EntrySource::new(state.clone(), key.clone(), 1), + handler: Arc::new(Callback), + routing: RouteRequest::Msi(bound.attachment.irq_route().unwrap()), + }) + .unwrap(); + let vector = first.vector(); + assert_ne!(vector, other.vector()); + adopt(&mut bound.attachment, first.retire().unwrap()); + assert_eq!(state.detachments.load(Ordering::Relaxed), 0); + assert_eq!(state.action_pins_released.load(Ordering::Relaxed), 0); + let mut replacement = registry + .request_owned(Request { + source: EntrySource::new(state.clone(), key.clone(), 0), + handler: Arc::new(Callback), + routing: RouteRequest::Msi(bound.attachment.irq_route().unwrap()), + }) + .unwrap(); + assert_eq!(replacement.vector(), vector); + assert!(bound.attachment.requester().same_requester(&key)); + assert!(matches!( + // SAFETY: deliberately invalid caller only in this synchronous negative + // model; outstanding actions must refuse before any backend effect. + unsafe { bound.attachment.detach() }, + Err(DmaError::DrainUnavailable) + )); + adopt(&mut bound.attachment, other.retire().unwrap()); + adopt(&mut bound.attachment, replacement.retire().unwrap()); + assert_eq!(state.action_records.lock().unwrap().len(), 3); + let mut mapping = bound.requester.into_function().into_config().into_mapping(); + // SAFETY: inactive fixture checks that real old-action config pins remain. + assert_eq!(unsafe { mapping.retire() }, Err(MappingError::Busy)); + // SAFETY: all action joins adopted, original engines absent and no DMA map + // was ever admitted in this bounded entry ownership fixture. + let detached = unsafe { bound.attachment.detach() }.unwrap(); + assert_eq!(state.detachments.load(Ordering::Relaxed), 1); + // SAFETY: acknowledged endpoint detach alone cannot release old route pins. + assert_eq!(unsafe { mapping.retire() }, Err(MappingError::Busy)); + bound + .attachment + .release_irq_pins(detached) + .unwrap_or_else(|failure| panic!("{:?}", failure.error)); + assert_eq!(state.action_pins_released.load(Ordering::Relaxed), 3); + // SAFETY: actual endpoint detach and every original action pin released. + unsafe { mapping.retire() }.unwrap(); +} diff --git a/crates/stela-driver-base/src/bus/vmd/source.rs b/crates/stela-driver-base/src/bus/vmd/source.rs index ee90c915fb..09660c9628 100644 --- a/crates/stela-driver-base/src/bus/vmd/source.rs +++ b/crates/stela-driver-base/src/bus/vmd/source.rs @@ -3,7 +3,7 @@ //! Each child contributes its real device source and IRQ handler. No completion //! is inferred from a VMD mask, a BDF, or a caller-set software stopped flag. use super::*; -use crate::bus::irq::{Handler, IrqError, MsiMessage, Route, RouteRequest, Source}; +use crate::bus::irq::{Handler, IrqError, MsiMessage, Route, Source}; use crate::bus::pci::regs; use alloc::{boxed::Box, rc::Rc, sync::Arc}; use core::cell::RefCell; @@ -63,7 +63,7 @@ impl ParentSource { if children.is_empty() || children .iter() - .any(|child| child.source.route() != RouteRequest::Msi) + .any(|child| child.source.route_kind() != crate::bus::irq::RouteKind::Msi) { return Err((Error::Address, host, children)); } @@ -119,11 +119,17 @@ unsafe impl Source for ParentSource { } Ok(()) } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> crate::bus::irq::RouteKind { + crate::bus::irq::RouteKind::Msi } - unsafe fn program(&mut self, route: Route) -> Result<(), IrqError> { - let Route::Msi(message) = route else { + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + None + } + unsafe fn program( + &mut self, + route: &crate::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), IrqError> { + let Route::Msi(message) = route.programming() else { return Err(IrqError::Unsupported); }; let host = self.host()?; @@ -140,7 +146,9 @@ unsafe impl Source for ParentSource { for child in self.children.as_mut().ok_or(IrqError::Unregistered)? { // SAFETY: this is the owned VMD route to the same parent // registry/callback, not an invented APIC target for the child. - unsafe { child.program(Route::Msi(message)) }?; + let child_route = unsafe { route.vmd_child(message) }; + // SAFETY: same exact complete child/VMD ingress owner, not a root grant. + unsafe { child.program(&child_route) }?; } Ok(()) } diff --git a/crates/stela-driver-base/src/bus/vmd/tests.rs b/crates/stela-driver-base/src/bus/vmd/tests.rs index e890e4b5cc..658fe1d6be 100644 --- a/crates/stela-driver-base/src/bus/vmd/tests.rs +++ b/crates/stela-driver-base/src/bus/vmd/tests.rs @@ -467,15 +467,18 @@ unsafe impl crate::bus::irq::Source for ChildEffects { Ok(()) } } - fn route(&self) -> crate::bus::irq::RouteRequest { - crate::bus::irq::RouteRequest::Msi + fn route_kind(&self) -> crate::bus::irq::RouteKind { + crate::bus::irq::RouteKind::Msi + } + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + None } unsafe fn program( &mut self, - route: crate::bus::irq::Route, + route: &crate::bus::irq::AllocatedRoute<'_>, ) -> Result<(), crate::bus::irq::IrqError> { assert_eq!( - route, + route.programming(), crate::bus::irq::Route::Msi(crate::bus::irq::MsiMessage { address: 0xfee0_1000, data: 0 @@ -537,10 +540,12 @@ fn child_providers_gate_parent_owner_return_and_uncertain_stop_retention() { source.mask().unwrap(); // SAFETY: simulate the owning IRQ registry's published model route. unsafe { - source.program(Route::Msi(MsiMessage { - address: 0xfee0_2000, - data: 0x50, - })) + source.program(&crate::bus::irq::AllocatedRoute::model_programming( + Route::Msi(MsiMessage { + address: 0xfee0_2000, + data: 0x50, + }), + )) } .unwrap(); // SAFETY: modeled registry keeps both source and fanout. diff --git a/crates/stela-driver-net/src/aqtion/native/cold.rs b/crates/stela-driver-net/src/aqtion/native/cold.rs index 10fb0772fa..3c02fcb809 100644 --- a/crates/stela-driver-net/src/aqtion/native/cold.rs +++ b/crates/stela-driver-net/src/aqtion/native/cold.rs @@ -28,7 +28,7 @@ struct FailedBinding { } pub(super) struct Bound { pub requester: StoppedRequester, - pub attachment: Box, + pub attachment: Attachment, pub hardware: Hardware, pub profile: Profile, pub firmware: firmware::Firmware, diff --git a/crates/stela-driver-net/src/aqtion/native/lifetime.rs b/crates/stela-driver-net/src/aqtion/native/lifetime.rs index 15d45f9152..c67a2f2c2b 100644 --- a/crates/stela-driver-net/src/aqtion/native/lifetime.rs +++ b/crates/stela-driver-net/src/aqtion/native/lifetime.rs @@ -15,7 +15,7 @@ use core::{mem::ManuallyDrop, ops::Deref}; struct Resources { core: Aqtion, - attachment: Box, + attachment: Attachment, retention: Option, configuration: Option, } diff --git a/crates/stela-driver-net/src/aqtion/tests/ownership.rs b/crates/stela-driver-net/src/aqtion/tests/ownership.rs index 91330961ed..a85e71bcfe 100644 --- a/crates/stela-driver-net/src/aqtion/tests/ownership.rs +++ b/crates/stela-driver-net/src/aqtion/tests/ownership.rs @@ -5,7 +5,7 @@ use crate::{ aqtion::native as adapter, bus::pci::requester::{ FunctionRole, RequesterBinding, - preparation::{self, Attachment, Root}, + preparation::{self, Root}, }, }; mod domain; diff --git a/crates/stela-driver-net/src/aqtion/tests/ownership/model.rs b/crates/stela-driver-net/src/aqtion/tests/ownership/model.rs index 4d691eb104..a476ff94a1 100644 --- a/crates/stela-driver-net/src/aqtion/tests/ownership/model.rs +++ b/crates/stela-driver-net/src/aqtion/tests/ownership/model.rs @@ -69,7 +69,10 @@ unsafe impl Root for OldRoot { unsafe fn bind( &self, binding: RequesterBinding, - ) -> core::result::Result, DmaError> { + ) -> core::result::Result< + Box, + DmaError, + > { self.state.stopped(); assert!(!self.state.old_pending.load(Ordering::Relaxed)); assert_eq!(self.state.old_backing.load(Ordering::Relaxed), 0x55aa); @@ -100,18 +103,24 @@ impl Drop for Control { } // SAFETY: one original model binding; detach checks every mapping and actual // model DMA/engine state, then releases that exact config binding once. -unsafe impl Attachment for Control { +unsafe impl crate::bus::pci::requester::preparation::AttachmentBackend for Control { fn domain(&self) -> Arc { Arc::new(super::domain::NativeDomain(self.0.clone())) } - unsafe fn detach(&mut self) -> core::result::Result<(), DmaError> { + unsafe fn detach( + &mut self, + ) -> core::result::Result<(), crate::bus::pci::requester::preparation::DetachError> { self.0.current()?; self.0.stopped(); assert!(self.0.base.maps.lock().unwrap().is_empty()); assert_eq!(self.0.base.pending_dma.load(Ordering::Relaxed), 0); assert!(self.0.base.posted.lock().unwrap().is_empty()); if self.0.record("detach") { - return Err(DmaError::InvalidationFailed); + return Err( + crate::bus::pci::requester::preparation::DetachError::Uncertain( + DmaError::InvalidationFailed, + ), + ); } self.0.binding.lock().unwrap().take().unwrap(); self.0.detached.store(true, Ordering::Relaxed); diff --git a/crates/stela-driver-net/src/tg3/io/cold.rs b/crates/stela-driver-net/src/tg3/io/cold.rs index 071abbcb1b..650c3b3f19 100644 --- a/crates/stela-driver-net/src/tg3/io/cold.rs +++ b/crates/stela-driver-net/src/tg3/io/cold.rs @@ -5,7 +5,6 @@ use crate::bus::pci::{ owned::OwnedConfig, requester::preparation::{self, Attachment, BoundRequester, PreparingRequester}, }; -use alloc::boxed::Box; use core::mem::ManuallyDrop; struct Resources { @@ -29,7 +28,7 @@ impl Drop for Cold { pub struct Bound { pub registers: Mmio, - pub attachment: Box, + pub attachment: Attachment, } /// Failed finalization keeps the original root and BAR graph indefinitely. diff --git a/crates/stela-driver-net/src/tg3/io/tests/cold.rs b/crates/stela-driver-net/src/tg3/io/tests/cold.rs index 3d2090affa..c30d371134 100644 --- a/crates/stela-driver-net/src/tg3/io/tests/cold.rs +++ b/crates/stela-driver-net/src/tg3/io/tests/cold.rs @@ -10,7 +10,7 @@ use crate::bus::{ owned::test_support::fixture, requester::{ FunctionRole, RequesterBinding, - preparation::{self, Attachment, Root}, + preparation::{self, Root}, }, }, }; @@ -45,7 +45,10 @@ unsafe impl Root for OldRoot { Ok(()) } } - unsafe fn bind(&self, binding: RequesterBinding) -> Result, DmaError> { + unsafe fn bind( + &self, + binding: RequesterBinding, + ) -> Result, DmaError> { binding.check_live().unwrap(); self.0.events.lock().unwrap().push("private bind"); if self.0.fail_bind.load(Ordering::Relaxed) { @@ -67,11 +70,13 @@ impl Drop for Control { } // SAFETY: no mapping can be created by this model; detach makes the shared // binding absent before releasing its original configuration retention. -unsafe impl Attachment for Control { +unsafe impl crate::bus::pci::requester::preparation::AttachmentBackend for Control { fn domain(&self) -> Arc { self.0.clone() } - unsafe fn detach(&mut self) -> Result<(), DmaError> { + unsafe fn detach( + &mut self, + ) -> Result<(), crate::bus::pci::requester::preparation::DetachError> { self.0 .binding .lock() diff --git a/crates/stela-driver-net/src/tg3/packet.rs b/crates/stela-driver-net/src/tg3/packet.rs index f27a9637b6..629378078e 100644 --- a/crates/stela-driver-net/src/tg3/packet.rs +++ b/crates/stela-driver-net/src/tg3/packet.rs @@ -10,7 +10,7 @@ use crate::{ }, check_frame, }; -use alloc::{boxed::Box, format, sync::Arc, vec::Vec}; +use alloc::{format, sync::Arc, vec::Vec}; mod memory; use super::geometry::Geometry; #[cfg(test)] @@ -34,7 +34,7 @@ pub struct Packet { hardware: Hardware, memory: Option, domain: Arc, - attachment: Option>, + attachment: Option, mac: Mac, board: Option, carrier_up: bool, @@ -148,7 +148,7 @@ impl Packet { pub unsafe fn attach_bound( hardware: Hardware, pages: &dyn PageSource, - attachment: Box, + attachment: Attachment, ) -> Result { // SAFETY: the caller supplies the same original stopped hardware, // IRQ/work exclusion and unique attachment. Keep it through all errors. diff --git a/crates/stela-driver-net/src/tg3/packet/tests/attachment.rs b/crates/stela-driver-net/src/tg3/packet/tests/attachment.rs index 44efe834f7..a401fa355f 100644 --- a/crates/stela-driver-net/src/tg3/packet/tests/attachment.rs +++ b/crates/stela-driver-net/src/tg3/packet/tests/attachment.rs @@ -23,18 +23,24 @@ impl Drop for Control { } // SAFETY: this independent synchronous RAM peer verifies its engine/BME stop, // posted-write drain and lack of live mappings. It reaches no native device. -unsafe impl Attachment for Control { +unsafe impl crate::bus::pci::requester::preparation::AttachmentBackend for Control { fn domain(&self) -> Arc { self.domain.clone() } - unsafe fn detach(&mut self) -> Result<(), DmaError> { + unsafe fn detach( + &mut self, + ) -> Result<(), crate::bus::pci::requester::preparation::DetachError> { self.domain.require_stopped(); assert!(self.domain.drained.load(Ordering::Relaxed)); assert!(self.domain.maps.lock().unwrap().is_empty()); assert!(self.domain.posted.lock().unwrap().is_empty()); self.state.calls.fetch_add(1, Ordering::Relaxed); if self.state.refuse.load(Ordering::Relaxed) { - return Err(DmaError::InvalidationFailed); + return Err( + crate::bus::pci::requester::preparation::DetachError::Unexposed( + DmaError::InvalidationFailed, + ), + ); } self.detached = true; Ok(()) @@ -50,11 +56,15 @@ struct Fixture { fn attached() -> Fixture { let (hardware, pages, domain, peer) = parts(); let state = Arc::new(ControlState::default()); - let attachment = Box::new(Control { - domain: domain.clone(), - state: state.clone(), - detached: false, - }); + // SAFETY: original synchronous RAM peer owns actual model leases and + // stop/drain checks; no native configuration/root is manufactured. + let attachment = unsafe { + Attachment::bounded_fixture(Box::new(Control { + domain: domain.clone(), + state: state.clone(), + detached: false, + })) + }; // SAFETY: all original configuration, device/RAM, remapper and timer // owners belong to this isolated fixture, with no IRQ/work users. let packet = unsafe { Packet::attach_bound(hardware, &pages, attachment) } diff --git a/crates/stela-drivers/Cargo.toml b/crates/stela-drivers/Cargo.toml index c8aa3ff6d2..8c2a5569c0 100644 --- a/crates/stela-drivers/Cargo.toml +++ b/crates/stela-drivers/Cargo.toml @@ -14,6 +14,7 @@ workspace = true native-acpi = ["stela-driver-base/native-acpi", "stela-driver-net/native-acpi"] linux-kernel = ["dep:stela-linux", "stela-linux/kernel"] ram-disk = ["stela-driver-base/ram-disk"] +irq-diagnostics = ["stela-driver-base/irq-diagnostics"] nvidia-port = ["stela-driver-gpu/nvidia-port"] intel-port = ["stela-driver-gpu/intel-port"] amd-port = ["stela-driver-gpu/amd-port"] diff --git a/crates/stela-drivers/src/bluetooth/bcm4377/native.rs b/crates/stela-drivers/src/bluetooth/bcm4377/native.rs index afaf3af723..c2ef91cdb5 100644 --- a/crates/stela-drivers/src/bluetooth/bcm4377/native.rs +++ b/crates/stela-drivers/src/bluetooth/bcm4377/native.rs @@ -6,7 +6,7 @@ //! epoch survive terminal source stop, posted-write completion and IRQ drain. pub(crate) mod cold; mod config; -use crate::bus::irq::posted_msi::MsiCompletion; +use crate::bus::irq::posted_msi::MsiRoute; mod registers; use super::{Board, Chip, PciIdentity, Platform, Result as DriverResult, Space, Transport, memory}; use crate::bus::pci::regs; @@ -17,9 +17,7 @@ use crate::{ mapping::{DmaDomain, DmaError}, memory::{CacheAttribute, PageSource}, }, - irq::{ - self, Disposition, Handler, IrqController, IrqRegistration, Route, RouteRequest, Source, - }, + irq::{self, Disposition, Handler, IrqController, IrqRegistration, Route, Source}, mmio::owned::{self, Mapping}, pci::{ Address, Function, @@ -131,14 +129,13 @@ pub struct Inputs< pub retained: RetainedOwner, pub topology: native_aspm::Topology, pub registers: R, - pub attachment: Box, + pub attachment: Attachment, pub pages: Box, pub board: Board, /// Original values read from this same requester's firmware node. pub properties: Vec<(&'static str, Vec)>, pub clock: T, pub interrupts: &'static dyn IrqController, - pub msi_completion: MsiCompletion, } struct Allocator { domain: Arc, @@ -180,7 +177,7 @@ struct ConfigurationState { struct NativeSource { config: Rc>>, signals: Arc, - delivery: Rc>, + requester: crate::bus::pci::requester::RequesterId, } impl NativeSource { fn checked(&self, result: Result<(), Error>, kind: irq::IrqError) -> Result<(), irq::IrqError> { @@ -192,9 +189,10 @@ impl NativeSource { } } // SAFETY: admission is a fresh independently drained unpublished reset epoch; -// retirement's stopped latch requires FLR, domain payload completion -// AND the independent root/route posted-MSI completion. Registry then drains -// CPU pending vectors/callbacks separately. +// retirement's stopped latch requires this owner's authorized containment FLR +// and domain payload completion. It does not advance the ownership generation. +// Registry separately fences the original root route, then CPU/callback/work; +// foreign reset/reassignment invalidates the grant instead of renewing it. unsafe impl Source for NativeSource { fn mask(&mut self) -> Result<(), irq::IrqError> { let result = { @@ -214,20 +212,26 @@ unsafe impl Source for NativeSource { Err(irq::IrqError::Quiesce) } } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> crate::bus::irq::RouteKind { + crate::bus::irq::RouteKind::Msi } - unsafe fn program(&mut self, route: Route) -> Result<(), irq::IrqError> { - let Route::Msi(message) = route else { + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + Some(&self.requester) + } + unsafe fn program( + &mut self, + route: &crate::bus::irq::AllocatedRoute<'_>, + ) -> Result<(), irq::IrqError> { + let Route::Msi(message) = route.programming() else { return Err(irq::IrqError::Route); }; - let result = (|| { - // SAFETY: this Source::program call holds the registry's route - // for the same original requester/root delivery owner. - unsafe { self.delivery.borrow_mut().bind_route(message) }.map_err(Error::Delivery)?; + if !route.matches_requester(&self.requester) { + return Err(irq::IrqError::Route); + } + let result = { // SAFETY: registry keeps the route and original owners. unsafe { self.config.borrow_mut().msi.program(message) }.map_err(Error::Msi) - })(); + }; self.checked(result, irq::IrqError::Route) } unsafe fn unmask(&mut self) -> Result<(), irq::IrqError> { @@ -258,7 +262,7 @@ pub struct NativePlatform< registers: Option, domain: Option>, allocator: Option, - attachment: Option>, + attachment: Option, retention: Option, quiesced: bool, resources_attempted: bool, @@ -269,7 +273,9 @@ pub struct NativePlatform< registration: Option>, signals: Arc, mappings: Vec, - delivery: Option>>, + msi_route: Option, + requester: crate::bus::pci::requester::RequesterId, + irq_retirement: Option, prepared: bool, admission_attempted: bool, retirement_attempted: bool, @@ -368,6 +374,23 @@ impl NativePlatform { Ok(retention) => retention, Err(error) => return Err((Error::Mapping(error), inputs)), }; + // Compare the actual original allocation before any route/entry or + // device write; equal BDF/vendor/BAR numbers are not source authority. + match inputs.attachment.matches_retention(&retention) { + Ok(true) => {} + Ok(false) => { + return Err(( + Error::Requirement("same actual source/attachment config allocation"), + inputs, + )); + } + Err(error) => return Err((Error::Dma(error), inputs)), + } + let requester = inputs.attachment.requester().clone(); + let msi_route = match inputs.attachment.irq_route() { + Ok(route) => route, + Err(error) => return Err((Error::Dma(error), inputs)), + }; let Inputs { function, retained, @@ -379,7 +402,6 @@ impl NativePlatform { properties, clock, interrupts, - msi_completion, } = inputs; let domain = attachment.domain(); Ok(Self { @@ -409,7 +431,9 @@ impl NativePlatform { stopped: AtomicBool::new(true), }), mappings: Vec::new(), - delivery: Some(Rc::new(RefCell::new(msi_completion))), + msi_route: Some(msi_route), + requester, + irq_retirement: None, prepared: false, admission_attempted: false, retirement_attempted: false, @@ -495,16 +519,18 @@ impl NativePlatform { // submissions are terminal, every page/domain/root stays held. // BM/TRPND/reset alone never authorize this operation's success. unsafe { self.domain.as_ref().unwrap().drain_posted_writes() }.map_err(Error::Dma)?; - if self.registration.is_some() { - // SAFETY: source/reset and payload completion above; this - // independently kept root/route owner completes MSI delivery. - unsafe { self.delivery.as_ref().unwrap().borrow().drain() }.map_err(Error::Delivery)?; - } self.signals.stopped.store(true, Ordering::Release); - if let Some(registration) = self.registration.as_mut() - && let Err(error) = registration.retire() - { - return Err(self.irq_error(error)); + if let Some(registration) = self.registration.as_mut() { + let retired = registration + .retire() + .map_err(|error| self.irq_error(error))?; + // SAFETY: exact checked original action/CPU/work retirement. Keep + // callback until source destruction and route through native close. + let (source, handler, route) = + unsafe { retired.into_parts() }.map_err(|failure| self.irq_error(failure.error))?; + drop(source); + drop(handler); + self.irq_retirement = Some(route); } self.registration = None; self.signals.pending.store(false, Ordering::Release); @@ -529,12 +555,33 @@ impl NativePlatform { Error::Requirement("native Broadcom quiescence before resource release").into(), ); } - // SAFETY: full engine/payload/MSI/CPU/work drain excludes every live + // SAFETY: full engine/payload/action/CPU/work drain excludes every live // consumer and original PCI owners remain. Normal transport close // already removed coherent leases. A direct safe platform call before // lease removal independently refuses inside Attachment::detach; // no BAR/config retirement can occur before its acknowledgement. - unsafe { self.attachment.as_mut().unwrap().detach() }.map_err(Error::Dma)?; + if let Some(grant) = self.msi_route.take() { + self.attachment + .as_mut() + .unwrap() + .cancel_unpublished_irq(grant) + .map_err(|failure| Error::Dma(failure.error))?; + } + if let Some(route) = self.irq_retirement.take() { + self.attachment + .as_mut() + .unwrap() + .retain_irq_action(route) + .map_err(|failure| Error::Irq(failure.error))?; + } + // SAFETY: separate terminal engine/payload and DMA-unmap proof above; + // every issued action is canceled or retained with its real join. + let detached = unsafe { self.attachment.as_mut().unwrap().detach() }.map_err(Error::Dma)?; + self.attachment + .as_mut() + .unwrap() + .release_irq_pins(detached) + .map_err(|failure| Error::Irq(failure.error))?; self.retention.take(); if let Some(function) = self.function.take() { self.mappings.push(function.into_config().into_mapping()); @@ -732,18 +779,23 @@ unsafe impl Platform for NativePlatform let source = NativeSource { config: configuration, signals: self.signals.clone(), - delivery: self.delivery.as_ref().unwrap().clone(), + requester: self.requester.clone(), }; - match self - .interrupts - .request(Box::new(source), Arc::new(Callback(self.signals.clone()))) - { + match self.interrupts.request(irq::Request { + source: Box::new(source), + handler: Arc::new(Callback(self.signals.clone())), + routing: irq::RouteRequest::Msi( + self.msi_route + .take() + .ok_or(Error::Requirement("original unused IRQ grant"))?, + ), + }) { Ok(registration) => { self.registration = Some(registration); self.signals.stopped.store(false, Ordering::Release); Ok(()) } - Err(error) => Err(self.irq_error(error)), + Err(error) => Err(self.irq_error(error.error)), } } fn retire_resources(&mut self) -> DriverResult<()> { @@ -751,7 +803,13 @@ unsafe impl Platform for NativePlatform return Err(error.clone()); } if self.resources_attempted { - return self.retirement_error.clone().map_or(Ok(()), Err); + if let Some(route) = &self.irq_retirement { + route.validate().map_err(|error| self.irq_error(error))?; + } + if let Some(attachment) = &self.attachment { + attachment.validate_irq_actions().map_err(Error::Irq)?; + } + return Ok(()); } self.resources_attempted = true; self.retirement_error = @@ -765,7 +823,13 @@ unsafe impl Platform for NativePlatform return Err(error.clone()); } if self.retirement_attempted || self.resources_attempted { - return self.retirement_error.clone().map_or(Ok(()), Err); + if let Some(route) = &self.irq_retirement { + route.validate().map_err(|error| self.irq_error(error))?; + } + if let Some(attachment) = &self.attachment { + attachment.validate_irq_actions().map_err(Error::Irq)?; + } + return Ok(()); } self.retirement_attempted = true; self.retirement_error = @@ -798,6 +862,7 @@ impl Drop for NativePlatform { if let Some(value) = self.retention.take() { core::mem::forget(value); } + core::mem::forget(self.irq_retirement.take()); if let Some(value) = self.domain.take() { core::mem::forget(value); } @@ -810,7 +875,7 @@ impl Drop for NativePlatform { if let Some(value) = self.registration.take() { core::mem::forget(value); } - if let Some(value) = self.delivery.take() { + if let Some(value) = self.msi_route.take() { core::mem::forget(value); } for mapping in self.mappings.drain(..) { diff --git a/crates/stela-drivers/src/bluetooth/bcm4377/native/cold.rs b/crates/stela-drivers/src/bluetooth/bcm4377/native/cold.rs index b990691a68..ea96e3ac14 100644 --- a/crates/stela-drivers/src/bluetooth/bcm4377/native/cold.rs +++ b/crates/stela-drivers/src/bluetooth/bcm4377/native/cold.rs @@ -30,7 +30,7 @@ pub(crate) unsafe trait Preparation: 'static { } pub(crate) struct Finalized { pub function: Function, - pub attachment: Box, + pub attachment: Attachment, } pub(crate) struct FinalizeFailure { pub error: preparation::Error, @@ -81,7 +81,7 @@ pub(crate) struct Cold { } pub(crate) struct Bound { pub function: Function, - pub attachment: Box, + pub attachment: Attachment, pub topology: native_aspm::Topology, pub registers: R, pub clock: T, diff --git a/crates/stela-drivers/src/bluetooth/bcm4377/tests/native.rs b/crates/stela-drivers/src/bluetooth/bcm4377/tests/native.rs index c01063d027..b4857ee879 100644 --- a/crates/stela-drivers/src/bluetooth/bcm4377/tests/native.rs +++ b/crates/stela-drivers/src/bluetooth/bcm4377/tests/native.rs @@ -23,7 +23,7 @@ use crate::bluetooth::bcm4377::native::{ }; use crate::bus::{ dma::{memory::PageSource, pages::DmaPages}, - irq::{self, Registry, posted_msi::MsiCompletion}, + irq::{self, Registry}, mmio::owned::{ self, AddressSpace, Authority, InstalledMapping, MapFailure, MapRequest, Mapping, MappingPlatform, PhysicalSpan, Protection, Resource as MmioResource, ResourceBacking, @@ -56,6 +56,7 @@ enum Event { PageSourceDrop, MsiBind, MsiDrain, + MsiPinRelease, CpuPending, Eoi, BarUnmap, @@ -72,6 +73,10 @@ struct State { fail_cpu: AtomicBool, fail_payload: AtomicBool, fail_msi: AtomicBool, + delivery_available: AtomicBool, + ownership_epoch: AtomicU64, + root_generation: AtomicU64, + owner_thread: std::thread::ThreadId, fail_enable_ack: AtomicBool, fail_master_ack: AtomicBool, panic_master: AtomicBool, @@ -104,6 +109,10 @@ impl State { fail_cpu: AtomicBool::new(false), fail_payload: AtomicBool::new(false), fail_msi: AtomicBool::new(false), + delivery_available: AtomicBool::new(false), + ownership_epoch: AtomicU64::new(1), + root_generation: AtomicU64::new(1), + owner_thread: std::thread::current().id(), fail_enable_ack: AtomicBool::new(false), fail_master_ack: AtomicBool::new(false), panic_master: AtomicBool::new(false), @@ -379,24 +388,58 @@ impl Drop for AttachmentModel { } // SAFETY: one original config seal pins this independent domain generation; // detach refuses mappings and releases that pin only after modeled blocking. -unsafe impl crate::bus::pci::requester::preparation::Attachment for AttachmentModel { +unsafe impl crate::bus::pci::requester::preparation::AttachmentBackend for AttachmentModel { fn domain(&self) -> Arc { self.domain.clone() } - unsafe fn detach(&mut self) -> core::result::Result<(), DmaError> { + fn irq_owner( + &mut self, + _requester: &crate::bus::pci::requester::RequesterId, + _config: Option<&crate::bus::pci::owned::ConfigRetention>, + ) -> core::result::Result>, DmaError> { + if !self.domain.state.delivery_available.load(Ordering::Relaxed) { + return Ok(None); + } + let pin = self + .retention + .as_ref() + .ok_or(DmaError::Unmapped)? + .retain_epoch() + .map_err(|_| DmaError::MappingFailed)?; + Ok(Some(Box::new(Delivery { + state: self.domain.state.clone(), + pin: Some(pin), + epoch: self.domain.state.ownership_epoch.load(Ordering::Relaxed), + root_generation: self.domain.state.root_generation.load(Ordering::Relaxed), + allocated: false, + }))) + } + unsafe fn detach( + &mut self, + ) -> core::result::Result<(), crate::bus::pci::requester::preparation::DetachError> { if self.retention.is_none() { return Ok(()); } if !self.domain.domain.0.lock().unwrap().leases.is_empty() { - return Err(DmaError::MappingFailed); + return Err( + crate::bus::pci::requester::preparation::DetachError::Unexposed( + DmaError::MappingFailed, + ), + ); } self.domain.state.event(Event::Detach); assert!( !self.domain.state.panic_detach.load(Ordering::Relaxed), "injected detach unwind" ); + // Audited model-only refusal: the event log is observational; no + // binding, table, pin or device effect has occurred before this flag. if self.domain.state.fail_detach.load(Ordering::Relaxed) { - return Err(DmaError::DrainUnavailable); + return Err( + crate::bus::pci::requester::preparation::DetachError::Unexposed( + DmaError::DrainUnavailable, + ), + ); } self.domain.state.bound.store(false, Ordering::Relaxed); self.retention.take(); @@ -453,12 +496,20 @@ unsafe impl host::cold::Preparation for PreparingModel { let (function, domain, old_retention) = unsafe { core::mem::ManuallyDrop::take(&mut self.owner) }; drop(old_retention); + let wrapper_pin = retention.retain_epoch().unwrap(); Ok(host::cold::Finalized { function, - attachment: Box::new(AttachmentModel { - domain, - retention: Some(retention), - }), + // SAFETY: same original model configuration/root binding; wrapper + // checks its own live pin through the actual backend detach. + attachment: unsafe { + crate::bus::pci::requester::preparation::Attachment::new( + Box::new(AttachmentModel { + domain, + retention: Some(retention), + }), + wrapper_pin, + ) + }, }) } } @@ -503,40 +554,140 @@ impl PageSource for PageModel { ) } } -struct Delivery(Arc); -// SAFETY: independent route model; payload and MSI completion are -// separate events, with independent injected failures and kept ownership. -unsafe impl irq::posted_msi::DeliveryOwner for Delivery { - fn bind_route( +struct DeliveryDomain { + state: Arc, + pin: ConfigRetention, + epoch: u64, + root_generation: u64, +} +// SAFETY: this exact bounded source holds the actual original config view; +// model root/owner generations are distinct and no native grant is created. +unsafe impl irq::posted_msi::NotificationDomain for DeliveryDomain { + fn check(&self) -> core::result::Result<(), irq::posted_msi::Error> { + if self.state.fail_msi.load(Ordering::Acquire) { + return Err(irq::posted_msi::Error::RootFailed); + } + if self.state.owner_thread != std::thread::current().id() + || self.state.root_generation.load(Ordering::Acquire) != self.root_generation + || self.state.ownership_epoch.load(Ordering::Acquire) != self.epoch + || self.state.dead.load(Ordering::Acquire) + { + return Err(irq::posted_msi::Error::Context); + } + self.pin + .check_live() + .map_err(|_| irq::posted_msi::Error::Context) + } +} +struct Delivery { + state: Arc, + pin: Option, + epoch: u64, + root_generation: u64, + allocated: bool, +} +// SAFETY: exact original RAM config/root model and real retained mapping pin. +// Independent payload/MSI/CPU controls remain separate; the same attachment +// must actually detach before this source pin is explicitly released. +unsafe impl irq::posted_msi::RouteOwner for Delivery { + fn allocate( &mut self, - message: irq::MsiMessage, - ) -> core::result::Result<(), irq::posted_msi::Error> { + target: &irq::CpuTarget<'_>, + ) -> core::result::Result { + target.check_current().map_err(|_| { + irq::posted_msi::AllocationError::Unexposed(irq::posted_msi::Error::Context) + })?; + self.validate() + .map_err(irq::posted_msi::AllocationError::Unexposed)?; + assert!(!self.allocated); + self.allocated = true; + let target = target.descriptor(); + let message = irq::MsiMessage { + address: 0xfee0_0000 | u64::from(target.destination) << 12, + data: u32::from(target.vector), + }; assert_eq!(message.address, 0xfee0_0000); assert_eq!( message.data, - u32::from(self.0.vector.load(Ordering::Relaxed)) + u32::from(self.state.vector.load(Ordering::Relaxed)) ); - self.0.event(Event::MsiBind); + self.state.event(Event::MsiBind); + Ok(message) + } + fn validate(&self) -> core::result::Result<(), irq::posted_msi::Error> { + if self.state.owner_thread != std::thread::current().id() + || self.state.root_generation.load(Ordering::Acquire) != self.root_generation + { + return Err(irq::posted_msi::Error::Context); + } + if let Some(pin) = &self.pin { + // Source/config identity is checked while that exact pin exists. + // Terminal observation never touches a released/reprobed endpoint. + if self.state.ownership_epoch.load(Ordering::Acquire) != self.epoch + || self.state.dead.load(Ordering::Acquire) + { + return Err(irq::posted_msi::Error::Context); + } + pin.check_live() + .map_err(|_| irq::posted_msi::Error::Context)?; + } Ok(()) } - unsafe fn drain_posted_msi(&self) -> core::result::Result<(), irq::posted_msi::Error> { - self.0.event(Event::MsiDrain); + fn notification_domain( + &self, + ) -> core::result::Result, irq::posted_msi::Error> + { + self.validate()?; + let pin = self + .pin + .as_ref() + .ok_or(irq::posted_msi::Error::Unbound)? + .retain_epoch() + .map_err(|_| irq::posted_msi::Error::Context)?; + Ok(Arc::new(DeliveryDomain { + state: self.state.clone(), + pin, + epoch: self.epoch, + root_generation: self.root_generation, + })) + } + unsafe fn strong_fence(&mut self) -> core::result::Result<(), irq::posted_msi::Error> { + self.validate()?; + self.state.event(Event::MsiDrain); assert_eq!( - self.0.events.lock().unwrap().iter().rev().nth(1), + self.state.events.lock().unwrap().iter().rev().nth(1), Some(&Event::PayloadDrain) ); - if self.0.fail_msi.load(Ordering::Relaxed) { + if self.state.fail_msi.load(Ordering::Relaxed) { return Err(irq::posted_msi::Error::RootFailed); } Ok(()) } + unsafe fn release_endpoint( + &mut self, + proof: &irq::posted_msi::EndpointRetirement<'_>, + ) -> core::result::Result<(), irq::posted_msi::Error> { + self.validate()?; + assert!(proof.requester().is_some()); + assert!(!self.state.bound.load(Ordering::Relaxed)); + self.state.event(Event::MsiPinRelease); + self.pin.take(); + Ok(()) + } } + struct Cpu(Arc); // SAFETY: explicit same-CPU APIC delivery model, Registry controls slots. unsafe impl irq::Platform for Cpu { fn check_cpu(&self) -> core::result::Result<(), irq::IrqError> { + if self.0.owner_thread != std::thread::current().id() { + return Err(irq::IrqError::WrongCpu); + } Ok(()) } + fn check_process(&self) -> core::result::Result<(), crate::bus::irq::IrqError> { + self.check_cpu() + } fn save_and_disable(&self) -> u64 { 0 } @@ -552,9 +703,13 @@ unsafe impl irq::Platform for Cpu { self.0.event(Event::CpuPending); Ok(self.0.fail_cpu.load(Ordering::Relaxed) || self.0.pending.load(Ordering::Relaxed)) } - fn eoi(&self) { + fn eoi( + &self, + _vector: u8, + ) -> core::result::Result { self.0.event(Event::Eoi); self.0.pending.store(false, Ordering::Relaxed); + Ok(crate::bus::irq::Trigger::Edge) } fn ticks(&self) -> u64 { self.0.accesses.fetch_add(1, Ordering::Relaxed) as u64 @@ -704,6 +859,9 @@ fn fixture_native_setup( Ok(bound) => bound, Err(failure) => return Err((failure.error.clone(), state, counters, device)), }; + state + .delivery_available + .store(completion, Ordering::Relaxed); let inputs = Inputs { function: bound.function, retained: Arc::new(Root(state.clone())), @@ -716,11 +874,6 @@ fn fixture_native_setup( clock: bound.clock, // SAFETY: original_inputs leaked this same model Registry. interrupts: unsafe { &*state.registry.load(Ordering::Relaxed) }, - msi_completion: if completion { - MsiCompletion::model(Box::new(Delivery(state.clone()))) - } else { - MsiCompletion::unavailable() - }, }; Ok(Fixture { inputs, @@ -870,8 +1023,11 @@ fn all_four_native_ids_use_real_registry_msi_dma_hci_and_ordered_retirement() { t.close().unwrap(); let events = state.events.lock().unwrap().clone(); assert!(position(&events, Event::Reset) < position(&events, Event::PayloadDrain)); - assert!(position(&events, Event::PayloadDrain) < position(&events, Event::MsiDrain)); - assert!(position(&events, Event::MsiDrain) < position(&events, Event::CpuPending)); + assert!( + !events.contains(&Event::MsiDrain), + "action join does not claim fabric completion" + ); + assert!(position(&events, Event::PayloadDrain) < position(&events, Event::CpuPending)); assert!(position(&events, Event::CpuPending) < position(&events, Event::BarUnmap)); assert!(position(&events, Event::CpuPending) < position(&events, Event::DmaUnmap)); assert!(position(&events, Event::DmaUnmap) < position(&events, Event::Detach)); @@ -908,14 +1064,13 @@ fn native_unpublished_close_stops_the_prepared_bus_master_and_releases_without_r } #[test] fn every_distinct_retirement_failure_keeps_original_route_pins_root_and_first_error() { - for failure in 0..7 { - let (mut t, device, state, counters) = transport(fixture_native(0x5f69, failure != 3)); + for failure in [0, 1, 2, 4, 5, 6] { + let (mut t, device, state, counters) = transport(fixture_native(0x5f69, true)); t.start(&catalog(&device, false)).unwrap(); match failure { 0 => state.stuck_pending.store(true, Ordering::Relaxed), 1 => state.fail_payload.store(true, Ordering::Relaxed), 2 => state.fail_msi.store(true, Ordering::Relaxed), - 3 => {} 4 => state.fail_cpu.store(true, Ordering::Relaxed), 5 => state.fail_bar_unmap.store(true, Ordering::Relaxed), 6 => state.fail_detach.store(true, Ordering::Relaxed), @@ -1491,3 +1646,92 @@ fn protocol_close_unwind_seals_every_public_admission_before_platform_retirement assert_eq!(counters.unmaps.load(Ordering::Relaxed), 0); assert!(!device.lock().unwrap().dropped); } + +#[test] +fn containment_flr_preserves_retiring_owner_but_foreign_generation_refuses() { + let (mut first_transport, device, state, _) = transport(fixture_native(0x5f69, true)); + first_transport.start(&catalog(&device, false)).unwrap(); + let epoch = state.ownership_epoch.load(Ordering::Relaxed); + first_transport.close().unwrap(); + assert_eq!(state.ownership_epoch.load(Ordering::Relaxed), epoch); + let events = state.events.lock().unwrap(); + let detached = events.iter().rposition(|e| *e == Event::Detach).unwrap(); + let pin = events + .iter() + .rposition(|e| *e == Event::MsiPinRelease) + .unwrap(); + let config = events + .iter() + .rposition(|e| *e == Event::ConfigUnmap) + .unwrap(); + assert!(detached < pin && pin < config); + drop(events); + + let (mut transport, device, state, counters) = transport(fixture_native(0x5f69, true)); + transport.start(&catalog(&device, false)).unwrap(); + state.ownership_epoch.fetch_add(1, Ordering::Relaxed); + assert!(transport.close().is_err()); + assert_eq!(counters.unmaps.load(Ordering::Relaxed), 0); + assert!(!device.lock().unwrap().dropped); +} + +#[test] +fn equal_bdf_different_actual_config_attachment_refuses_before_native_admission() { + let mut source = fixture_native(0x5f69, true); + let mut foreign = fixture_native(0x5f69, true); + assert_eq!( + source.inputs.function.address, + foreign.inputs.function.address + ); + // Real independent RAM configuration allocations, not source IDs/numbers. + let source_pin = source.inputs.function.config().retain_epoch().unwrap(); + assert!( + source + .inputs + .attachment + .matches_retention(&source_pin) + .unwrap() + ); + assert!( + !foreign + .inputs + .attachment + .matches_retention(&source_pin) + .unwrap() + ); + std::mem::swap( + &mut source.inputs.attachment, + &mut foreign.inputs.attachment, + ); + let writes = source + .state + .events + .lock() + .unwrap() + .iter() + .filter(|event| matches!(event, Event::Write(..))) + .count(); + // SAFETY: bounded read-only adversarial source assembly: all input graphs + // remain retained, but their claimed association must be rejected. + let (error, returned) = match unsafe { NativePlatform::new(source.inputs) } { + Ok(_) => panic!("foreign actual configuration admitted"), + Err(failure) => failure, + }; + assert!(matches!( + error, + host::Error::Requirement("same actual source/attachment config allocation") + )); + let events = source.state.events.lock().unwrap(); + assert_eq!( + events + .iter() + .filter(|event| matches!(event, Event::Write(..))) + .count(), + writes + ); + assert!(!events.contains(&Event::MsiBind)); + assert_eq!(source.counters.unmaps.load(Ordering::Relaxed), 0); + // Default erroneous-input abandonment cannot release uncertain native pins. + core::mem::forget(returned); + core::mem::forget(foreign.inputs); +} diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie.rs b/crates/stela-drivers/src/bluetooth/intel_pcie.rs index dfb03aad63..4539303ac2 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie.rs @@ -76,6 +76,7 @@ pub enum State { Rom, Iml, Operational, + Closing, Closed, Failed, } @@ -242,7 +243,18 @@ impl Transport

{ &mut self.snapshot, ) } + fn admission(&self) -> Result<()> { + if self.retirement_attempted { + return Err(self + .retirement_error + .as_deref() + .cloned() + .unwrap_or(Error::State(self.state))); + } + Ok(()) + } pub fn start(&mut self) -> Result<()> { + self.admission()?; if self.state != State::Allocated { return Err(Error::State(self.state)); } @@ -487,6 +499,7 @@ impl Transport

{ self.platform.service_complete() } fn active(&self) -> Result<()> { + self.admission()?; if matches!(self.state, State::Rom | State::Iml | State::Operational) { Ok(()) } else { @@ -649,13 +662,25 @@ impl Transport

{ } fn retire(&mut self) -> Result<()> { if self.retirement_attempted { - return self - .retirement_error - .as_deref() - .cloned() - .map_or(Ok(()), Err); + return self.retirement_error.as_deref().cloned().map_or_else( + || { + if self.retired { + Ok(()) + } else { + Err(Error::Unsupported("interrupted Intel PCIe retirement")) + } + }, + Err, + ); } + let failed = self.state == State::Failed; self.retirement_attempted = true; + self.state = State::Closing; + // Seal every public admission before any register/reset/root callback. + // This error remains if a foreign callback unwinds below this owner. + self.retirement_error = Some(Box::new(Error::Unsupported( + "interrupted Intel PCIe retirement", + ))); let result: Result<()> = (|| { self.write(FH_MASK, u32::MAX)?; self.write(HW_MASK, u32::MAX)?; @@ -678,9 +703,14 @@ impl Transport

{ match result { Ok(()) => { self.retired = true; + self.retirement_error = None; + if failed { + self.state = State::Failed; + } Ok(()) } Err(e) => { + self.state = State::Failed; self.retirement_error = Some(Box::new(e.clone())); Err(e) } diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/firmware.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/firmware.rs index 3cae85faf1..3131ec3313 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/firmware.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/firmware.rs @@ -34,6 +34,12 @@ pub fn initialize( provider: &dyn Provider, platform: intel::PlatformInputs, ) -> Result { + if let Err(error) = transport.active() { + return Err(Error { + cause: Box::new(intel::Error::PcieTransport(error)), + received: Vec::new(), + }); + } let mut io = Native { transport, received: Vec::new(), diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/native.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/native.rs index d0caa721c1..493f64414d 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/native.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/native.rs @@ -8,9 +8,7 @@ use crate::bus::pci::regs; use crate::{ Clock, bus::{ - irq::{ - self, Disposition, Handler, IrqController, IrqRegistration, Route, RouteRequest, Source, - }, + irq::{self, Disposition, Handler, IrqController, IrqRegistration, Route, Source}, mmio::owned::{self, CacheAttribute, Mapping, PhysicalSpan, Protection}, pci::{ Function, @@ -139,7 +137,7 @@ pub struct Inputs { pub clock: Clock, pub interrupts: &'static dyn IrqController, pub domain: Arc, - pub msi_completion: irq::posted_msi::MsiCompletion, + pub msi_route: irq::posted_msi::MsiRoute, } struct Signals { registers: R, @@ -220,9 +218,8 @@ struct NativeSource { configuration: Rc>>, signals: Arc>, domain: Arc, - delivery: Rc>, + requester: Option, programmed: bool, - drained: bool, } impl NativeSource { fn checked( @@ -239,8 +236,8 @@ impl NativeSource { } // SAFETY: the consumed native grant binds PCI/reset/UC/DMA ownership. // Source quiescence observes stop/reset/cause acknowledgments, completes the -// paired payload path and independently drains bound posted MSI-X delivery. -// Registry then drains CPU/callbacks before pending work is canceled. +// paired payload path. Registry separately fences the original retained root +// route before CPU/callback drain and actual pending-work cancellation. unsafe impl Source for NativeSource { fn mask(&mut self) -> core::result::Result<(), irq::IrqError> { let result = self @@ -254,7 +251,7 @@ unsafe impl Source for NativeSour fn quiesce(&mut self) -> core::result::Result<(), irq::IrqError> { let result = (|| { self.signals.stopped()?; - if self.programmed && !self.drained { + if self.programmed { // SAFETY: this original function acknowledged disconnect/reset, // all MSI-X entries are masked, and the serialized core cannot // resume. Its buffers/configuration and root remain held. @@ -262,30 +259,36 @@ unsafe impl Source for NativeSour operation: lifetime::DmaOperation::Drain, source, })?; - // SAFETY: same source/payload completion, masked original route - // and kept owners. This is independent of payload/CPU drain. - unsafe { self.delivery.borrow().drain() }.map_err(Error::Delivery)?; - self.drained = true; } Ok(()) })(); self.checked(result, irq::IrqError::Quiesce) } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> crate::bus::irq::RouteKind { + crate::bus::irq::RouteKind::Msi } - unsafe fn program(&mut self, route: Route) -> core::result::Result<(), irq::IrqError> { - let Route::Msi(message) = route else { + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + self.requester.as_ref() + } + unsafe fn program( + &mut self, + route: &crate::bus::irq::AllocatedRoute<'_>, + ) -> core::result::Result<(), irq::IrqError> { + let Route::Msi(message) = route.programming() else { return Err(irq::IrqError::Route); }; + if self + .requester + .as_ref() + .is_some_and(|own| !route.matches_requester(own)) + { + return Err(irq::IrqError::Route); + } self.programmed = true; - let result = (|| { - // SAFETY: Source::program holds this registry's original exclusive - // route for the paired requester/root owner. - unsafe { self.delivery.borrow_mut().bind_route(message) }.map_err(Error::Delivery)?; + let result = { // SAFETY: registry keeps the checked route/callback while masked. unsafe { self.configuration.borrow_mut().msix.program(message) }.map_err(Error::Msix) - })(); + }; self.checked(result, irq::IrqError::Route) } unsafe fn unmask(&mut self) -> core::result::Result<(), irq::IrqError> { @@ -308,7 +311,9 @@ pub struct NativePlatform { signals: Option>>, interrupts: &'static dyn IrqController, domain: Option>, - delivery: Option>>, + msi_route: Option, + requester: Option, + irq_retirement: Option, clock: Clock, clock_origin: u64, registration: Option>, @@ -324,8 +329,10 @@ impl NativePl /// its coordinator. Supplied DMA retains coherent mappings and page pins /// for this requester; bus addresses need not equal physical/CPU addresses. /// IRQ routing is real/checked. `domain` is the paired coherent payload - /// root; `msi_completion` owns its independent posted-interrupt path. - /// Unavailable completion permits I/O but refuses armed route retirement. + /// root; `msi_route` owns genuine stable notification admission. Attached + /// native routes require the owning assembler's actual configuration + /// allocation check before a private Source requester can be assigned. + /// Missing admission refuses before IRQ publication. /// Only one serialized process/deferred owner may service this transport; /// the callback's pending flag is its entire work queue. No source, /// mapping, DMA or reset owner may be revoked while kept. Native mappings @@ -395,7 +402,7 @@ impl NativePl clock, interrupts, domain, - msi_completion, + msi_route, } = inputs; // SAFETY: same consumed Function/reset/resources grant. Old real // routes/CPU callbacks are independently drained; no numeric substitute. @@ -412,7 +419,7 @@ impl NativePl clock, interrupts, domain, - msi_completion, + msi_route, }, )); } @@ -437,7 +444,9 @@ impl NativePl })), interrupts, domain: Some(domain), - delivery: Some(Rc::new(RefCell::new(msi_completion))), + msi_route: Some(msi_route), + requester: None, + irq_retirement: None, clock, clock_origin, registration: None, @@ -529,17 +538,25 @@ unsafe impl P configuration: self.configuration.as_ref().unwrap().clone(), signals: self.signals.as_ref().unwrap().clone(), domain: self.domain.as_ref().unwrap().clone(), - delivery: self.delivery.as_ref().unwrap().clone(), + requester: self.requester.clone(), programmed: false, - drained: false, }; let handler = Callback(self.signals.as_ref().unwrap().clone()); - match self.interrupts.request(Box::new(source), Arc::new(handler)) { + let routing = irq::RouteRequest::Msi( + self.msi_route + .take() + .ok_or(Error::Requirement("original unused IRQ grant"))?, + ); + match self.interrupts.request(irq::Request { + source: Box::new(source), + handler: Arc::new(handler), + routing, + }) { Ok(registration) => { self.registration = Some(registration); Ok(()) } - Err(error) => Err(self.irq_error(error)), + Err(error) => Err(self.irq_error(error.error)), } } fn service_complete(&mut self) -> DriverResult<()> { @@ -585,23 +602,38 @@ unsafe impl P } fn retire_vector_zero(&mut self) -> DriverResult<()> { if self.retired { + if let Some(route) = &self.irq_retirement { + route.validate().map_err(|error| self.irq_error(error))?; + } return Ok(()); } if self.attempted && self.registration.is_none() { return Err(Error::Requirement("uncertain native IRQ admission retained").into()); } - if let Some(registration) = self.registration.as_mut() - && let Err(error) = registration.retire() - { - return Err(self.irq_error(error)); + if let Some(registration) = self.registration.as_mut() { + let retired = registration + .retire() + .map_err(|error| self.irq_error(error))?; + // SAFETY: exact same checked native route; source is released while + // its callback remains kept, after actual action/CPU/work retirement. + let (source, handler, mut route) = + unsafe { retired.into_parts() }.map_err(|failure| self.irq_error(failure.error))?; + if route.requester().is_none() { + // Only the feature-confined no-native-pin fixture can succeed. + route + .release_unattached_fixture() + .map_err(|error| self.irq_error(error))?; + } + drop(source); + drop(handler); + self.irq_retirement = Some(route); } - // The registry masks MSI-X before its source quiescence checks. - // A failed DMA stop still gets that real mask/quarantine attempt. self.signals().stopped()?; self.registration = None; let mut configuration = self.configuration.as_ref().unwrap().borrow_mut(); - // SAFETY: bus-master stop/reset/cause acknowledgments and real - // registry CPU/callback/work drain all completed. DMA pages remain pinned. + // SAFETY: exact retained route and Registry action/CPU/work retirement, + // or the original never-programmed path; device stop is acknowledged. + // DMA and the independent IRQ config pin remain held for native close. let owners = unsafe { configuration.msix.release() }.map_err(Error::Msix)?; configuration.released = Some(owners); self.retired = true; @@ -622,7 +654,8 @@ impl Drop for NativePlatform NativePlatform { + fn check_attachment( + &mut self, + attachment: &crate::bus::pci::requester::preparation::Attachment, + ) -> DriverResult<()> { + let source = self + .configuration + .as_ref() + .ok_or(Error::Requirement("original MSI-X owner"))? + .borrow() + .msix + .retain_config_epoch() + .map_err(Error::Msix)?; + if !attachment + .matches_retention(&source) + .map_err(|error| Error::Dma { + operation: lifetime::DmaOperation::Drain, + source: error, + })? + { + return Err( + Error::Requirement("same actual MSI-X/attachment config allocation").into(), + ); + } + if !self + .msi_route + .as_ref() + .is_some_and(|route| route.belongs_to(attachment.requester())) + { + return Err(Error::Requirement("same original requester IRQ attachment").into()); + } + // Only this checked real source-owner assembly can assign requester. + // The generic constructor cannot copy authority from arbitrary grant + // metadata into a different Function or configuration allocation. + self.requester = Some(attachment.requester().clone()); + Ok(()) + } + fn take_unpublished_irq(&mut self) -> Option { + self.msi_route.take() + } + fn take_retired_irq(&mut self) -> Option { + self.irq_retirement.take() + } fn stop_requester( &mut self, seal: &crate::bus::pci::owned::ConfigRetention, diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/native/cold.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/native/cold.rs index e353907455..8b722cf0cb 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/native/cold.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/native/cold.rs @@ -38,7 +38,7 @@ pub struct Cold { pub struct Bound { pub requester: StoppedRequester, pub registers: R, - pub attachment: Box, + pub attachment: Attachment, } /// Failed cold preparation never releases the original root/BAR graph. pub struct Failure { diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/native/lifetime.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/native/lifetime.rs index 0ab3f67989..cac8d43d02 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/native/lifetime.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/native/lifetime.rs @@ -25,12 +25,12 @@ pub enum DmaOperation { pub struct Inputs { pub platform: NativePlatform, pub allocator: DomainAllocator<'static>, - pub attachment: Box, + pub attachment: Attachment, pub retention: ConfigRetention, } struct Allocations { allocator: DomainAllocator<'static>, - attachment: Box, + attachment: Attachment, retention: Option, } struct AllocationOwner(Option>); @@ -85,10 +85,23 @@ impl OwnedTransport { fn transport_mut(&mut self) -> &mut Transport> { &mut self.resources.as_deref_mut().unwrap().transport } + fn admission(&self) -> Result<()> { + if let Some(error) = &self.failure { + return Err(error.clone()); + } + if self.completed { + return Err(Error::State( + self.resources.as_deref().unwrap().transport.state(), + )); + } + Ok(()) + } pub fn start(&mut self) -> Result<()> { + self.admission()?; self.transport_mut().start() } pub fn poll(&mut self) -> Result> { + self.admission()?; self.transport_mut().poll() } pub fn send( @@ -96,9 +109,11 @@ impl OwnedTransport { kind: super::super::Kind, bytes: &[u8], ) -> Result { + self.admission()?; self.transport_mut().send(kind, bytes) } pub fn enter_d0(&mut self) -> Result { + self.admission()?; self.transport_mut().enter_d0() } pub fn initialize_firmware( @@ -106,6 +121,12 @@ impl OwnedTransport { provider: &dyn crate::firmware::Provider, platform: crate::bluetooth::intel::PlatformInputs, ) -> core::result::Result { + if let Err(error) = self.admission() { + return Err(super::super::firmware::Error { + cause: Box::new(crate::bluetooth::intel::Error::PcieTransport(error)), + received: alloc::vec::Vec::new(), + }); + } super::super::firmware::initialize(self.transport_mut(), provider, platform) } /// # Safety @@ -116,11 +137,21 @@ impl OwnedTransport { /// exclusions and the original processor/root context remain held. pub unsafe fn new(inputs: Inputs) -> core::result::Result { let Inputs { - platform, + mut platform, allocator, attachment, retention, } = inputs; + if let Err(error) = platform.check_attachment(&attachment) { + return Err(Failure { + error, + _allocations: AllocationOwner(Some(Box::new(Allocations { + allocator, + attachment, + retention: Some(retention), + }))), + }); + } let mut allocations = AllocationOwner(Some(Box::new(Allocations { allocator, attachment, @@ -156,6 +187,11 @@ impl OwnedTransport { if let Some(error) = &self.failure { return Err(error.clone()); } + // Unlike a returned error, unwind cannot run the match below. Seal + // outer ownership/admissions before the first core/config/DMA effect. + self.failure = Some(Error::Unsupported( + "interrupted owned Intel PCIe retirement", + )); let result: Result<()> = (|| { let Resources { transport, @@ -182,10 +218,33 @@ impl OwnedTransport { .map_err(|error| Error::Dma(BlockError::Dma(error)))?; // SAFETY: every mapping is gone and the original function cannot // resume. The same config/BAR/root owners remain through detach. - unsafe { allocation.attachment.detach() }.map_err(|source| NativeError::Dma { - operation: DmaOperation::Detach, - source, - })?; + if let Some(grant) = transport.platform.take_unpublished_irq() { + allocation + .attachment + .cancel_unpublished_irq(grant) + .map_err(|failure| NativeError::Dma { + operation: DmaOperation::Detach, + source: failure.error, + })?; + } + + if let Some(route) = transport.platform.take_retired_irq() { + allocation + .attachment + .retain_irq_action(route) + .map_err(|failure| NativeError::Irq(failure.error))?; + } + // SAFETY: original terminal engine/payload proof and every DMA + // mapping is gone; exact action joins remain kept in Attachment. + let detached = + unsafe { allocation.attachment.detach() }.map_err(|source| NativeError::Dma { + operation: DmaOperation::Detach, + source, + })?; + allocation + .attachment + .release_irq_pins(detached) + .map_err(|failure| NativeError::Irq(failure.error))?; // The seal was checked before DMA retirement; release its view so // configuration mapping retirement can complete after detach. allocation.retention.take(); @@ -198,6 +257,7 @@ impl OwnedTransport { match result { Ok(()) => { self.completed = true; + self.failure = None; Ok(()) } Err(error) => { diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests.rs index eeab8cf072..ef945cafbe 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests.rs @@ -1,3 +1,4 @@ +extern crate std; use super::*; use crate::bus::dma::RegionAllocator; use alloc::{collections::BTreeMap, rc::Rc}; @@ -58,6 +59,7 @@ pub(super) struct Model { d0_delay: u64, read_error: Option, write_error: Option<(usize, usize)>, + panic_write: Option, byte_error: Option, context: u64, posted: BTreeMap, @@ -122,6 +124,7 @@ impl Model { d0_delay: 0, read_error: None, write_error: None, + panic_write: None, byte_error: None, context: 0, posted: BTreeMap::new(), @@ -221,6 +224,7 @@ impl Model { } fn write32(&mut self, o: usize, v: u32) { self.writes.push((self.time.get(), o, v)); + assert_ne!(self.panic_write, Some(o), "injected native register unwind"); match o { FH_CAUSE | HW_CAUSE | AUTOMASK => { let old = self.reg(o); @@ -1473,3 +1477,46 @@ fn firmware_error_drains_complete_native_packets_queued_before_send_or_poll_fail mod native_models; mod ownership; + +struct NeverFirmware; +impl crate::firmware::Provider for NeverFirmware { + fn load( + &self, + _: crate::firmware::Requirement<'_>, + ) -> core::result::Result, crate::firmware::Error> { + panic!("closed transport must not request firmware") + } +} +#[test] +fn retirement_unwind_seals_core_before_the_first_register_effect() { + let mut backing = vec![0u64; 1024 * 1024]; + let mut dma = allocator(&mut backing); + let (mut transport, model) = transport(0x4d76, &mut dma); + transport.start().unwrap(); + model.borrow_mut().panic_write = Some(FH_MASK); + assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| transport.close())).is_err()); + assert_eq!(transport.state(), State::Closing); + model.borrow_mut().panic_write = None; + let writes = model.borrow().writes.clone(); + let error = Error::Unsupported("interrupted Intel PCIe retirement"); + assert_eq!(transport.start(), Err(error.clone())); + assert_eq!(transport.poll(), Err(error.clone())); + assert_eq!( + transport.send(Kind::Command, &[3, 12, 0]), + Err(error.clone()) + ); + assert_eq!(transport.enter_d0(), Err(error.clone())); + assert!(!transport.ready()); + assert!( + firmware::initialize( + &mut transport, + &NeverFirmware, + crate::bluetooth::intel::PlatformInputs::default() + ) + .is_err() + ); + assert_eq!(transport.close(), Err(error)); + drop(transport); + assert_eq!(model.borrow().writes, writes); + assert_eq!(model.borrow().retire_count, 0); +} diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models.rs index 6342dafcbe..c34f541b84 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models.rs @@ -1,4 +1,4 @@ -//! Native IRQ/HCI models with separate payload and posted-MSI completion. +//! Bounded native IRQ/HCI models: action joins are separate from payload/fabric. extern crate std; use super::*; use crate::{ @@ -23,7 +23,7 @@ struct Hardware { fail_table: Option, payload_drains: usize, msi_drains: usize, - cpu_after_delivery: usize, + cpu_after_payload: usize, fail_payload: bool, fail_posted_msi: bool, fail_msi_bind: bool, @@ -48,7 +48,7 @@ impl Hardware { fail_table: None, payload_drains: 0, msi_drains: 0, - cpu_after_delivery: 0, + cpu_after_payload: 0, fail_payload: false, fail_posted_msi: false, fail_msi_bind: false, @@ -237,6 +237,9 @@ unsafe impl irq::Platform for Cpu { fn check_cpu(&self) -> core::result::Result<(), irq::IrqError> { Ok(()) } + fn check_process(&self) -> core::result::Result<(), crate::bus::irq::IrqError> { + self.check_cpu() + } fn save_and_disable(&self) -> u64 { 0 } @@ -251,8 +254,7 @@ unsafe impl irq::Platform for Cpu { { let mut h = self.hardware.lock().unwrap(); if h.payload_drains != 0 { - assert!(h.msi_drains != 0); - h.cpu_after_delivery += 1; + h.cpu_after_payload += 1; } } if self.fail_pending.load(Ordering::Acquire) { @@ -261,8 +263,12 @@ unsafe impl irq::Platform for Cpu { Ok(false) } } - fn eoi(&self) { + fn eoi( + &self, + _vector: u8, + ) -> core::result::Result { self.eoi.fetch_add(1, Ordering::Relaxed); + Ok(crate::bus::irq::Trigger::Edge) } fn ticks(&self) -> u64 { self.ticks.fetch_add(1, Ordering::Relaxed) @@ -305,7 +311,7 @@ fn inputs() -> Context { }, interrupts: registry, domain: Arc::new(root::Payload(h.clone())), - msi_completion: root::completion(h.clone()), + msi_route: root::completion(h.clone()), }; (inputs, h, registry, fail_pending) } @@ -353,7 +359,7 @@ fn native_owned_function_msix_callback_and_dma_service_release_only_after_real_r t.close().unwrap(); assert_eq!(t.state(), State::Closed); assert!(!h.lock().unwrap().bt.armed); - assert!(!registry.dispatch(irq::FIRST_VECTOR)); + assert!(registry.dispatch(irq::FIRST_VECTOR)); drop(t); let h = h.lock().unwrap(); assert_eq!((h.config_drops, h.bar_drops, h.register_drops), (1, 1, 1)); @@ -542,7 +548,7 @@ fn native_constructor_refuses_unqualified_inputs_without_writes_and_returns_owne assert_eq!(h.lock().unwrap().config, before); assert!(h.lock().unwrap().table_writes.is_empty()); assert!(h.lock().unwrap().bt.writes.is_empty()); - assert!(!registry.dispatch(irq::FIRST_VECTOR)); + assert!(registry.dispatch(irq::FIRST_VECTOR)); } } #[test] diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models/root.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models/root.rs index bdac23063d..1dc4799e78 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models/root.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/native_models/root.rs @@ -50,26 +50,77 @@ unsafe impl DmaDomain for Payload { } } } -struct Delivery(Arc>); -// SAFETY: original synchronous route peer. Binding checks the registry's exact -// model message; posted interrupt completion is independent of payload/CPU IO. -unsafe impl irq::posted_msi::DeliveryOwner for Delivery { - fn bind_route( +struct DeliveryDomain { + hardware: Arc>, + thread: std::thread::ThreadId, +} +// SAFETY: same original synchronous device/root peer and actual owner thread; +// this fixture has no physical/remapping authority or native mode transition. +unsafe impl irq::posted_msi::NotificationDomain for DeliveryDomain { + fn check(&self) -> core::result::Result<(), irq::posted_msi::Error> { + if self.thread != std::thread::current().id() { + return Err(irq::posted_msi::Error::Context); + } + let hardware = self.hardware.lock().unwrap(); + if hardware.config_drops != 0 || hardware.register_drops != 0 { + return Err(irq::posted_msi::Error::RootFailed); + } + Ok(()) + } +} +struct Delivery { + hardware: Arc>, + owner: std::thread::ThreadId, +} +// SAFETY: original synchronous isolated route peer, with independent payload +// and root completion controls, no native configuration pin or DMA attachment. +unsafe impl irq::posted_msi::RouteOwner for Delivery { + fn allocate( &mut self, - message: irq::MsiMessage, - ) -> core::result::Result<(), irq::posted_msi::Error> { + target: &irq::CpuTarget<'_>, + ) -> core::result::Result { + target.check_current().map_err(|_| { + irq::posted_msi::AllocationError::Unexposed(irq::posted_msi::Error::Context) + })?; + let target = target.descriptor(); + let message = irq::MsiMessage { + address: 0xfee0_0000 | u64::from(target.destination) << 12, + data: u32::from(target.vector), + }; assert_eq!(message.address, 0xfee01000); assert_eq!(message.data, u32::from(irq::FIRST_VECTOR)); - let mut h = self.0.lock().unwrap(); + let mut h = self.hardware.lock().unwrap(); assert!(h.msi_message.replace(message).is_none()); if h.fail_msi_bind { - Err(irq::posted_msi::Error::RootFailed) + Err(irq::posted_msi::AllocationError::Uncertain( + irq::posted_msi::Error::RootFailed, + )) + } else { + Ok(message) + } + } + fn validate(&self) -> core::result::Result<(), irq::posted_msi::Error> { + if self.owner != std::thread::current().id() { + Err(irq::posted_msi::Error::Context) } else { Ok(()) } } - unsafe fn drain_posted_msi(&self) -> core::result::Result<(), irq::posted_msi::Error> { - let mut h = self.0.lock().unwrap(); + fn notification_domain( + &self, + ) -> core::result::Result, irq::posted_msi::Error> + { + self.validate()?; + // Original resource custody is live before route allocation; binding + // itself is installed before the guard enters a LIVE Slot. + Ok(Arc::new(DeliveryDomain { + hardware: self.hardware.clone(), + thread: self.owner, + })) + } + unsafe fn strong_fence(&mut self) -> core::result::Result<(), irq::posted_msi::Error> { + self.validate()?; + let mut h = self.hardware.lock().unwrap(); assert!(h.payload_drains > 0); assert!(!h.bt.armed); assert!(h.msi_message.is_some()); @@ -80,50 +131,56 @@ unsafe impl irq::posted_msi::DeliveryOwner for Delivery { Ok(()) } } + unsafe fn release_endpoint( + &mut self, + proof: &irq::posted_msi::EndpointRetirement<'_>, + ) -> core::result::Result<(), irq::posted_msi::Error> { + self.validate()?; + assert!(proof.requester().is_none()); + Ok(()) + } } -pub(super) fn completion(h: Arc>) -> irq::posted_msi::MsiCompletion { - irq::posted_msi::MsiCompletion::model(Box::new(Delivery(h))) +pub(super) fn completion(hardware: Arc>) -> irq::posted_msi::MsiRoute { + // SAFETY: bounded no-native-pin test peer above; not NativeServices and + // cannot supply an Attachment or a shared reset retirement receipt. + unsafe { + irq::posted_msi::MsiRoute::bounded_fixture(Box::new(Delivery { + hardware, + owner: std::thread::current().id(), + })) + } +} + +#[test] +fn missing_notification_admission_refuses_before_source_programming() { + let mut backing = vec![0u64; 1024 * 1024]; + let mut dma = allocator(&mut backing); + let (mut inputs, h, _, _) = inputs(); + inputs.msi_route = irq::posted_msi::MsiRoute::unavailable(); + // SAFETY: original bounded device model; no native capability is minted. + let platform = + unsafe { native::NativePlatform::new(inputs) }.unwrap_or_else(|(e, _)| panic!("{e:?}")); + let mut t = Transport::new(platform, &mut dma).unwrap(); + assert!(t.start().is_err()); + assert!(h.lock().unwrap().msi_message.is_none()); + drop(t); + let h = h.lock().unwrap(); + assert_eq!(h.msi_drains, 0); + assert_eq!((h.config_drops, h.bar_drops, h.register_drops), (0, 0, 0)); } #[test] -fn missing_or_failed_posted_completion_keeps_armed_route_and_all_owners() { - for unavailable in [false, true] { - let mut backing = vec![0u64; 1024 * 1024]; - let mut dma = allocator(&mut backing); - let (mut inputs, h, registry, _) = inputs(); - if unavailable { - inputs.msi_completion = irq::posted_msi::MsiCompletion::unavailable(); - } - // SAFETY: explicit original synchronous device/root/IRQ fixture. - let platform = - unsafe { native::NativePlatform::new(inputs) }.unwrap_or_else(|(e, _)| panic!("{e:?}")); - let mut t = Transport::new(platform, &mut dma).unwrap(); - t.start().unwrap(); - if !unavailable { - h.lock().unwrap().fail_posted_msi = true; - } - let error = t - .close() - .expect_err("independent posted completion required"); - assert_eq!( - error, - Error::Native(native::Error::Delivery(if unavailable { - irq::posted_msi::Error::RootUnavailable - } else { - irq::posted_msi::Error::RootFailed - })) - ); - assert!(!t.retired); - assert_eq!(t.state(), State::Failed); - let writes = h.lock().unwrap().bt.writes.len(); - assert_eq!(t.close(), Err(error)); - assert!(registry.dispatch(irq::FIRST_VECTOR)); - drop(t); - let h = h.lock().unwrap(); - assert_eq!(h.payload_drains, 1); - assert_eq!(h.msi_drains, usize::from(!unavailable)); - assert_eq!((h.config_drops, h.bar_drops, h.register_drops), (0, 0, 0)); - assert_eq!(h.bt.writes.len(), writes); - } +fn independent_fabric_pending_does_not_substitute_for_action_or_payload_join() { + let mut backing = vec![0u64; 1024 * 1024]; + let mut dma = allocator(&mut backing); + let (mut t, h, registry, _) = attach(&mut dma); + t.start().unwrap(); + h.lock().unwrap().fail_posted_msi = true; + t.close().unwrap(); + assert!(registry.dispatch(irq::FIRST_VECTOR)); // ordinary unbound EOI only + drop(t); + let h = h.lock().unwrap(); + assert_eq!((h.payload_drains, h.msi_drains), (1, 0)); + assert_eq!((h.config_drops, h.bar_drops, h.register_drops), (1, 1, 1)); } #[test] fn payload_failure_does_not_claim_posted_interrupt_completion() { @@ -140,7 +197,7 @@ fn payload_failure_does_not_claim_posted_interrupt_completion() { assert_eq!((h.config_drops, h.bar_drops, h.register_drops), (0, 0, 0)); } #[test] -fn successful_completion_orders_payload_then_posted_delivery_before_cpu_retirement() { +fn terminal_endpoint_close_orders_payload_before_action_and_native_resources() { let mut backing = vec![0u64; 1024 * 1024]; let mut dma = allocator(&mut backing); let (mut t, h, registry, _) = attach(&mut dma); @@ -150,11 +207,11 @@ fn successful_completion_orders_payload_then_posted_delivery_before_cpu_retireme assert_eq!((h.payload_drains, h.msi_drains), (0, 0)); } t.close().unwrap(); - assert!(!registry.dispatch(irq::FIRST_VECTOR)); + assert!(registry.dispatch(irq::FIRST_VECTOR)); drop(t); let h = h.lock().unwrap(); - assert_eq!((h.payload_drains, h.msi_drains), (1, 1)); - assert!(h.cpu_after_delivery > 0); + assert_eq!((h.payload_drains, h.msi_drains), (1, 0)); + assert!(h.cpu_after_payload > 0); assert_eq!((h.config_drops, h.bar_drops, h.register_drops), (1, 1, 1)); } diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership.rs index d909388a10..b27fc20c61 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership.rs @@ -14,7 +14,7 @@ use crate::bus::{ owned::test_support::{Counters, fixture}, requester::{ FunctionRole, RequesterBinding, - preparation::{self, Attachment, Root}, + preparation::{self, Root}, }, }, }; diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/cold.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/cold.rs index 7ec8a95643..5fd303641c 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/cold.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/cold.rs @@ -13,10 +13,10 @@ fn reset_and_original_drain_precede_private_binding() { ); assert_eq!(counts.unmaps.load(Ordering::Relaxed), 0); assert_eq!(root.registers_dropped.load(Ordering::Relaxed), 0); - assert_eq!( - bound.requester.into_function().config().read16(4) & 0x406, - 0x402 - ); + // Keep the actual configuration owner through the attachment's detach. + // A temporary Function here would quarantine its mapping after this read. + let mut function = bound.requester.into_function(); + assert_eq!(function.config().read16(4) & 0x406, 0x402); // SAFETY: this model admits no mappings or asynchronous users. unsafe { bound.attachment.detach() }.unwrap(); drop(bound.registers); diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/lifetime.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/lifetime.rs index 00dad93f2f..2f67eb5cf0 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/lifetime.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/lifetime.rs @@ -178,3 +178,49 @@ fn failed_engine_stop_keeps_dma_and_original_native_graph() { assert_eq!(root.registers_dropped.load(Ordering::Relaxed), 0); assert_eq!(counts.unmaps.load(Ordering::Relaxed), 0); } + +#[test] +fn core_and_post_core_unwind_never_reopen_owned_transport_or_retry_effects() { + for (phase, nth) in [ + ("reset", 1), + ("domain drain", 1), + ("unmap", 2), + ("detach", 1), + ("register retire", 1), + ] { + let root = Arc::new(RootState::default()); + let (mut transport, counts) = owned(root.clone()); + root.events.lock().unwrap().clear(); + *root.panic_phase.lock().unwrap() = Some(phase); + root.panic_nth.store(nth, Ordering::Relaxed); + assert!( + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| transport.close())).is_err(), + "{phase}" + ); + *root.panic_phase.lock().unwrap() = None; + let events = root.events.lock().unwrap().clone(); + let unmaps = counts.unmaps.load(Ordering::Relaxed); + let error = Error::Unsupported("interrupted owned Intel PCIe retirement"); + assert_eq!(transport.start(), Err(error.clone())); + assert_eq!(transport.poll(), Err(error.clone())); + assert_eq!( + transport.send(Kind::Command, &[3, 12, 0]), + Err(error.clone()) + ); + assert_eq!(transport.enter_d0(), Err(error.clone())); + assert!(!transport.ready()); + assert!( + transport + .initialize_firmware( + &super::super::NeverFirmware, + crate::bluetooth::intel::PlatformInputs::default() + ) + .is_err() + ); + assert_eq!(transport.close(), Err(error)); + drop(transport); + assert_eq!(*root.events.lock().unwrap(), events, "{phase}"); + assert_eq!(counts.unmaps.load(Ordering::Relaxed), unmaps, "{phase}"); + assert_eq!(root.registers_dropped.load(Ordering::Relaxed), 0, "{phase}"); + } +} diff --git a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/model.rs b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/model.rs index e8e5909560..6f62cf6d39 100644 --- a/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/model.rs +++ b/crates/stela-drivers/src/bluetooth/intel_pcie/tests/ownership/model.rs @@ -5,6 +5,9 @@ pub(super) struct RootState { pub events: Mutex>, pub fail_config: Mutex>>, pub fail: Mutex>, + pub panic_phase: Mutex>, + pub panic_nth: AtomicUsize, + pub panic_hits: AtomicUsize, pub registers_dropped: AtomicUsize, pub bars_dropped: AtomicUsize, pub pages_dropped: AtomicUsize, @@ -16,6 +19,15 @@ pub(super) struct RootState { impl RootState { fn step(&self, name: &'static str) -> core::result::Result<(), DmaError> { self.events.lock().unwrap().push(name); + let panic_phase = *self.panic_phase.lock().unwrap(); + if panic_phase == Some(name) { + let hit = self.panic_hits.fetch_add(1, Ordering::Relaxed) + 1; + assert_ne!( + hit, + self.panic_nth.load(Ordering::Relaxed), + "injected native close unwind" + ); + } if *self.fail.lock().unwrap() == Some(name) { Err(DmaError::InvalidationFailed) } else { @@ -33,7 +45,10 @@ unsafe impl Root for OldRoot { unsafe fn bind( &self, binding: RequesterBinding, - ) -> core::result::Result, DmaError> { + ) -> core::result::Result< + Box, + DmaError, + > { self.0.step("bind")?; binding.check_live().unwrap(); assert!(self.0.bound.lock().unwrap().replace(binding).is_none()); @@ -50,11 +65,13 @@ impl Drop for Control { } // SAFETY: unique synchronous model attachment; refuses live mappings and only // clears its kept configuration after acknowledged symbolic detach. -unsafe impl Attachment for Control { +unsafe impl crate::bus::pci::requester::preparation::AttachmentBackend for Control { fn domain(&self) -> Arc { Arc::new(Domain(self.0.clone())) } - unsafe fn detach(&mut self) -> core::result::Result<(), DmaError> { + unsafe fn detach( + &mut self, + ) -> core::result::Result<(), crate::bus::pci::requester::preparation::DetachError> { assert!(self.0.live.lock().unwrap().is_empty()); self.0.step("detach")?; self.0 @@ -164,7 +181,11 @@ unsafe impl native::Registers for Registers { } m.write32(offset, value); if offset == FUNC && value & RESET != 0 { - self.root.events.lock().unwrap().push("reset"); + // Record the actual modeled store through the common phase hook, + // including its effect-then-unwind injection used by close tests. + self.root + .step("reset") + .map_err(|_| native::Error::Requirement("modeled reset register effect"))?; } if m.write_error.is_some_and(|(at, _)| at == offset) { return Err(native::Error::Requirement("late modeled store")); @@ -325,9 +346,9 @@ struct NoInterrupts; impl irq::IrqController for NoInterrupts { fn request( &'static self, - _: Box, - _: Arc, - ) -> core::result::Result, irq::IrqError> { + request: irq::Request>, + ) -> core::result::Result, irq::RequestError> { + let _kept = core::mem::ManuallyDrop::new(request); panic!("unstarted transport admits no IRQ") } fn quarantine_count(&self) -> u64 { @@ -340,12 +361,13 @@ pub(super) fn owned_inputs( root: Arc, ) -> (native::lifetime::Inputs, Arc) { let (cold, counts) = cold(root.clone()); - let bound = cold + let mut bound = cold .quiesce_and_bind() .unwrap_or_else(|f| panic!("{:?}", f.error)); let mut function = bound.requester.into_function(); let retention = function.config().retain_epoch().unwrap(); function.enable_polled(); + let msi_route = bound.attachment.irq_route().unwrap(); let inputs = native::Inputs { function, retained: Arc::new(()), @@ -354,7 +376,7 @@ pub(super) fn owned_inputs( clock: CLOCK, interrupts: &NO_INTERRUPTS, domain: bound.attachment.domain(), - msi_completion: irq::posted_msi::MsiCompletion::unavailable(), + msi_route, }; // SAFETY: exclusively owned model uses the same cold receipt/root/BAR. let platform = diff --git a/crates/stela-drivers/src/input/ish/native.rs b/crates/stela-drivers/src/input/ish/native.rs index e0dc531a40..cfcad9b2d8 100644 --- a/crates/stela-drivers/src/input/ish/native.rs +++ b/crates/stela-drivers/src/input/ish/native.rs @@ -10,9 +10,7 @@ use crate::{ Clock, bus::{ dma::mapping::DmaDomain, - irq::{ - self, Disposition, Handler, IrqController, IrqRegistration, Route, RouteRequest, Source, - }, + irq::{self, Disposition, Handler, IrqController, IrqRegistration, Route, Source}, pci::{ Address, CapabilityError, Function, Layout, msi::{self, DisabledMsiConfig, MsiConfig, MsiConfigSpace, RetainedOwner}, @@ -75,6 +73,7 @@ pub struct Inputs< pub registers: R, pub domain: Arc, pub interrupts: &'static dyn IrqController, + pub msi_route: irq::posted_msi::MsiRoute, pub clock: T, } struct Signals { @@ -152,8 +151,9 @@ struct NativeSource { shared: Arc>, } // SAFETY: fresh admission is independently stopped/drained. After any route -// programming this source cannot claim posted-MSI completion: quiesce refuses -// and every owner stays held. No inferred barrier grants route reuse. +// This owner has no qualified terminal IRQ-action/pending-cause join yet; +// quiesce refuses after publication and keeps every uncertain owner. Neither +// payload completion nor notification-domain admission supplies that join. unsafe impl Source for NativeSource { fn mask(&mut self) -> core::result::Result<(), irq::IrqError> { let result = (|| { @@ -177,11 +177,17 @@ unsafe impl Source for NativeSource { Ok(()) } } - fn route(&self) -> RouteRequest { - RouteRequest::Msi + fn route_kind(&self) -> crate::bus::irq::RouteKind { + crate::bus::irq::RouteKind::Msi } - unsafe fn program(&mut self, route: Route) -> core::result::Result<(), irq::IrqError> { - let Route::Msi(message) = route else { + fn requester(&self) -> Option<&crate::bus::pci::requester::RequesterId> { + None + } + unsafe fn program( + &mut self, + route: &crate::bus::irq::AllocatedRoute<'_>, + ) -> core::result::Result<(), irq::IrqError> { + let Route::Msi(message) = route.programming() else { return Err(irq::IrqError::Route); }; self.shared @@ -229,6 +235,7 @@ pub struct Native< shared: Option>>, config: Option>>>, registration: Option>, + msi_route: Option, interrupts: &'static dyn IrqController, clock: T, engine: Engine, @@ -259,6 +266,10 @@ impl Native { /// service/stop; only the documented IRQ callback accesses shared registers. /// Clock/domain/native access contracts remain valid for every owner. /// Rejection returns original owners without any native write. + #[expect( + clippy::result_large_err, + reason = "rejection returns every affine input without allocating or releasing resources" + )] pub unsafe fn new( mut inputs: Inputs, ) -> core::result::Result)> { @@ -337,6 +348,7 @@ impl Native { registers, domain, interrupts, + msi_route, clock, } = inputs; Ok(Self { @@ -356,6 +368,7 @@ impl Native { })), config: None, registration: None, + msi_route: Some(msi_route), interrupts, clock, engine: Engine::new(), @@ -529,18 +542,28 @@ impl Native { shared: shared.clone(), }); let callback = Arc::new(Callback(shared)); - self.registration = Some(match self.interrupts.request(source, callback) { - Ok(registration) => registration, - Err(error) => { - return Err(self - .config - .as_ref() - .unwrap() - .borrow() - .failure - .unwrap_or(Error::Irq(error))); - } - }); + self.registration = Some( + match self.interrupts.request(irq::Request { + source, + handler: callback, + routing: irq::RouteRequest::Msi( + self.msi_route + .take() + .ok_or(Error::Requirement("original unused IRQ route"))?, + ), + }) { + Ok(registration) => registration, + Err(error) => { + return Err(self + .config + .as_ref() + .unwrap() + .borrow() + .failure + .unwrap_or(Error::Irq(error.error))); + } + }, + ); self.accept_reset = true; self.reset_ready = false; let host = read(self.regs(), HOST_COMM)?; @@ -944,8 +967,8 @@ impl Native { // SAFETY: submissions/firmware DMA are terminal and acknowledged idle; // original domain/root/config/IRQ/mappings remain held. unsafe { self.domain.as_ref().unwrap().drain_posted_writes() }.map_err(Error::Dma)?; - // No registration.retire/release/unmap. Translated payload - // completion does not drain already posted MSI on the original route. + // No registration.retire/release/unmap: this adapter has no terminal + // old service/pending-cause action join. Payload drain cannot invent it. Err(Error::PostedMsiRetirementUnavailable) } } @@ -953,6 +976,9 @@ impl Drop for Native { fn drop(&mut self) { // Neither Drop nor a failed stop can certify original posted-MSI/root // completion. Preserve every uncertain owner, even after panic. + if let Some(v) = self.msi_route.take() { + core::mem::forget(v); + } if let Some(v) = self.registration.take() { core::mem::forget(v); } diff --git a/crates/stela-drivers/src/input/ish/tests.rs b/crates/stela-drivers/src/input/ish/tests.rs index d71469a2da..14885cf1fb 100644 --- a/crates/stela-drivers/src/input/ish/tests.rs +++ b/crates/stela-drivers/src/input/ish/tests.rs @@ -656,12 +656,85 @@ unsafe impl DmaDomain for Domain { } } } +struct NotificationPeer { + peer: Arc, + thread: std::thread::ThreadId, +} +// SAFETY: actual original bounded BAR/device peer and its creating thread; +// no native requester, fabric completion or Attachment receipt is supplied. +unsafe impl irq::posted_msi::NotificationDomain for NotificationPeer { + fn check(&self) -> core::result::Result<(), irq::posted_msi::Error> { + if self.thread != std::thread::current().id() { + return Err(irq::posted_msi::Error::Context); + } + self.peer + .view + .check_current() + .map_err(|_| irq::posted_msi::Error::Context) + } +} +struct DeliveryPeer { + peer: Arc, + thread: std::thread::ThreadId, + allocated: bool, +} +// SAFETY: synchronous explicit source model, no native root/endpoint grant. +unsafe impl irq::posted_msi::RouteOwner for DeliveryPeer { + fn allocate( + &mut self, + target: &irq::CpuTarget<'_>, + ) -> core::result::Result { + self.validate() + .map_err(irq::posted_msi::AllocationError::Unexposed)?; + target.check_current().map_err(|_| { + irq::posted_msi::AllocationError::Unexposed(irq::posted_msi::Error::Context) + })?; + if self.allocated { + return Err(irq::posted_msi::AllocationError::Unexposed( + irq::posted_msi::Error::AlreadyBound, + )); + } + self.allocated = true; + let target = target.descriptor(); + Ok(irq::MsiMessage { + address: 0xfee0_0000 | u64::from(target.destination) << 12, + data: u32::from(target.vector), + }) + } + fn validate(&self) -> core::result::Result<(), irq::posted_msi::Error> { + irq::posted_msi::NotificationDomain::check(&NotificationPeer { + peer: self.peer.clone(), + thread: self.thread, + }) + } + fn notification_domain( + &self, + ) -> core::result::Result, irq::posted_msi::Error> + { + self.validate()?; + Ok(Arc::new(NotificationPeer { + peer: self.peer.clone(), + thread: self.thread, + })) + } + unsafe fn release_endpoint( + &mut self, + _proof: &irq::posted_msi::EndpointRetirement<'_>, + ) -> core::result::Result<(), irq::posted_msi::Error> { + // NativeSource deliberately cannot retire yet. Never turn the missing + // source protocol into a successful empty fixture acknowledgement. + Err(irq::posted_msi::Error::Unsupported) + } +} struct Cpu(Arc); // SAFETY: serial software CPU/real Registry fixture, not a native IRQ adapter. unsafe impl irq::Platform for Cpu { fn check_cpu(&self) -> core::result::Result<(), irq::IrqError> { Ok(()) } + fn check_process(&self) -> core::result::Result<(), crate::bus::irq::IrqError> { + self.check_cpu() + } fn save_and_disable(&self) -> u64 { 0 } @@ -676,8 +749,12 @@ unsafe impl irq::Platform for Cpu { fn pending(&self, _: u8) -> core::result::Result { Ok(false) } - fn eoi(&self) { + fn eoi( + &self, + _vector: u8, + ) -> core::result::Result { self.0.eois.fetch_add(1, Ordering::Relaxed); + Ok(crate::bus::irq::Trigger::Edge) } fn ticks(&self) -> u64 { self.0.state.lock().unwrap().now @@ -766,6 +843,14 @@ fn inputs() -> Parts { }, domain: Arc::new(Domain(peer.clone())), interrupts: registry, + // SAFETY: exact original bounded fixture peer only, no native pin. + msi_route: unsafe { + irq::posted_msi::MsiRoute::bounded_fixture(Box::new(DeliveryPeer { + peer: peer.clone(), + thread: std::thread::current().id(), + allocated: false, + })) + }, clock: ClockModel(peer.clone()), }, peer, diff --git a/crates/stela-drivers/src/probe/native.rs b/crates/stela-drivers/src/probe/native.rs index 38fa42b69f..28280dd38d 100644 --- a/crates/stela-drivers/src/probe/native.rs +++ b/crates/stela-drivers/src/probe/native.rs @@ -9,7 +9,6 @@ use crate::{ bluetooth::{bcm4377, intel_pcie}, bus::{ dma::{DomainAllocator, mapping::DmaDomain}, - irq::posted_msi::MsiCompletion, mmio::owned::{CacheAttribute, Mapping, Protection}, pci::{ Address, Bar, ConfigSpace, Function, @@ -1067,9 +1066,6 @@ pub(super) unsafe fn bcm4377( properties: Vec::new(), clock: bound.clock, interrupts, - // No root delivery adapter completes posted MSIs yet, so a stopped - // function stays quarantined with its owners rather than retired. - msi_completion: MsiCompletion::unavailable(), }; // SAFETY: vendor FLR/D0/BAR restore, original-root drain and current-epoch // binding completed under the same owners. Constructor performs no reset; @@ -1157,7 +1153,7 @@ pub(super) unsafe fn intel_bluetooth( Ok(cold) => cold, Err((error, inputs)) => return Err(failed(error, Box::new((inputs, table)))), }; - let bound = match cold.quiesce_and_bind() { + let mut bound = match cold.quiesce_and_bind() { Ok(bound) => bound, Err(failure) => { let error = failure.error.clone(); @@ -1174,11 +1170,43 @@ pub(super) unsafe fn intel_bluetooth( )); } }; + match bound.attachment.matches_config(function.config()) { + Ok(true) => {} + Ok(false) => { + return Err(failed( + native::Error::Requirement("same original BT config allocation").into(), + Box::new((function, bound.registers, bound.attachment, retention)), + )); + } + Err(error) => { + return Err(failed( + native::Error::Dma { + operation: lifetime::DmaOperation::Drain, + source: error, + } + .into(), + Box::new((function, bound.registers, bound.attachment, retention)), + )); + } + } // Vendor disconnect/reset, original-root drain and current-epoch binding // are complete. BME now permits only the subsequently allocated new domain. function.enable_polled(); let mut msix = [const { None }; 6]; msix[0] = Some(table); + let msi_route = match bound.attachment.irq_route() { + Ok(route) => route, + Err(error) => { + return Err(failed( + native::Error::Dma { + operation: lifetime::DmaOperation::Drain, + source: error, + } + .into(), + Box::new((function, msix, bound.registers, bound.attachment, retention)), + )); + } + }; let inputs = Inputs { function, retained: Arc::new(authority), @@ -1187,7 +1215,7 @@ pub(super) unsafe fn intel_bluetooth( clock, interrupts, domain: bound.attachment.domain(), - msi_completion: MsiCompletion::unavailable(), + msi_route, }; // SAFETY: same original stopped function/root, acknowledged memory/BME, // coherent domain, routed IRQ provider and checked UC/MSI-X owners. @@ -1298,6 +1326,10 @@ pub(super) unsafe fn ish( registers, domain, interrupts, + // No original stable notification/source grant is supplied by this + // producer yet. Registry refuses before programming instead of + // deriving native root authority from a numeric target. + msi_route: crate::bus::irq::posted_msi::MsiRoute::unavailable(), clock, }; // SAFETY: the mount claimed the stopped function, mapped its BAR0 and diff --git a/crates/stela-drivers/src/usb/ehci/native/requester.rs b/crates/stela-drivers/src/usb/ehci/native/requester.rs index 1defe27ef4..b5b69e7e9f 100644 --- a/crates/stela-drivers/src/usb/ehci/native/requester.rs +++ b/crates/stela-drivers/src/usb/ehci/native/requester.rs @@ -6,7 +6,7 @@ pub(super) enum Requester { Preparing(PreparingRequester), Bound { pci: Function, - attachment: Box, + attachment: preparation::Attachment, }, Retired { pci: Function, diff --git a/crates/stela-drivers/src/usb/xhci/native.rs b/crates/stela-drivers/src/usb/xhci/native.rs index 3d7ec2aaa8..10b05e634d 100644 --- a/crates/stela-drivers/src/usb/xhci/native.rs +++ b/crates/stela-drivers/src/usb/xhci/native.rs @@ -37,6 +37,9 @@ struct Owner { // Neither a replacement domain nor HCRST certifies old-route retirement. resources: RefCell>, register_failure: Rc>>, + // Keep the exact retired action/source/route graph through subsequent + // device work; IRQ action retirement does not release endpoint resources. + retired_irq: RefCell>>, } struct Access(Rc); @@ -407,6 +410,7 @@ pub unsafe fn attach( let owner = Rc::new(Owner { resources: RefCell::new(ManuallyDrop::new(resources)), register_failure: Rc::new(Cell::new(None)), + retired_irq: RefCell::new(None), }); let mut controller = None; let mut retained_memory = None; @@ -447,7 +451,8 @@ pub unsafe fn attach( } // Original source mask, callback synchronization and route // retirement; IMAN.IE=0 alone cannot establish these facts. - resources.irq.retire().map_err(Error::Irq)?; + let retired = resources.irq.retire().map_err(Error::Irq)?; + *owner.retired_irq.borrow_mut() = Some(retired); let command = resources.function.config().read16(4); resources.function.config().write16(4, command | 2 | 0x400); if resources.function.config().read16(4) & 0x406 != 0x402 { diff --git a/crates/stela-linux/Cargo.toml b/crates/stela-linux/Cargo.toml index 9a8015b316..207794e209 100644 --- a/crates/stela-linux/Cargo.toml +++ b/crates/stela-linux/Cargo.toml @@ -10,9 +10,10 @@ workspace = true [features] # Default builds require no external Linux source. -kernel = ["dep:cc", "dep:stela-c-build", "stela-c-build/linux-registry", "stela-driver-base/linux-kernel"] +kernel = ["dep:stela-driver-core", "dep:cc", "dep:stela-c-build", "stela-c-build/linux-registry", "stela-driver-base/linux-kernel"] [dependencies] +stela-driver-core = { path = "../stela-driver-core", optional = true } stela-driver-base = { path = "../stela-driver-base" } stela-crypto = { path = "../stela-crypto" } zeroize = { version = "1.9", default-features = false, features = ["alloc"] } diff --git a/crates/stela-linux/build/native.rs b/crates/stela-linux/build/native.rs index eb5ca046f4..1f7e0d61c9 100644 --- a/crates/stela-linux/build/native.rs +++ b/crates/stela-linux/build/native.rs @@ -290,6 +290,26 @@ impl Linux { ("linux_kstrtox", "kstrtox.c", "STELA_LINUX_KSTRTOX_TEST"), ("linux_jiffies", "jiffies.c", "STELA_LINUX_JIFFIES_TEST"), ("linux_device", "device.c", "STELA_LINUX_DEVICE_TEST"), + ( + "linux_device_catalogue", + "catalogue.c", + "STELA_LINUX_CATALOGUE_TEST", + ), + ( + "linux_device_catalogue_legacy", + "catalogue.c", + "STELA_LINUX_CATALOGUE_LEGACY_TEST", + ), + ( + "linux_device_catalogue_task", + "catalogue.c", + "STELA_LINUX_CATALOGUE_TASK_TEST", + ), + ( + "linux_device_catalogue_workqueue", + "catalogue.c", + "STELA_LINUX_CATALOGUE_WORKQUEUE_TEST", + ), ("linux_file", "file.c", "STELA_LINUX_FILE_TEST"), ("linux_mapping", "mapping.c", "STELA_LINUX_MAPPING_TEST"), ("linux_reclaim", "reclaim.c", "STELA_LINUX_RECLAIM_TEST"), diff --git a/crates/stela-linux/src/catalogue.rs b/crates/stela-linux/src/catalogue.rs new file mode 100644 index 0000000000..31ef65a88d --- /dev/null +++ b/crates/stela-linux/src/catalogue.rs @@ -0,0 +1,378 @@ +//! Exact original-device firmware metadata, backed by real C device references. +//! These leases retain source custody and data; they grant no active I/O or +//! ownership of an original driver's arbitrary callback context. +use alloc::{boxed::Box, rc::Rc, string::String, sync::Arc}; +use core::{ + cell::RefCell, + ffi::c_void, + marker::PhantomData, + ptr::NonNull, + sync::atomic::{AtomicU64, Ordering}, +}; +use stela_driver_base::bus::pci::{ + owned::{ConfigRetention, OwnedConfig}, + requester::{RequesterId, preparation::Attachment}, +}; +use stela_driver_core::firmware::{Catalog, Target}; + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum Error { + InvalidTarget(&'static str), + SourceBusy, + ForeignSource, + NativeSource(stela_driver_base::bus::dma::mapping::DmaError), + Config(stela_driver_base::bus::mmio::owned::Error), + Native(i32), +} +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "device catalogue: {self:?}") + } +} +impl core::error::Error for Error {} + +/// Owned exact label syntax only; these strings grant no source authority. +/// Native enrollment separately proves manifest/observed-device correspondence. +/// None is a board-independent exact target, not an inferred board wildcard. +pub struct FirmwareTarget { + driver: String, + hardware: String, + revision: String, + board: Option, +} +impl FirmwareTarget { + pub fn new( + driver: String, + hardware: String, + revision: String, + board: Option, + ) -> Result { + for (name, value) in [ + ("driver", driver.as_str()), + ("hardware", hardware.as_str()), + ("revision", revision.as_str()), + ] + .into_iter() + .chain(board.as_deref().map(|value| ("board", value))) + { + if value.is_empty() || value.chars().any(char::is_control) { + return Err(Error::InvalidTarget(name)); + } + } + Ok(Self { + driver, + hardware, + revision, + board, + }) + } + pub fn view(&self) -> Target<'_> { + Target { + driver: &self.driver, + hardware: &self.hardware, + revision: &self.revision, + board: self.board.as_deref(), + } + } +} + +/// Shared custody of the actual original attachment allocation. The slot is +/// private: safe callers cannot replace it with another requester's attachment. +pub struct FunctionCustody { + attachment: RefCell, + requester: RequesterId, +} +impl FunctionCustody { + pub fn new(attachment: Attachment) -> Rc { + let requester = attachment.requester().clone(); + Rc::new(Self { + attachment: RefCell::new(attachment), + requester, + }) + } + pub fn requester(&self) -> &RequesterId { + &self.requester + } + /// Native control of this same original allocation, never a catalogue grant. + /// + /// # Safety + /// The original method's actual CPU/context/I/O permissions hold. Do not + /// replace/retarget the attachment, sleep, reenter or call Linux/driver code + /// while this short mutable borrow exists. Never detach, consume/release + /// original ConfigRetention or replace its epoch through this callback: + /// catalogue/device/request custodians still own that exact allocation. + /// Final detach uses into_attachment only after the last Rc custodian ends. + /// Route/wait objects must be moved out before any callback or suspension. + pub unsafe fn with_native( + &self, + operation: impl FnOnce(&mut Attachment) -> R, + ) -> Result { + let mut attachment = self + .attachment + .try_borrow_mut() + .map_err(|_| Error::SourceBusy)?; + Ok(operation(&mut attachment)) + } + /// Only ownership transfer after all actual catalogue/lease custodians end; + /// the returned attachment still requires its native IRQ/DMA detach proofs. + pub fn into_attachment(self: Rc) -> Result> { + Rc::try_unwrap(self).map(|source| source.attachment.into_inner()) + } +} + +/// Keeps the actual native attachment/configuration custody, not just its ID. +/// Native control keeps its own Rc; catalogue users cannot borrow the attachment. +pub struct PciAuthority { + _config: ConfigRetention, + _execution: super::kernel::ExecutionPin, + source: Rc, + requester: RequesterId, + target: FirmwareTarget, + catalog: Arc, +} +impl PciAuthority { + /// Qualify a manifest target against this actual original native function. + /// + /// # Safety + /// The exact driver/hardware/revision/board labels and Catalog resources + /// are approved for this same observed original OwnedConfig allocation and + /// retained attachment, including the actual board identity when required. + /// This is the native source/manifest qualification boundary: syntax, + /// filename, BDF, driver name or another device's valid image is no proof. + /// Keep the actual observation/provenance and original source epoch valid; + /// any requalification follows native removal/retirement, not relabeling. + pub unsafe fn new( + kernel: &super::kernel::KernelOwner, + source: Rc, + original: &OwnedConfig, + target: FirmwareTarget, + catalog: Arc, + ) -> Result { + let requester = { + let source = source + .attachment + .try_borrow() + .map_err(|_| Error::SourceBusy)?; + if !source + .matches_config(original) + .map_err(Error::NativeSource)? + { + return Err(Error::ForeignSource); + } + source.requester().clone() + }; + // Actual original mapping/allocation custody, never a cloned writer or + // permission to access config after its native epoch stops admitting it. + let config = original.retain_epoch().map_err(Error::Config)?; + Ok(Self { + _config: config, + _execution: kernel.execution(), + source, + requester, + target, + catalog, + }) + } + pub fn requester(&self) -> &RequesterId { + &self.requester + } + pub(crate) fn domain( + &self, + ) -> Result, Error> { + let source = self + .source + .attachment + .try_borrow() + .map_err(|_| Error::SourceBusy)?; + if !source.requester().same_requester(&self.requester) { + return Err(Error::ForeignSource); + } + Ok(source.domain()) + } +} + +/// Only explicit enrollment of the original regulatory device creates this +/// route. It is never inferred from a resource or faux-device name. +pub struct GlobalAuthority { + target: FirmwareTarget, + catalog: Arc, + _execution: super::kernel::ExecutionPin, +} +pub enum Authority { + Pci(PciAuthority), + GlobalRegulatory(GlobalAuthority), +} +impl Authority { + pub(crate) fn global_regulatory( + target: FirmwareTarget, + catalog: Arc, + execution: super::kernel::ExecutionPin, + ) -> Self { + Self::GlobalRegulatory(GlobalAuthority { + target, + catalog, + _execution: execution, + }) + } + pub fn target(&self) -> Target<'_> { + match self { + Self::Pci(pci) => pci.target.view(), + Self::GlobalRegulatory(global) => global.target.view(), + } + } + pub fn catalog(&self) -> &Catalog { + match self { + Self::Pci(pci) => &pci.catalog, + Self::GlobalRegulatory(global) => &global.catalog, + } + } + pub fn requester(&self) -> Option<&RequesterId> { + match self { + Self::Pci(pci) => Some(pci.requester()), + Self::GlobalRegulatory(_) => None, + } + } +} +#[repr(C)] +struct RawLease { + device: *mut c_void, + authority: *const c_void, +} +unsafe extern "C" { + fn stela_linux_device_bind( + device: *mut c_void, + authority: *mut c_void, + release: unsafe extern "C" fn(*mut c_void), + ) -> i32; + fn stela_linux_device_acquire(device: *mut c_void, lease: *mut RawLease) -> i32; + fn stela_linux_device_release(lease: *mut RawLease) -> i32; +} +unsafe extern "C" fn release_authority(authority: *mut c_void) { + // SAFETY: bind transferred exactly this Box on success; original final + // device retirement invokes this once in its canonical process owner. + drop(unsafe { Box::from_raw(authority.cast::()) }); +} + +/// # Safety +/// Entered canonical process owner; device is the original initialized object +/// still owned by its prepare/global registration. Failure transfers nothing. +pub(crate) unsafe fn bind( + device: *mut c_void, + authority: Box, +) -> Result<(), (Box, Error)> { + let authority = Box::into_raw(authority); + // SAFETY: the exact C object and owned authority above obey the caller's contract. + let status = unsafe { stela_linux_device_bind(device, authority.cast(), release_authority) }; + if status == 0 { + Ok(()) + } else { + // SAFETY: failure took no authority ownership and invoked no destructor. + Err((unsafe { Box::from_raw(authority) }, Error::Native(status))) + } +} + +static RETAINED: AtomicU64 = AtomicU64::new(0); +/// Leases abandoned without the explicit process-owner release remain held. +pub fn retained_leases() -> u64 { + RETAINED.load(Ordering::Relaxed) +} + +/// An actual original C device ref and its source record. This is neither a +/// driver-context reference nor permission to access the requester. +#[must_use = "release explicitly in the canonical process owner or retain the real device reference"] +pub struct DeviceLease { + raw: RawLease, + released: bool, + local: PhantomData<*mut ()>, +} +impl DeviceLease { + /// # Safety + /// The caller holds the original Linux API's valid device/reference + /// contract and is on the canonical owner's checked Linux task/CPU. + pub unsafe fn acquire(device: *mut c_void) -> Result { + let mut raw = RawLease { + device: core::ptr::null_mut(), + authority: core::ptr::null(), + }; + // SAFETY: C checks original enrolled membership before taking its real reference. + let status = unsafe { stela_linux_device_acquire(device, &raw mut raw) }; + if status != 0 { + return Err(Error::Native(status)); + } + assert!(!raw.device.is_null() && !raw.authority.is_null()); + Ok(Self { + raw, + released: false, + local: PhantomData, + }) + } + pub fn authority(&self) -> &Authority { + let authority = NonNull::new(self.raw.authority.cast_mut().cast::()) + .expect("live authority"); + // SAFETY: the real C reference keeps the Rust-created enrolled source + // record alive through original final release; no driver context is borrowed. + unsafe { authority.as_ref() } + } + /// # Safety + /// Same canonical process owner/CPU, quiescent outside atomic/RCU delivery. + /// A refusal returns the unchanged real reference for retained retry. + pub unsafe fn release(mut self) -> Result<(), Self> { + // SAFETY: caller establishes the process release scope; C refuses before effects otherwise. + if unsafe { stela_linux_device_release(&raw mut self.raw) } != 0 { + return Err(self); + } + self.released = true; + Ok(()) + } +} +impl Drop for DeviceLease { + fn drop(&mut self) { + if !self.released { + // No put_device is invented outside the admitted process scope. + // The actual extra C ref remains, retaining device/native source. + let _ = RETAINED.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| { + Some(value.saturating_add(1)) + }); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use alloc::string::ToString; + + #[test] + fn target_labels_remain_exact_and_owned() { + let target = FirmwareTarget::new( + "original-driver".to_string(), + "exact-hardware".to_string(), + "revision-2".to_string(), + Some("board-a".to_string()), + ) + .unwrap(); + let view = target.view(); + assert_eq!(view.driver, "original-driver"); + assert_eq!(view.hardware, "exact-hardware"); + assert_eq!(view.revision, "revision-2"); + assert_eq!(view.board, Some("board-a")); + } + + #[test] + fn target_refuses_empty_and_control_labels() { + for (driver, hardware, revision, board, expected) in [ + ("", "hw", "rev", None, "driver"), + ("drv", "hw\n", "rev", None, "hardware"), + ("drv", "hw", "", None, "revision"), + ("drv", "hw", "rev", Some(""), "board"), + ] { + let result = FirmwareTarget::new( + driver.to_string(), + hardware.to_string(), + revision.to_string(), + board.map(ToString::to_string), + ); + assert!(matches!(result, Err(Error::InvalidTarget(field)) if field == expected)); + } + } +} diff --git a/crates/stela-linux/src/compat/kernel/catalogue.c b/crates/stela-linux/src/compat/kernel/catalogue.c new file mode 100644 index 0000000000..ad6421f6d3 --- /dev/null +++ b/crates/stela-linux/src/compat/kernel/catalogue.c @@ -0,0 +1,494 @@ +// SPDX-License-Identifier: MIT +/* Exact original device membership under one kernel owner. No device name, + * BDF, firmware name or current driver name selects an authority. */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct entry { + struct list_head node; + struct device *device; + struct device *root; + void *authority; + void (*release_authority)(void *); + bool closing; +}; +static const struct stela_linux_owner *kernel_owner; +static bool ready, canonical_environment; +/* Irreversible: 0 = untouched, 1 = legacy activity, 2 = canonical claim. + * Even a finished legacy environment/entry does not qualify global adoption. */ +static unsigned int bootstrap; +static LIST_HEAD(devices); +static u64 quarantined; + +int stela_linux_kernel_claim(const struct stela_linux_owner *owner) +{ + if (!owner) + return -EINVAL; + if (stela_linux_pci_devices_present()) + return -EBUSY; + unsigned int fresh = 0; + if (!__atomic_compare_exchange_n(&bootstrap, &fresh, 2, false, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE)) + return fresh == 2 ? -EALREADY : -EBUSY; + __atomic_store_n(&kernel_owner, owner, __ATOMIC_RELEASE); + return 0; +} +int stela_linux_kernel_environment(const struct stela_linux_owner *owner) +{ + if (!owner) + return -EINVAL; + const struct stela_linux_owner *claimed = __atomic_load_n(&kernel_owner, __ATOMIC_ACQUIRE); + if (claimed) { + if (owner != claimed) + return -EPERM; + bool expected = false; + return __atomic_compare_exchange_n(&canonical_environment, &expected, true, false, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE) ? 0 : -EALREADY; + } + unsigned int fresh = 0; + if (__atomic_compare_exchange_n(&bootstrap, &fresh, 1, false, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE) || fresh == 1) + return 0; + return -EPERM; +} +bool stela_linux_kernel_owner_allowed(const struct stela_linux_owner *owner) +{ + if (__atomic_load_n(&bootstrap, __ATOMIC_ACQUIRE) != 2) + return true; + return owner && owner == __atomic_load_n(&kernel_owner, __ATOMIC_ACQUIRE) && + __atomic_load_n(&ready, __ATOMIC_ACQUIRE); +} +int stela_linux_kernel_prepare_resource(void) +{ + unsigned int fresh = 0; + if (__atomic_compare_exchange_n(&bootstrap, &fresh, 1, false, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE) || fresh == 1) + return 0; + return __atomic_load_n(&ready, __ATOMIC_ACQUIRE) ? 0 : -EPERM; +} +int stela_linux_kernel_entry(const struct stela_linux_owner *owner) +{ + unsigned int fresh = 0; + if (__atomic_compare_exchange_n(&bootstrap, &fresh, 1, false, + __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE) || fresh == 1) + return 0; + return stela_linux_kernel_owner_allowed(owner) ? 0 : -EPERM; +} +int stela_linux_kernel_ready(const struct stela_linux_owner *owner) +{ + if (!owner || __atomic_load_n(&kernel_owner, __ATOMIC_ACQUIRE) != owner || + !__atomic_load_n(&canonical_environment, __ATOMIC_ACQUIRE)) + return -EPERM; + __atomic_store_n(&ready, true, __ATOMIC_RELEASE); + return 0; +} +bool stela_linux_kernel_catalogue_active(void) +{ + return __atomic_load_n(&bootstrap, __ATOMIC_ACQUIRE) == 2; +} +static bool ours(void) +{ + return __atomic_load_n(&ready, __ATOMIC_ACQUIRE) && + stela_linux_owner() == __atomic_load_n(&kernel_owner, __ATOMIC_ACQUIRE); +} +static struct entry *find(const struct device *dev) +{ + struct entry *entry; + list_for_each_entry(entry, &devices, node) + if (entry->device == dev) + return entry; + return NULL; +} +static struct device *retain(struct device *dev) +{ + return dev && kobject_get_unless_zero(&dev->kobj) ? dev : NULL; +} +int stela_linux_device_bind(struct device *dev, void *authority, + void (*release_authority)(void *)) +{ + if (!ours() || !stela_linux_quiescent()) + return -EPERM; + if (!dev || !authority || !release_authority || !dev->kobj.state_initialized) + return -EINVAL; + if (find(dev)) + return -EEXIST; + struct entry *entry = kzalloc_obj(*entry); + if (!entry) + return -ENOMEM; + if (!ours() || !stela_linux_quiescent() || find(dev)) { + kfree(entry); + return -EEXIST; + } + entry->device = dev; + entry->root = dev; + entry->authority = authority; + entry->release_authority = release_authority; + list_add_tail(&entry->node, &devices); + return 0; +} +int stela_linux_device_inherit(struct device *dev) +{ + if (!stela_linux_kernel_catalogue_active()) + return 0; + if (!ours() || !stela_linux_quiescent()) + return -EPERM; + if (find(dev)) + return 0; + struct entry *parent = find(dev->parent); + if (!parent) + return 0; /* ordinary devices acquire no firmware authority */ + struct entry *root = find(parent->root); + if (parent->closing || !root || root->closing) + return -ENODEV; + /* device_add retains the actual parent before this call; root keeps the + * exact native source while a sleepable allocation is attempted. */ + if (!retain(parent->root)) + return -ENODEV; + struct device *root_device = parent->root; + struct entry *entry = kzalloc_obj(*entry); + if (!entry) { + put_device(root_device); + return -ENOMEM; + } + parent = find(dev->parent); + root = find(root_device); + if (!ours() || !stela_linux_quiescent() || find(dev) || + !parent || parent->closing || parent->root != root_device || + !root || root->closing) { + kfree(entry); + put_device(root_device); + return -ENODEV; + } + entry->device = dev; + entry->root = parent->root; + entry->authority = parent->authority; + list_add_tail(&entry->node, &devices); + return 0; +} +bool stela_linux_device_publish_allowed(struct device *dev) +{ + if (!stela_linux_kernel_catalogue_active()) + return true; /* existing non-canonical GPU composition is not migrated */ + if (!ours()) + return false; + struct entry *entry = find(dev); + return entry && !entry->closing; +} +void stela_linux_device_close(struct device *dev) +{ + if (!stela_linux_kernel_catalogue_active()) + return; + if (!ours() || !stela_linux_quiescent()) + stela_linux_fatal("device close outside canonical process owner"); + struct entry *entry = find(dev); + if (entry) + entry->closing = true; +} +int stela_linux_device_acquire(struct device *dev, struct stela_linux_device_lease *lease) +{ + if (!lease) + return -EINVAL; + lease->device = NULL; + lease->authority = NULL; + if (!stela_linux_kernel_catalogue_active() || !ours()) + return -EPERM; + struct entry *entry = find(dev); + struct entry *root = entry ? find(entry->root) : NULL; + if (!entry || entry->closing || !root || root->closing || !retain(dev)) + return -ENODEV; + lease->device = dev; + lease->authority = entry->authority; + return 0; +} +int stela_linux_device_release(struct stela_linux_device_lease *lease) +{ + if (!ours() || !stela_linux_quiescent()) + return -EPERM; + if (!lease || !lease->device) + return -EINVAL; + struct device *dev = lease->device; + lease->device = NULL; + lease->authority = NULL; + put_device(dev); + return 0; +} +bool stela_linux_device_release_begin(struct device *dev, + struct stela_linux_device_retirement *retired) +{ + retired->entry = NULL; + if (!stela_linux_kernel_catalogue_active()) + return true; + if (!ours() || !stela_linux_quiescent()) { + u64 value = __atomic_load_n(&quarantined, __ATOMIC_RELAXED); + while (value != ~(u64)0 && + !__atomic_compare_exchange_n(&quarantined, &value, value + 1, false, + __ATOMIC_RELAXED, __ATOMIC_RELAXED)) + ; + return false; /* retain C storage and every source owner */ + } + struct entry *entry = find(dev); + if (entry) { + list_del(&entry->node); + retired->entry = entry; + } + return true; +} +void stela_linux_device_release_end(struct stela_linux_device_retirement *retired) +{ + struct entry *entry = retired->entry; + if (!entry) + return; + retired->entry = NULL; + struct device *root = entry->root; + bool child = root != entry->device; + void *authority = entry->authority; + void (*release_authority)(void *) = entry->release_authority; + kfree(entry); + /* No lookup/list borrow or access to a released original device follows. */ + if (child) + put_device(root); + else + release_authority(authority); +} +u64 stela_linux_device_quarantined_releases(void) +{ + return __atomic_load_n(&quarantined, __ATOMIC_RELAXED); +} + + +#ifdef STELA_LINUX_CATALOGUE_TEST +#include +#include + +struct peer { + struct device device; + unsigned int released; +}; +struct source { unsigned int *released; }; +static unsigned int source_releases, host_releases, probes; +static struct peer root, child, unknown, global_device; +static void release_peer(struct device *device) +{ + struct peer *peer = container_of(device, struct peer, device); + peer->released++; +} +static struct source *source(void) +{ + struct source *value = calloc(1, sizeof(*value)); + assert(value); + value->released = &source_releases; + return value; +} +static void release_source(void *opaque) +{ + struct source *value = opaque; + (*value->released)++; + free(value); +} +static void initialize(struct peer *peer) +{ + memset(peer, 0, sizeof(*peer)); + peer->device.release = release_peer; + device_initialize(&peer->device); +} +static void child_keeps_original_root(void) +{ + initialize(&root); + initialize(&child); + initialize(&unknown); + assert(!stela_linux_device_bind(&root.device, source(), release_source)); + child.device.parent = &root.device; + assert(!dev_set_name(&child.device, "same-visible-name")); + assert(!device_add(&child.device)); + struct stela_linux_device_lease lease, rejected; + assert(!stela_linux_device_acquire(&child.device, &lease)); + assert(stela_linux_device_acquire(&unknown.device, &rejected) == -ENODEV); + assert(!rejected.device && !rejected.authority); + device_del(&child.device); + assert(stela_linux_device_acquire(&child.device, &rejected) == -ENODEV); + put_device(&root.device); + put_device(&child.device); + assert(!root.released && !child.released && !source_releases); + assert(!stela_linux_device_release(&lease)); + assert(child.released == 1 && root.released == 1 && source_releases == 1); + put_device(&unknown.device); +} +static void closing_root_refuses_live_child(void) +{ + unsigned int before = source_releases; + initialize(&root); + initialize(&child); + assert(!stela_linux_device_bind(&root.device, source(), release_source)); + child.device.parent = &root.device; + assert(!dev_set_name(&child.device, "arbitrary-child")); + assert(!device_add(&child.device)); + stela_linux_device_close(&root.device); + struct stela_linux_device_lease refused; + assert(stela_linux_device_acquire(&child.device, &refused) == -ENODEV); + assert(!refused.device && !refused.authority); + device_del(&child.device); + put_device(&child.device); + put_device(&root.device); + assert(child.released == 1 && root.released == 1 && source_releases == before + 1); +} +static void explicit_global_and_root_close(void) +{ + unsigned int before = source_releases; + initialize(&root); + initialize(&global_device); + struct source *pci = source(), *global = source(); + assert(!stela_linux_device_bind(&root.device, pci, release_source)); + /* Explicit original global device, with no name interpretation. */ + assert(!stela_linux_device_bind(&global_device.device, global, release_source)); + struct stela_linux_device_lease first, second, refused; + assert(!stela_linux_device_acquire(&root.device, &first)); + assert(!stela_linux_device_acquire(&global_device.device, &second)); + assert(first.authority == pci && second.authority == global && first.authority != second.authority); + stela_linux_device_close(&root.device); + assert(stela_linux_device_acquire(&root.device, &refused) == -ENODEV); + assert(!stela_linux_device_release(&first)); + assert(!stela_linux_device_release(&second)); + put_device(&root.device); + put_device(&global_device.device); + assert(source_releases == before + 2); +} +static int read_config(void *context, int where, int size, u32 *value) +{ + (void)context; (void)size; + *value = where == PCI_VENDOR_ID ? 0x1234U : + where == PCI_DEVICE_ID ? 0x5678U : 0; + return PCIBIOS_SUCCESSFUL; +} +static int enroll_peer(void *context, struct device *device) +{ + assert(context == &host_releases); + return stela_linux_device_bind(device, source(), release_source); +} +static void host_release(void *context) +{ + assert(context == &host_releases); + host_releases++; +} +static int probe(struct pci_dev *device, const struct pci_device_id *id) +{ + (void)id; + struct stela_linux_device_lease lease; + assert(!stela_linux_device_acquire(&device->dev, &lease)); + assert(lease.device == &device->dev && lease.authority); + assert(!stela_linux_device_release(&lease)); + probes++; + return 0; +} +static void enrolled_before_probe(void) +{ + unsigned int before = source_releases; + static const struct pci_device_id ids[] = { + { .vendor = 0x1234U, .device = 0x5678U, + .subvendor = (u32)PCI_ANY_ID, .subdevice = (u32)PCI_ANY_ID }, + { } + }; + struct pci_driver driver = {.name = "catalogue-reference-peer", .id_table = ids, .probe = probe}; + assert(!__pci_register_driver(&driver, NULL, "catalogue-reference-peer")); + struct stela_linux_pci_function function = { + .context = &host_releases, .read_config = read_config, + .release_context = host_release, .enroll = enroll_peer, + }; + int error = -1; + struct pci_dev *device = stela_linux_pci_attach(&function, &error); + assert(device && !error && probes == 1); + struct stela_linux_device_lease lease; + assert(!stela_linux_device_acquire(&device->dev, &lease)); + stela_linux_pci_remove_device(device); + assert(!host_releases); + assert(!stela_linux_device_release(&lease)); + assert(host_releases == 1 && source_releases == before + 1); + pci_unregister_driver(&driver); + /* A canonical owner refuses an unenrolled root before probe. */ + function.enroll = NULL; + device = stela_linux_pci_attach(&function, &error); + assert(!device && error == -EPERM && probes == 1 && host_releases == 1); +} +int main(void) +{ + static const struct stela_linux_services services = {}; + static const struct stela_linux_owner owner = {.services = &services}; + static const struct stela_linux_owner other = {.services = &services}; + assert(!stela_linux_kernel_claim(&owner)); + assert(stela_linux_kernel_claim(&other) == -EALREADY); + assert(stela_linux_kernel_ready(&owner) == -EPERM); + assert(stela_linux_kernel_prepare_resource() == -EPERM); + assert(stela_linux_kernel_environment(&other) == -EPERM); + assert(!stela_linux_kernel_environment(&owner)); + assert(stela_linux_kernel_environment(&owner) == -EALREADY); + assert(!stela_linux_kernel_owner_allowed(&owner)); + assert(!stela_linux_kernel_ready(&owner)); + assert(stela_linux_kernel_owner_allowed(&owner)); + assert(!stela_linux_kernel_prepare_resource()); + assert(!stela_linux_kernel_owner_allowed(&other)); + stela_linux_enter(&owner); + child_keeps_original_root(); + closing_root_refuses_live_child(); + explicit_global_and_root_close(); + enrolled_before_probe(); + assert(!stela_linux_device_quarantined_releases()); + stela_linux_exit(); + printf("Linux catalogue: original refs, pre-probe enrollment, exact roots/global authority passed\n"); + return 0; +} +#endif + +#ifdef STELA_LINUX_CATALOGUE_LEGACY_TEST +#include +int main(void) +{ + static const struct stela_linux_services services = {}; + static const struct stela_linux_owner owner = {.services = &services}; + /* Real entry/exit with zero presented devices is still irreversible + * legacy kernel activity, not proof its global resources can be adopted. */ + stela_linux_enter(&owner); + stela_linux_exit(); + assert(!stela_linux_pci_devices_present()); + assert(stela_linux_kernel_claim(&owner) == -EBUSY); + return 0; +} +#endif + +#ifdef STELA_LINUX_CATALOGUE_TASK_TEST +#include +#include +int main(void) +{ + struct stela_linux_task *task = stela_linux_task_allocate(); + assert(task); + stela_linux_task_release(task); + assert(stela_linux_kernel_claim(&stela_linux_bare) == -EBUSY); + return 0; +} +#endif + +#ifdef STELA_LINUX_CATALOGUE_WORKQUEUE_TEST +#include +#include +int main(void) +{ + /* GFP_KERNEL allocation requires the actual entered process owner. */ + stela_linux_enter(&stela_linux_bare); + struct workqueue_struct *wq = alloc_workqueue("legacy-catalogue-peer", 0, 1); + assert(wq); + stela_linux_exit(); + /* The real global queue survives its allocating legacy entry. */ + assert(stela_linux_kernel_claim(&stela_linux_bare) == -EBUSY); + stela_linux_enter(&stela_linux_bare); + destroy_workqueue(wq); + stela_linux_exit(); + assert(stela_linux_kernel_claim(&stela_linux_bare) == -EBUSY); + return 0; +} +#endif diff --git a/crates/stela-linux/src/compat/kernel/device.c b/crates/stela-linux/src/compat/kernel/device.c index 8d94ed190e..789c334289 100644 --- a/crates/stela-linux/src/compat/kernel/device.c +++ b/crates/stela-linux/src/compat/kernel/device.c @@ -12,11 +12,15 @@ #include #include #include +#include #include static void device_release(struct kobject *kobj) { struct device *dev = kobj_to_dev(kobj); + struct stela_linux_device_retirement retired; + if (!stela_linux_device_release_begin(dev, &retired)) + return; if (dev->release) dev->release(dev); @@ -26,6 +30,7 @@ static void device_release(struct kobject *kobj) dev->class->dev_release(dev); else WARN(1, "a device has no release function\n"); + stela_linux_device_release_end(&retired); } static const struct kobj_type device_ktype = { @@ -73,14 +78,22 @@ int device_add(struct device *dev) } if (!dev_name(dev)) return -EINVAL; + struct device *parent = dev->parent; get_device(dev); - get_device(dev->parent); + get_device(parent); + int error = stela_linux_device_inherit(dev); + if (error) { + put_device(dev); + put_device(parent); + return error; + } return 0; } void device_del(struct device *dev) { struct device *parent = dev->parent; + stela_linux_device_close(dev); stela_linux_devres_release(dev); put_device(dev); diff --git a/crates/stela-linux/src/compat/kernel/irq.c b/crates/stela-linux/src/compat/kernel/irq.c index cc275070fa..b4d9cb26c2 100644 --- a/crates/stela-linux/src/compat/kernel/irq.c +++ b/crates/stela-linux/src/compat/kernel/irq.c @@ -6,47 +6,126 @@ * hard-IRQ scope there. Threaded handlers run as work, which may sleep as an * IRQ thread does. The owner routes each line (irq_enable, irq_disable). */ #include +#include #include #include #include #include #include +struct irq_line; struct requested { struct list_head node; struct irqaction action; + struct irq_line *line; struct work_struct thread; + bool closing; + bool thread_active; + bool thread_joined; }; static LIST_HEAD(requests); - -static bool line_requested(unsigned int irq) +/* Like the selected original irq_desc request mutex, this serializes only + * one logical line across real sleeping action-thread joins. Global line + * metadata remains with the one canonical C image for kernel lifetime. */ +struct irq_line { + struct list_head node; + unsigned int irq; + struct mutex request_mutex; + bool oneshot_masked; +}; +static LIST_HEAD(lines); +static DEFINE_MUTEX(lines_mutex); +static struct irq_line *line_owner(unsigned int irq, bool create) { - struct requested *request; - - list_for_each_entry(request, &requests, node) - if (request->action.irq == irq) - return true; - return false; + struct irq_line *line; + mutex_lock(&lines_mutex); + list_for_each_entry(line, &lines, node) + if (line->irq == irq) { + mutex_unlock(&lines_mutex); + return line; + } + line = create ? kzalloc_obj(*line) : NULL; + if (line) { + line->irq = irq; + mutex_init(&line->request_mutex); + list_add_tail(&line->node, &lines); + } + mutex_unlock(&lines_mutex); + return line; } -static int enable_line(unsigned int irq) +static int enable_line(unsigned int irq, bool *unexposed) { const struct stela_linux_owner *owner = stela_linux_owner(); - + *unexposed = false; if (!owner->services->irq_enable) { + /* No native callback was invoked or route published. */ + *unexposed = true; stela_linux_unsupported("interrupt lines"); return -ENOSYS; } - return owner->services->irq_enable(owner->context, irq); + return owner->services->irq_enable(owner->context, irq, unexposed); } static void disable_line(unsigned int irq) { const struct stela_linux_owner *owner = stela_linux_owner(); + if (!owner->services->irq_disable || + owner->services->irq_disable(owner->context, irq)) + stela_linux_fatal("IRQ source mask unavailable; request retained"); +} - if (owner->services->irq_disable) - owner->services->irq_disable(owner->context, irq); +static void retire_line(unsigned int irq) +{ + const struct stela_linux_owner *owner = stela_linux_owner(); + if (!owner->services->irq_retire || + owner->services->irq_retire(owner->context, irq)) + /* Existing no-return fatal/trap boundary: no normal C return, + * request unlink/free or caller dev_id reclamation before the trap. + * Trap disposition itself is not task cancellation/join evidence. */ + stela_linux_fatal("IRQ action retirement unavailable; request retained"); +} + +/* Checked by the exact native service epoch join, after free_irq canceled + * each closing action's real work. A mask/root fence alone never sets this. */ +bool stela_linux_irq_actions_joined(unsigned int irq) +{ + struct requested *request; + bool found = false; + list_for_each_entry(request, &requests, node) + if (request->action.irq == irq) { + found = true; + if (!request->closing || !request->thread_joined) + return false; + } + return found; +} + +/* Every outstanding shared ONESHOT action, including one being canceled, + * keeps the physical line masked. A closing thread ceases to count only after + * its real callback returns or cancel_work_sync actually joins/removes it. */ +static void maybe_rearm(struct irq_line *line) +{ + struct requested *request; + bool live = false; + if (!READ_ONCE(line->oneshot_masked)) + return; + list_for_each_entry(request, &requests, node) { + if (request->action.irq != line->irq) + continue; + if (!READ_ONCE(request->closing)) + live = true; + if ((request->action.flags & IRQF_ONESHOT) && + READ_ONCE(request->thread_active)) + return; + } + if (live) { + bool unexposed = false; + if (enable_line(line->irq, &unexposed)) + stela_linux_fatal("IRQ oneshot rearm unavailable; action retained"); + WRITE_ONCE(line->oneshot_masked, false); + } } /* A threaded action's handler; a oneshot line stays masked until it ends. */ @@ -56,8 +135,9 @@ static void run_thread(struct work_struct *work) struct irqaction *action = &request->action; action->thread_fn((int)action->irq, action->dev_id); + WRITE_ONCE(request->thread_active, false); if (action->flags & IRQF_ONESHOT) - WARN_ON(enable_line(action->irq)); + maybe_rearm(request->line); } /* The primary handler of an action with only a threaded one. */ @@ -68,9 +148,11 @@ static irqreturn_t wake_thread(int irq, void *dev_id) return IRQ_WAKE_THREAD; } -int request_threaded_irq(unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn, +static int request_irq_locked(struct irq_line *line, unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn, unsigned long flags, const char *name, void *dev) { + if (in_interrupt()) + return -EINVAL; if (irq == IRQ_NOTCONNECTED) return -ENOTCONN; if ((flags & IRQF_SHARED) && !dev) @@ -89,6 +171,7 @@ int request_threaded_irq(unsigned int irq, irq_handler_t handler, irq_handler_t struct requested *request = kzalloc_obj(*request); if (!request) return -ENOMEM; + request->line = line; request->action = (struct irqaction){ .handler = handler ? handler : wake_thread, .thread_fn = thread_fn, @@ -98,34 +181,100 @@ int request_threaded_irq(unsigned int irq, irq_handler_t handler, irq_handler_t .name = name, }; INIT_WORK(&request->thread, run_thread); + /* Publish the fully initialized action before enable can deliver a + * synchronous notification or yield to this owner's real service task. */ + list_add_tail(&request->node, &requests); if (first && !(flags & IRQF_NO_AUTOEN)) { - int error = enable_line(irq); + bool unexposed = false; + int error = enable_line(irq, &unexposed); if (error) { + if (!unexposed) + stela_linux_fatal("IRQ enable uncertain; published request retained"); + /* Only the exact unused native owners/service epoch proof permits + * returning an error that lets the caller reclaim dev_id. */ + list_del(&request->node); kfree(request); return error; } } - list_add_tail(&request->node, &requests); return 0; } +int request_threaded_irq(unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn, + unsigned long flags, const char *name, void *dev) +{ + if (in_interrupt()) + return -EINVAL; + struct irq_line *line = line_owner(irq, true); + if (!line) + return -ENOMEM; + mutex_lock(&line->request_mutex); + int result = request_irq_locked(line, irq, handler, thread_fn, flags, name, dev); + mutex_unlock(&line->request_mutex); + return result; +} + +static const void *free_irq_locked(unsigned int irq, void *dev_id) +{ + struct requested *request; + /* Primary callbacks are atomic, and joining one's own IRQ work would + * deadlock. Never turn either invalid caller into a completed free. */ + if (in_interrupt()) + stela_linux_fatal("free_irq in interrupt context"); + list_for_each_entry(request, &requests, node) { + if (request->action.irq != irq || request->action.dev_id != dev_id) + continue; + if (current_work() == &request->thread) + stela_linux_fatal("free_irq from its own IRQ thread"); + const char *name = request->action.name; + bool last = true; + struct requested *other; + list_for_each_entry(other, &requests, node) + if (other != request && other->action.irq == irq) + last = false; + /* Canonical single-owner service CPU serializes primary callbacks. + * Keep the node/dev_id through real thread and native epoch joins. */ + WRITE_ONCE(request->closing, true); + if (last) + disable_line(irq); + cancel_work_sync(&request->thread); + WRITE_ONCE(request->thread_active, false); + WRITE_ONCE(request->thread_joined, true); + if (last) + retire_line(irq); + struct irq_line *line = request->line; + list_del(&request->node); + kfree(request); + if (last) + WRITE_ONCE(line->oneshot_masked, false); + else + maybe_rearm(line); + return name; + } + WARN(1, "Trying to free already-free IRQ %u\n", irq); + return NULL; +} + const void *free_irq(unsigned int irq, void *dev_id) { struct requested *request; - - list_for_each_entry(request, &requests, node) { - if (request->action.irq != irq || request->action.dev_id != dev_id) - continue; - const char *name = request->action.name; - list_del(&request->node); - if (!line_requested(irq)) - disable_line(irq); - cancel_work_sync(&request->thread); - kfree(request); - return name; + if (in_interrupt()) + stela_linux_fatal("free_irq in interrupt context"); + /* Check self-join before acquiring a mutex another free_irq may hold + * while cancel_work_sync waits for this very IRQ thread. */ + list_for_each_entry(request, &requests, node) + if (request->action.irq == irq && request->action.dev_id == dev_id && + current_work() == &request->thread) + stela_linux_fatal("free_irq from its own IRQ thread"); + struct irq_line *line = line_owner(irq, false); + if (!line) { + WARN(1, "Trying to free already-free IRQ %u\n", irq); + return NULL; } - WARN(1, "Trying to free already-free IRQ %u\n", irq); - return NULL; + mutex_lock(&line->request_mutex); + const void *name = free_irq_locked(irq, dev_id); + mutex_unlock(&line->request_mutex); + return name; } void stela_linux_irq_run(unsigned int irq) @@ -136,13 +285,17 @@ void stela_linux_irq_run(unsigned int irq) stela_linux_atomic_callback_begin(&scope); list_for_each_entry(request, &requests, node) { struct irqaction *action = &request->action; - if (action->irq != irq || + if (action->irq != irq || READ_ONCE(request->closing) || + ((action->flags & IRQF_ONESHOT) && READ_ONCE(request->thread_active)) || !(action->handler((int)irq, action->dev_id) & IRQ_WAKE_THREAD)) continue; if (WARN_ON_ONCE(!action->thread_fn)) continue; - if (action->flags & IRQF_ONESHOT) + if (action->flags & IRQF_ONESHOT) { disable_line(irq); + WRITE_ONCE(request->line->oneshot_masked, true); + } + WRITE_ONCE(request->thread_active, true); queue_work(system_highpri_wq, &request->thread); } stela_linux_atomic_callback_end(&scope); diff --git a/crates/stela-linux/src/compat/kernel/linux.c b/crates/stela-linux/src/compat/kernel/linux.c index e77b4334d4..410fee7c94 100644 --- a/crates/stela-linux/src/compat/kernel/linux.c +++ b/crates/stela-linux/src/compat/kernel/linux.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT /* The execution Stela gives Linux code: one owner at a time, on one context * that nothing preempts or interrupts. */ +#include #include #include #include @@ -81,7 +82,7 @@ bool stela_linux_lease_resume(const struct stela_linux_lease *lease) bool stela_linux_try_enter(const struct stela_linux_owner *next) { - if (!next || !next->services) + if (!next || !next->services || stela_linux_kernel_entry(next)) __builtin_trap(); bool expected = false; if (!__atomic_compare_exchange_n(&running, &expected, true, false, diff --git a/crates/stela-linux/src/compat/kernel/page.c b/crates/stela-linux/src/compat/kernel/page.c index 4e6ad82959..bcef27cb65 100644 --- a/crates/stela-linux/src/compat/kernel/page.c +++ b/crates/stela-linux/src/compat/kernel/page.c @@ -17,6 +17,7 @@ #include #include #include +#include #define NO_INDEX SIZE_MAX @@ -140,6 +141,14 @@ static void require_catalog(void) __builtin_trap(); } +int stela_linux_page_owner_context(const struct stela_linux_owner *expected) +{ + struct stela_linux_lease lease; + stela_linux_lease_snapshot(&lease); + return expected && lease.owner == expected && !in_callback && + stela_linux_quiescent() ? 0 : -EPERM; +} + bool stela_linux_page_request_basic(u32 gfp) { /* x86-64 has no high memory, Stela no cpusets or NUMA nodes, and how hard @@ -455,6 +464,49 @@ void stela_linux_page_dma_unpin(void *pin) /* Final provider release still happens only at checked quiescence. */ } +/* This entry is for the actual registered Rust provider Context. Neither a + * PFN nor a caller's generation/context labels manufacture an allocation. */ +int stela_linux_page_mapping_pin(u64 generation, const void *context, + const struct stela_linux_owner *owner, u64 physical, + struct stela_linux_mapping_page *out) +{ + if (!out) return -EINVAL; + *out=(struct stela_linux_mapping_page){}; + int error=stela_linux_page_owner_context(owner); + if (error) return error; + if (!catalog.pages || generation!=catalog.generation || context!=catalog.context || + (physical & (PAGE_SIZE-1))) return -EINVAL; + size_t index=physical_slot(physical); + if (index==NO_INDEX || !catalog.state[index].live) return -ENOENT; + const struct registered_extent *extent=index_extent(index); + if (extent->kind!=STELA_LINUX_PAGE_ORDINARY) return -EOPNOTSUPP; + struct allocation_record *record=catalog.allocations+catalog.state[index].allocation; + if (!record->pin || !record->live || record->external_nonce) return -EOPNOTSUPP; + if (record->dma_refs==SIZE_MAX) return -EOVERFLOW; + record->dma_refs++; + *out=(struct stela_linux_mapping_page){.record=record,.provider_pin=record->pin, + .cpu_page=extent->cpu_base+((index-extent->first)<=bytes || (address-base)%sizeof(*catalog.allocations)) + return -EINVAL; + struct allocation_record *record=token; + if (!record->pin || !record->dma_refs || record->external_nonce) return -EINVAL; + record->dma_refs--; + /* No callback/allocation/recycle here: final provider release stays deferred + * to pages_finish after the Rust clone has left its explicit release scope. */ + return 0; +} + struct page *pfn_to_page(unsigned long pfn) { if (pfn > (U64_MAX >> PAGE_SHIFT)) @@ -2160,6 +2212,54 @@ static void dma_pins_retain_original_allocations(void) stela_linux_pages_finish(); } +static void mapping_pins_retain_exact_original_allocations( + const struct stela_linux_owner *owner) +{ + /* Match the actual entered owner so invalid generations/contexts reach + * their own validation instead of an earlier foreign-owner refusal. */ + assert(stela_linux_owner()==owner); + struct stela_linux_mapping_page a,b,refused; + struct page *page=alloc_pages(GFP_KERNEL,2); + assert(page); + u64 physical=page_to_phys(page), generation=catalog.generation; + static const struct stela_linux_services no_services={}; + static const struct stela_linux_owner foreign={.services=&no_services}; + assert(stela_linux_page_mapping_pin(generation+1,&fixture,owner,physical,&refused)==-EINVAL); + assert(!refused.record && !refused.provider_pin && !refused.cpu_page); + assert(stela_linux_page_mapping_pin(generation,&foreign,owner,physical,&refused)==-EINVAL); + assert(stela_linux_page_mapping_pin(generation,&fixture,&foreign,physical,&refused)==-EPERM); + assert(stela_linux_page_mapping_pin(generation,&fixture,owner,physical+1,&refused)==-EINVAL); + preempt_disable(); + assert(stela_linux_page_mapping_pin(generation,&fixture,owner,physical,&refused)==-EPERM); + preempt_enable(); + assert(!stela_linux_page_mapping_pin(generation,&fixture,owner,physical,&a)); + assert(!stela_linux_page_mapping_pin(generation,&fixture,owner,physical+3*PAGE_SIZE,&b)); + struct allocation_record *record=a.record; + assert(b.record==a.record && a.provider_pin==record->pin && b.provider_pin==record->pin); + assert(a.cpu_page==page_address(page) && b.cpu_page==(u8 *)page_address(page)+3*PAGE_SIZE); + record->dma_refs=SIZE_MAX; + assert(stela_linux_page_mapping_pin(generation,&fixture,owner,physical,&refused)==-EOVERFLOW); + assert(!refused.record && !refused.provider_pin && !refused.cpu_page); + record->dma_refs=2; + unsigned int before=fixture.releases; + __free_pages(page,2); + assert(stela_linux_page_mapping_pin(generation,&fixture,owner,physical,&refused)==-ENOENT); + assert(stela_linux_page_catalog_unregister(generation)==-EBUSY); + assert(fixture.releases==before && record->dma_refs==2 && record->pin); + assert(stela_linux_page_mapping_unpin(generation+1,&fixture,owner,a.record)==-EINVAL); + assert(stela_linux_page_mapping_unpin(generation,&foreign,owner,a.record)==-EINVAL); + assert(stela_linux_page_mapping_unpin(generation,&fixture,&foreign,a.record)==-EPERM); + assert(record->dma_refs==2); + assert(!stela_linux_page_mapping_unpin(generation,&fixture,owner,a.record)); + stela_linux_pages_finish(); + assert(record->dma_refs==1 && fixture.releases==before); + assert(!stela_linux_page_mapping_unpin(generation,&fixture,owner,b.record)); + assert(stela_linux_page_mapping_unpin(generation,&fixture,owner,b.record)==-EINVAL); + assert(fixture.releases==before); /* No inline provider release. */ + stela_linux_pages_finish(); + assert(fixture.releases==before+1); +} + int main(void) { reclaimable_policy(); @@ -2208,6 +2308,7 @@ int main(void) sg_chained_allocation(); sg_page_segments(); dma_pins_retain_original_allocations(); + mapping_pins_retain_exact_original_allocations(&owner); assert(!catalog.live_pages); assert(!stela_linux_page_catalog_unregister(1)); assert(stela_linux_page_catalog_register(&reservation, &test_ops, &fixture) == -EINVAL); diff --git a/crates/stela-linux/src/compat/kernel/pci.c b/crates/stela-linux/src/compat/kernel/pci.c index 4d9c811920..f232d893b8 100644 --- a/crates/stela-linux/src/compat/kernel/pci.c +++ b/crates/stela-linux/src/compat/kernel/pci.c @@ -10,6 +10,7 @@ #include #include #include +#include #include /* An ID field matches its value or, as PCI_ANY_ID, any value. */ @@ -161,15 +162,22 @@ static void unbind(struct pci_dev *dev) dev->driver = NULL; } -void stela_linux_pci_add_device(struct pci_dev *dev) +bool stela_linux_pci_devices_present(void) +{ + return !list_empty(&devices); +} + +int stela_linux_pci_publish_device(struct pci_dev *dev) { struct registered_driver *registered; + if (!stela_linux_device_publish_allowed(&dev->dev)) + return -EPERM; - device_initialize(&dev->dev); dev->dev.bus = &pci_bus_type; list_add_tail(&dev->bus_list, &devices); list_for_each_entry(registered, &drivers, node) bind(registered->driver, dev); + return 0; } bool stela_linux_pci_bound(const struct pci_dev *device) @@ -179,6 +187,7 @@ bool stela_linux_pci_bound(const struct pci_dev *device) void stela_linux_pci_remove_device(struct pci_dev *dev) { + stela_linux_device_close(&dev->dev); unbind(dev); list_del(&dev->bus_list); put_device(&dev->dev); @@ -519,7 +528,8 @@ int main(void) pci_disable_device(&dev); assert(config[PCI_COMMAND] == PCI_COMMAND_MEMORY && !dev.is_busmaster); - stela_linux_pci_add_device(&dev); + device_initialize(&dev.dev); + assert(!stela_linux_pci_publish_device(&dev)); assert(pci_get_domain_bus_and_slot(0, 3, PCI_DEVFN(1, 0)) == &dev); pci_dev_put(&dev); assert(!pci_get_domain_bus_and_slot(0, 4, PCI_DEVFN(1, 0))); diff --git a/crates/stela-linux/src/compat/kernel/pci_host.c b/crates/stela-linux/src/compat/kernel/pci_host.c index cafe746046..d2c40056d5 100644 --- a/crates/stela-linux/src/compat/kernel/pci_host.c +++ b/crates/stela-linux/src/compat/kernel/pci_host.c @@ -181,10 +181,12 @@ static void release(struct device *dev) kfree(host); } -struct pci_dev *stela_linux_pci_attach(const struct stela_linux_pci_function *function) +struct pci_dev *stela_linux_pci_attach(const struct stela_linux_pci_function *function, int *status) { + int error = -ENOMEM; struct host_function *host = kzalloc_obj(*host); - + if (status) + *status = error; if (!host) return NULL; host->function = *function; @@ -223,9 +225,24 @@ struct pci_dev *stela_linux_pci_attach(const struct stela_linux_pci_function *fu dev->dev.coherent_dma_mask = DMA_BIT_MASK(32); dev->dev.release = release; set_dma_ops(&dev->dev, &mapping_ops); - stela_linux_pci_add_device(dev); - dev_set_name(&dev->dev, "%04x:%02x:%02x.%d", 0, function->bus, PCI_SLOT(function->devfn), - PCI_FUNC(function->devfn)); + device_initialize(&dev->dev); + error = dev_set_name(&dev->dev, "%04x:%02x:%02x.%d", 0, function->bus, + PCI_SLOT(function->devfn), PCI_FUNC(function->devfn)); + if (!error && function->enroll) + error = function->enroll(function->context, &dev->dev); + if (!error) + error = stela_linux_pci_publish_device(dev); + if (error) { + /* Refusal never takes the caller's host-context ownership. Any exact + * source record already enrolled retires through the real final put. */ + host->function.release_context = NULL; + put_device(&dev->dev); + if (status) + *status = error; + return NULL; + } + if (status) + *status = 0; return dev; } @@ -314,7 +331,7 @@ int main(void) .release_context = test_release_context, }; function.regions[0] = (struct stela_linux_pci_region){BASE, 0x1000000, IORESOURCE_MEM}; - struct pci_dev *dev = stela_linux_pci_attach(&function); + struct pci_dev *dev = stela_linux_pci_attach(&function, NULL); assert(dev && !stela_linux_pci_bound(dev)); @@ -384,13 +401,13 @@ int main(void) assert(context_releases == 1); /* A legacy caller can still retain ownership without a release callback. */ function.release_context = NULL; - dev = stela_linux_pci_attach(&function); + dev = stela_linux_pci_attach(&function, NULL); assert(dev); stela_linux_pci_remove_device(dev); assert(context_releases == 1); /* An atomic final put cannot destroy the host or callback context. */ function.release_context = test_release_context; - dev = stela_linux_pci_attach(&function); + dev = stela_linux_pci_attach(&function, NULL); assert(dev); u64 before = stela_linux_pci_quarantined_functions(); local_bh_disable(); @@ -399,7 +416,7 @@ int main(void) assert(context_releases == 1 && stela_linux_pci_quarantined_functions() == before + 1); /* Quiescence under another platform does not authorize destruction of * this function's callback roots through that platform's services. */ - dev = stela_linux_pci_attach(&function); + dev = stela_linux_pci_attach(&function, NULL); assert(dev && pci_dev_get(dev) == dev); stela_linux_pci_remove_device(dev); const struct stela_linux_services other_services = {0}; diff --git a/crates/stela-linux/src/compat/kernel/registry.c b/crates/stela-linux/src/compat/kernel/registry.c index c2cda4d783..6d7235f0e2 100644 --- a/crates/stela-linux/src/compat/kernel/registry.c +++ b/crates/stela-linux/src/compat/kernel/registry.c @@ -601,6 +601,32 @@ int stela_linux_registry_status(const struct stela_linux_registry *r, size_t ind *out = r->status[index]; return 0; } +/* Declared source dependency, not a label/target-address search. The expected + * actual image pins the one canonical registry epoch; foreign metadata cannot + * nominate a different initializer that happened to return success. */ +int stela_linux_registry_require_success(const struct stela_linux_registry *r, + const struct stela_linux_registry_image *expected, + const struct stela_linux_init_record *required) +{ + struct call_guard guard; + if (!r || r != active || !expected || r->image != expected || !required) + return -EINVAL; + int error = guard_begin(&guard); + if (error) return error; + if (r->quarantined || r->retired || r->parameter_error) return -EPROTO; + for (size_t i = 0; i < r->image->init_count; ++i) { + if (r->image->inits[i] != required) continue; + const struct stela_linux_registration_status *status = &r->status[i]; + if (status->state == STELA_LINUX_RECORD_NOT_RUN) return -EAGAIN; + if (status->state == STELA_LINUX_RECORD_RUNNING) return -EINPROGRESS; + if (status->invocations != 1) return -EPROTO; + if (status->state == STELA_LINUX_RECORD_ZERO && !status->returned) return 0; + if (status->state == STELA_LINUX_RECORD_NEGATIVE && status->returned < 0) + return status->returned; + return -EPROTO; + } + return -ENOENT; +} int stela_linux_registry_parse_result(const struct stela_linux_registry *r, unsigned int pass, char **out) { @@ -1096,11 +1122,60 @@ static void positive_parameter_case(void) assert(stela_linux_registry_run_stage(test_registry,0,NULL)==-EINVAL && !event_count); stela_linux_exit(); } +static struct registry_fixture *dependency_fixture; +static const struct stela_linux_init_record *dependency_record; +static int dependency_result; +static unsigned int dependency_hooks, dependency_borrows; +static int dependency_prerequisite(void) +{ + assert(stela_linux_registry_require_success(test_registry, &dependency_fixture->image, + dependency_record) == -EINPROGRESS); + return dependency_result; +} +static int dependency_hook(void) +{ + dependency_hooks++; + int result = stela_linux_registry_require_success(test_registry, + &dependency_fixture->image, + dependency_record); + if (result) return result; /* Never enter the borrowed accessor on failure. */ + dependency_borrows++; + return 0; +} +static void dependency_case(void) +{ + stela_linux_enter(&stela_linux_bare); + struct registry_fixture f; fixture_init(&f); + fixture_call(&f,0,STELA_LINUX_REG_INIT,5,0,dependency_prerequisite); + fixture_call(&f,1,STELA_LINUX_REG_INIT,5,STELA_LINUX_REG_SYNC,dependency_hook); + dependency_fixture=&f; dependency_record=f.inits[0]; + begin_fixture(&f,""); option_phases(); + assert(stela_linux_registry_require_success(test_registry,&f.image,dependency_record)==-EAGAIN); + struct stela_linux_registry_image foreign_image=f.image; + struct stela_linux_init_record foreign_record=*dependency_record; + assert(stela_linux_registry_require_success(test_registry,&foreign_image,dependency_record)==-EINVAL); + assert(stela_linux_registry_require_success(test_registry,&f.image,&foreign_record)==-ENOENT); + int expected=dependency_result>0 ? -EPROTO : dependency_result; + for(unsigned stage=0;stage int main(void) { for(setup_differential_index=0;setup_differential_indexdrain(call->context); stela_linux_atomic_process_leaf_end(&leaf); - for (int irq; (irq = call->next_irq(call->context)) >= 0;) + for (int irq; (irq = call->next_irq(call->context)) >= 0;) { stela_linux_irq_run((unsigned int)irq); + call->complete_irq(call->context); + } call->finish(call->context, stela_linux_service_run()); } stela_linux_exit(); diff --git a/crates/stela-linux/src/compat/kernel/task.c b/crates/stela-linux/src/compat/kernel/task.c index 0f0144ef19..216fb43edd 100644 --- a/crates/stela-linux/src/compat/kernel/task.c +++ b/crates/stela-linux/src/compat/kernel/task.c @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MIT /* Original Linux task metadata bound to actual retained Runtime continuations. * This implements identity/lease transitions, not a substitute Linux scheduler. */ +#include #include #include #include @@ -271,6 +272,8 @@ static struct signal_struct no_process; struct stela_linux_task *stela_linux_task_allocate(void) { + if (stela_linux_kernel_prepare_resource()) + return NULL; struct stela_linux_task *task = stela_linux_heap_alloc(sizeof(*task), __alignof__(*task)); if (!task) return NULL; diff --git a/crates/stela-linux/src/compat/kernel/workqueue.c b/crates/stela-linux/src/compat/kernel/workqueue.c index 4ccb8ab587..1edaa8a3a0 100644 --- a/crates/stela-linux/src/compat/kernel/workqueue.c +++ b/crates/stela-linux/src/compat/kernel/workqueue.c @@ -12,6 +12,7 @@ * queued before it. Linux code runs in one context at a time, which * serializes everything here. BH workqueues, which run work in softirq * context, are not provided. */ +#include #include #include #include @@ -206,6 +207,8 @@ static void enqueue(struct workqueue_struct *wq, struct work_struct *work) bool queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work) { + /* Validate the actual entered owner before any pending/list mutation. */ + (void)stela_linux_owner(); (void)cpu; if (test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) return false; @@ -352,6 +355,8 @@ void drain_workqueue(struct workqueue_struct *wq) struct workqueue_struct *alloc_workqueue_noprof(const char *fmt, unsigned int flags, int max_active, ...) { + if (stela_linux_kernel_prepare_resource()) + return NULL; if (flags & WQ_BH) { stela_linux_unsupported("BH workqueues"); return NULL; diff --git a/crates/stela-linux/src/compat/stela/catalogue.h b/crates/stela-linux/src/compat/stela/catalogue.h new file mode 100644 index 0000000000..028f8859c3 --- /dev/null +++ b/crates/stela-linux/src/compat/stela/catalogue.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: MIT */ +#ifndef STELA_LINUX_CATALOGUE_H +#define STELA_LINUX_CATALOGUE_H +#include +struct device; +struct stela_linux_owner; +/* One mount-lifetime kernel owner. A failed claim is never reset. */ +int stela_linux_kernel_claim(const struct stela_linux_owner *owner); +int stela_linux_kernel_ready(const struct stela_linux_owner *owner); +/* A refused partial Environment is not reusable; no global reset is proven. */ +int stela_linux_kernel_environment(const struct stela_linux_owner *owner); +bool stela_linux_kernel_owner_allowed(const struct stela_linux_owner *owner); +int stela_linux_kernel_entry(const struct stela_linux_owner *owner); +/* Pre-entry task/WQ allocation also forbids adopting a legacy kernel later. */ +int stela_linux_kernel_prepare_resource(void); +bool stela_linux_kernel_catalogue_active(void); +/* Root binding takes authority only on success. It retains no self-device ref. + * Caller owns the initialized original device through publication/final put. */ +int stela_linux_device_bind(struct device *dev, void *authority, + void (*release_authority)(void *)); +int stela_linux_device_inherit(struct device *dev); +bool stela_linux_device_publish_allowed(struct device *dev); +void stela_linux_device_close(struct device *dev); +/* These are actual get_device/kobject references, not a context-lifetime grant. + * A lease keeps an enrolled child's actual original root through final put. */ +struct stela_linux_device_lease { struct device *device; const void *authority; }; +int stela_linux_device_acquire(struct device *dev, struct stela_linux_device_lease *lease); +int stela_linux_device_release(struct stela_linux_device_lease *lease); +/* Remove lookup membership before foreign device release; finish afterwards + * without touching the device, which the foreign callback may have freed. */ +struct stela_linux_device_retirement { void *entry; }; +bool stela_linux_device_release_begin(struct device *dev, + struct stela_linux_device_retirement *retired); +void stela_linux_device_release_end(struct stela_linux_device_retirement *retired); +u64 stela_linux_device_quarantined_releases(void); +#endif diff --git a/crates/stela-linux/src/compat/stela/irq.h b/crates/stela-linux/src/compat/stela/irq.h index 2acd87fb77..c79d0881dd 100644 --- a/crates/stela-linux/src/compat/stela/irq.h +++ b/crates/stela-linux/src/compat/stela/irq.h @@ -1,7 +1,9 @@ /* SPDX-License-Identifier: MIT */ #ifndef STELA_IRQ_H #define STELA_IRQ_H +#include /* Run the handlers of a raised line, on the owner's service task. */ void stela_linux_irq_run(unsigned int irq); +bool stela_linux_irq_actions_joined(unsigned int irq); #endif diff --git a/crates/stela-linux/src/compat/stela/linux.h b/crates/stela-linux/src/compat/stela/linux.h index 201c9fd403..24d0da9f31 100644 --- a/crates/stela-linux/src/compat/stela/linux.h +++ b/crates/stela-linux/src/compat/stela/linux.h @@ -60,11 +60,15 @@ struct stela_linux_services { /* Map count write-back pages contiguously, or return NULL. */ void *(*map_pages)(void *context, const u64 *physical, size_t count); void (*unmap_pages)(void *context, void *address, size_t count); - /* Route a line to the owner's service, which calls stela_linux_irq_run - * when it fires, or return a negative errno; disabling masks it and - * returns only once no new firing can reach the service. */ - int (*irq_enable)(void *context, unsigned int irq); - void (*irq_disable)(void *context, unsigned int irq); + /* Action is already linked before enable. Initialize *unexposed=false; + * set true only with actual no-publication plus exact owner/event cleanup + * proof. An errno/disabled bit never implies that classification. */ + int (*irq_enable)(void *context, unsigned int irq, bool *unexposed); + /* Reversible mask only; queued old delivery remains owned. */ + int (*irq_disable)(void *context, unsigned int irq); + /* Exact action/root/CPU/service join after C action-thread joining. + * A negative result must not return through free_irq/reclaim dev_id. */ + int (*irq_retire)(void *context, unsigned int irq); /* Copy between the running client's memory and Linux's, returning the * bytes left uncopied at a fault. */ unsigned long (*copy_from_user)(void *context, void *to, const void *from, @@ -85,7 +89,7 @@ struct stela_linux_owner { /* Private x86-64 C ABI. All producers and consumers rebuild from this header; * Rust currently passes owners opaquely rather than mirroring this table. */ -_Static_assert(sizeof(struct stela_linux_services) == 152, "Linux services ABI"); +_Static_assert(sizeof(struct stela_linux_services) == 160, "Linux services ABI"); _Static_assert(__builtin_offsetof(struct stela_linux_services, random_bytes) == 48, "Linux random callback ABI"); _Static_assert(sizeof(struct stela_linux_owner) == 16, "Linux owner ABI"); diff --git a/crates/stela-linux/src/compat/stela/page.h b/crates/stela-linux/src/compat/stela/page.h index f2b9b67e64..3aa52adbc9 100644 --- a/crates/stela-linux/src/compat/stela/page.h +++ b/crates/stela-linux/src/compat/stela/page.h @@ -2,6 +2,9 @@ #ifndef STELA_PAGE_H #define STELA_PAGE_H #include +struct stela_linux_owner; +/* Pure current-owner/quiescence check; no entry, callback or ownership change. */ +int stela_linux_page_owner_context(const struct stela_linux_owner *expected); /* One retained, permanently mapped, contiguous RAM reservation. A generation * is nonzero and strictly newer than every successfully registered catalog. @@ -142,6 +145,14 @@ void stela_linux_pages_finish(void); * requires exactly one unpin. Unpin does not invoke the provider or allocate. */ void *stela_linux_page_dma_pin(u64 physical); void stela_linux_page_dma_unpin(void *pin); +/* Opaque affine allocation ref plus its original provider pin and exact CPU + * page. The Rust producer binds the original Context/generation and clones + * that Pin's actual PinnedPages before any caller can expose a mapping. */ +struct stela_linux_mapping_page { void *record, *provider_pin, *cpu_page; }; +int stela_linux_page_mapping_pin(u64 generation, const void *context, + const struct stela_linux_owner *owner, u64 physical, struct stela_linux_mapping_page *); +int stela_linux_page_mapping_unpin(u64 generation, const void *context, + const struct stela_linux_owner *owner, void *record); /* Explicit bounded service diagnostic, not GPU or native-IRQ qualification. * Requires quiescent entry; owns and retires only its temporary allocations. */ int stela_linux_page_catalog_verify(u64 generation); diff --git a/crates/stela-linux/src/compat/stela/pci.h b/crates/stela-linux/src/compat/stela/pci.h index 3eb3948a0b..03822e022f 100644 --- a/crates/stela-linux/src/compat/stela/pci.h +++ b/crates/stela-linux/src/compat/stela/pci.h @@ -3,9 +3,10 @@ #define STELA_PCI_H #include -/* A function its owner built, on a bus with the owner's pci_ops. Adding - * initializes its device; removing drops that reference. */ -void stela_linux_pci_add_device(struct pci_dev *dev); +/* A function its owner built, on a bus with the owner's pci_ops. Publish an + * already initialized/enrolled device; removal drops its registration ref. */ +int stela_linux_pci_publish_device(struct pci_dev *dev); +bool stela_linux_pci_devices_present(void); bool stela_linux_pci_bound(const struct pci_dev *device); void stela_linux_pci_remove_device(struct pci_dev *dev); @@ -39,18 +40,23 @@ struct stela_linux_pci_function { * Nonquiescent or other-owner final release quarantines host/context; * no destructor is invoked from atomic or private RCU callback context. */ void (*release_context)(void *context); + /* Original initialized device enrollment; called before any driver probe. */ + int (*enroll)(void *context, struct device *device); }; -_Static_assert(sizeof(struct stela_linux_pci_function) == 232, "Linux PCI function ABI"); +_Static_assert(sizeof(struct stela_linux_pci_function) == 240, "Linux PCI function ABI"); _Static_assert(__builtin_offsetof(struct stela_linux_pci_function, release_context) == 224, "Linux PCI context release ABI"); -/* Present function to Linux, which binds any driver matching it; NULL when out - * of memory, without taking context ownership. Removal unregisters the device +_Static_assert(__builtin_offsetof(struct stela_linux_pci_function, enroll) == 232, + "Linux PCI enrollment ABI"); + +/* Present function to Linux, which binds any driver matching it. NULL reports + * a negative errno (if error is non-NULL), without taking context ownership. Removal unregisters the device * and drops the registration reference; other references keep callbacks live. * The attach owner/platform and callback code must outlive every escaped * device reference or quarantined final release. */ -struct pci_dev *stela_linux_pci_attach(const struct stela_linux_pci_function *function); +struct pci_dev *stela_linux_pci_attach(const struct stela_linux_pci_function *function, int *error); /* Cumulative final releases quarantined outside the original process owner. * Atomic observation only; no reset or deferred reclamation is implied. */ u64 stela_linux_pci_quarantined_functions(void); diff --git a/crates/stela-linux/src/compat/stela/registry.h b/crates/stela-linux/src/compat/stela/registry.h index a191525b10..520e21f697 100644 --- a/crates/stela-linux/src/compat/stela/registry.h +++ b/crates/stela-linux/src/compat/stela/registry.h @@ -144,6 +144,13 @@ int stela_linux_registry_initial_parameters(struct stela_linux_registry *, int stela_linux_registry_run_stage(struct stela_linux_registry *, unsigned int, struct stela_linux_registry_report *); /* Stable status index: init, exit, parameter, info, device, setup arrays. */ +/* Source-owned declared prerequisite by exact actual image/record identity. + * Reaching a later stage is not success: stage execution continues on errors. + * No initializer/getter callback, lookup by label or implicit readiness. + * This is historical success only: caller separately keeps exact source + * context/module lifetime and declared init phase; it is no device/I/O grant. */ +int stela_linux_registry_require_success(const struct stela_linux_registry *, + const struct stela_linux_registry_image *, const struct stela_linux_init_record *); int stela_linux_registry_status(const struct stela_linux_registry *, size_t, struct stela_linux_registration_status *); /* Original NULL/tail/ERR_PTR result from an already-attempted pass0..9. diff --git a/crates/stela-linux/src/compat/stela/service.h b/crates/stela-linux/src/compat/stela/service.h index 134af035a4..33cc008af4 100644 --- a/crates/stela-linux/src/compat/stela/service.h +++ b/crates/stela-linux/src/compat/stela/service.h @@ -17,6 +17,8 @@ struct stela_linux_service_call { bool (*begin)(void *context); /* The next line raised since the batch began, or a negative value. */ int (*next_irq)(void *context); + /* Complete the exact original primary service body after it returned. */ + void (*complete_irq)(void *context); /* Nonblocking process leaves, on this real service task in the owner. */ void (*drain)(void *context); /* Finish it, with the clock reading to run again at (as above). */ @@ -24,7 +26,7 @@ struct stela_linux_service_call { bool (*done)(void *context); }; -_Static_assert(sizeof(struct stela_linux_service_call) == 56, "Linux service call ABI"); +_Static_assert(sizeof(struct stela_linux_service_call) == 64, "Linux service call ABI"); /* The body of a service task, entered in call's owner until call is done. */ void stela_linux_service_loop(const struct stela_linux_service_call *call); diff --git a/crates/stela-linux/src/compat/stela/service_test.c b/crates/stela-linux/src/compat/stela/service_test.c index a631a9dfd0..b5426c32be 100644 --- a/crates/stela-linux/src/compat/stela/service_test.c +++ b/crates/stela-linux/src/compat/stela/service_test.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #define LINE 7 @@ -15,6 +16,7 @@ struct service_test { const struct stela_linux_owner *owner; void *context; void (*raise)(void *context, unsigned int line); + bool (*masked)(void *context, unsigned int line); }; void stela_linux_service_test_leaf_context(void); @@ -33,7 +35,7 @@ static unsigned int handled; static void finish_work(struct work_struct *item) { - assert(item == &work && handled == 1); + assert(item == &work && handled >= 1 && handled <= 2); complete(&done); } @@ -45,6 +47,60 @@ static irqreturn_t handle(int irq, void *data) return IRQ_HANDLED; } +static DECLARE_COMPLETION(shared_a_done); +static DECLARE_COMPLETION(shared_b_entered); +static DECLARE_COMPLETION(shared_b_gate); +static DECLARE_COMPLETION(shared_b_done); +static int shared_a, shared_b; +static bool wake_b = true; +static unsigned int shared_a_runs; +static irqreturn_t shared_primary(int irq, void *data) +{ + assert(irq == LINE && (data == &shared_a || data == &shared_b)); + return data == &shared_a || wake_b ? IRQ_WAKE_THREAD : IRQ_HANDLED; +} +static irqreturn_t shared_thread(int irq, void *data) +{ + assert(irq == LINE); + if (data == &shared_a) { + shared_a_runs++; + complete(&shared_a_done); + } else { + assert(data == &shared_b); + complete(&shared_b_entered); + wait_for_completion(&shared_b_gate); + complete(&shared_b_done); + } + return IRQ_HANDLED; +} +static void shared_oneshot_controls(const struct service_test *test) +{ + unsigned long flags = IRQF_SHARED | IRQF_ONESHOT; + assert(!request_threaded_irq(LINE, shared_primary, shared_thread, flags, "A", &shared_a)); + assert(!request_threaded_irq(LINE, shared_primary, shared_thread, flags, "B", &shared_b)); + test->raise(test->context, LINE); + wait_for_completion(&shared_a_done); + wait_for_completion(&shared_b_entered); + msleep(2); + assert(test->masked(test->context, LINE)); + complete(&shared_b_gate); + wait_for_completion(&shared_b_done); + assert(!test->masked(test->context, LINE)); + free_irq(LINE, &shared_a); + free_irq(LINE, &shared_b); + + /* Cancel queued masked A while live B does not need its thread. */ + wake_b = false; + assert(!request_threaded_irq(LINE, shared_primary, shared_thread, flags, "A", &shared_a)); + assert(!request_threaded_irq(LINE, shared_primary, shared_thread, flags, "B", &shared_b)); + stela_linux_irq_run(LINE); + assert(test->masked(test->context, LINE)); + free_irq(LINE, &shared_a); + assert(shared_a_runs == 1); + assert(!test->masked(test->context, LINE)); + free_irq(LINE, &shared_b); +} + void stela_linux_service_test_body(void *context) { const struct service_test *test = context; @@ -55,6 +111,17 @@ void stela_linux_service_test_body(void *context) msleep(2); test->raise(test->context, LINE); wait_for_completion(&done); + /* A raised notification from the old action must not become work for + * a replacement action at the same logical IRQ/configuration epoch. */ + test->raise(test->context, LINE); free_irq(LINE, &handled); + assert(!request_irq(LINE, handle, 0, "replacement", &handled)); + msleep(2); + assert(handled == 1); + test->raise(test->context, LINE); + wait_for_completion(&done); + assert(handled == 2); + free_irq(LINE, &handled); + shared_oneshot_controls(test); stela_linux_exit(); } diff --git a/crates/stela-linux/src/compat/stela/workqueue_test.c b/crates/stela-linux/src/compat/stela/workqueue_test.c index eff673100a..552d692b0e 100644 --- a/crates/stela-linux/src/compat/stela/workqueue_test.c +++ b/crates/stela-linux/src/compat/stela/workqueue_test.c @@ -2,6 +2,7 @@ /* Linux's workqueues on the existing fixture's real Runtime tasks: the owner * starts each requested worker as a General job. */ #include +#include #include #include #include @@ -85,20 +86,44 @@ static void shutdown(void *context, bool force) } static unsigned int line_enables, line_disables; +static bool enable_notify, enable_refuse; +static unsigned int enable_primary_calls; -static int irq_enable(void *context, unsigned int irq) +static int irq_enable(void *context, unsigned int irq, bool *unexposed) { (void)context; assert(irq == 7); + *unexposed = false; + if (enable_refuse) { + /* Actual bounded software peer: no route/event/callback was issued. */ + *unexposed = true; + return -ENOSYS; + } line_enables++; + if (enable_notify) + stela_linux_irq_run(irq); return 0; } -static void irq_disable(void *context, unsigned int irq) +static irqreturn_t initial_enable_handler(int irq, void *dev_id) +{ + assert(irq == 7 && dev_id == &enable_primary_calls && in_hardirq()); + enable_primary_calls++; + return IRQ_HANDLED; +} + +static int irq_disable(void *context, unsigned int irq) { (void)context; assert(irq == 7); line_disables++; + return 0; +} +static int irq_retire(void *context, unsigned int irq) +{ + (void)context; + assert(irq == 7 && stela_linux_irq_actions_joined(irq)); + return 0; } static const struct stela_linux_services services = { @@ -107,6 +132,7 @@ static const struct stela_linux_services services = { .shutdown = shutdown, .irq_enable = irq_enable, .irq_disable = irq_disable, + .irq_retire = irq_retire, }; static const struct stela_linux_owner owner = {.services = &services}; @@ -294,6 +320,20 @@ void stela_linux_workqueue_test_main(void *context) assert(forced); /* Two sharers: the oneshot's thread keeps the line masked until it ends. */ + /* A truly unexposed refusal removes only this initialized action; retry + * proves there is no phantom list member. The next native enable delivers + * synchronously while request_irq still holds its request mutex. */ + enable_refuse = true; + assert(request_irq(7, initial_enable_handler, 0, "initial-refused", &enable_primary_calls) == -ENOSYS); + assert(!enable_primary_calls && !line_enables); + enable_refuse = false; + enable_notify = true; + assert(!request_irq(7, initial_enable_handler, 0, "initial-visible", &enable_primary_calls)); + assert(enable_primary_calls == 1); + enable_notify = false; + free_irq(7, &enable_primary_calls); + line_enables = line_disables = 0; + assert(!request_threaded_irq(7, hard_handler, thread_handler, IRQF_SHARED | IRQF_ONESHOT, "threaded", &hard_runs)); assert(line_enables == 1); diff --git a/crates/stela-linux/src/function.rs b/crates/stela-linux/src/function.rs index 3d702cb3f2..4e7dd771e9 100644 --- a/crates/stela-linux/src/function.rs +++ b/crates/stela-linux/src/function.rs @@ -3,11 +3,13 @@ //! stay Stela's: the function's owner placed it, and Linux reaches both through //! the table here. Domain errors retain real allocation pins and stop at the //! terminal Linux boundary before callers can reuse DMA-visible memory. +use super::catalogue::{self, Authority, PciAuthority}; use super::owner::Errno; use alloc::{boxed::Box, collections::BTreeMap, sync::Arc, vec::Vec}; use core::{ ffi::{c_char, c_int, c_uint, c_void}, marker::PhantomData, + mem::ManuallyDrop, ptr::NonNull, sync::atomic::{AtomicU64, Ordering}, }; @@ -28,7 +30,6 @@ const PAGE_SHIFT: u8 = 12; const PAGE_BYTES: u64 = 1 << PAGE_SHIFT; const PCIBIOS_BAD_REGISTER_NUMBER: c_int = 0x87; -const ENOMEM: Errno = -12; static QUARANTINED_MAPPINGS: AtomicU64 = AtomicU64::new(0); static QUARANTINED_BYTES: AtomicU64 = AtomicU64::new(0); @@ -103,7 +104,8 @@ impl Msi { Self { capability } } - fn control(self, config: &C) -> u16 { + /// Read this capability's control word through its configuration owner. + pub fn control(self, config: &C) -> u16 { config.read16(self.capability + Self::CONTROL) } @@ -148,13 +150,16 @@ struct RawFunction { irq: c_uint, regions: [Region; BARS], release_context: Option, + enroll: Option c_int>, } -const _: () = assert!(size_of::() == 232); +const _: () = assert!(size_of::() == 240); +const _: () = assert!(core::mem::offset_of!(RawFunction, enroll) == 232); const _: () = assert!(core::mem::offset_of!(RawFunction, release_context) == 224); unsafe extern "C" { - fn stela_linux_pci_attach(function: *const RawFunction) -> *mut c_void; + fn stela_linux_pci_attach(function: *const RawFunction, error: *mut c_int) -> *mut c_void; + fn stela_linux_owner() -> *const super::owner::RawOwner; fn stela_linux_pci_bound(device: *const c_void) -> bool; fn stela_linux_pci_remove_device(device: *mut c_void); fn stela_linux_pci_quarantined_functions() -> u64; @@ -305,6 +310,7 @@ fn direction(linux: c_uint) -> Direction { struct State { host: H, mappings: Mappings, + enrollment: Option>, } unsafe extern "C" fn release_context(context: *mut c_void) { @@ -404,6 +410,75 @@ unsafe extern "C" fn disable_msi(context: *mut c_void) { unsafe { state::(context) }.host.disable_msi(); } +unsafe extern "C" fn enroll(context: *mut c_void, device: *mut c_void) -> c_int { + // SAFETY: the attach call retains this State; take ends the mutable borrow + // before the generic catalogue can allocate or release any foreign object. + let authority = unsafe { state::(context) }.enrollment.take(); + let Some(authority) = authority else { + return -22; + }; + // SAFETY: C initialized this exact device before the first probe; this + // canonical process owner still holds the original registration reference. + match unsafe { catalogue::bind(device, authority) } { + Ok(()) => 0, + Err((authority, error)) => { + // SAFETY: refusal took no state or authority; no callback overlaps this short restore. + unsafe { state::(context) }.enrollment = Some(authority); + match error { + catalogue::Error::Native(error) => error, + _ => -22, + } + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum AttachError { + Catalogue(catalogue::Error), + Native(Errno), +} +static RETAINED_PRESENTATIONS: AtomicU64 = AtomicU64::new(0); +/// Refused presentation graphs abandoned without native retirement proof. +/// Observation only: this does not certify reclamation or native progress. +pub fn retained_presentations() -> u64 { + RETAINED_PRESENTATIONS.load(Ordering::Relaxed) +} +struct Retained { + _value: ManuallyDrop, +} +impl Retained { + fn new(value: T) -> Self { + Self { + _value: ManuallyDrop::new(value), + } + } +} +impl Drop for Retained { + fn drop(&mut self) { + // Presentation refusal is not proof that a caller's native host was + // unexposed. Keep the actual allocation and all source/domain roots. + let _ = RETAINED_PRESENTATIONS.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| { + Some(value.saturating_add(1)) + }); + } +} +/// The actual host/domain/authority remain retained on a refused presentation. +/// Drop keeps that graph: no H destructor or native retirement is inferred. +#[must_use = "presentation refusal retains actual native roots; inspect error and retained state"] +pub struct Rejected { + pub error: AttachError, + _held: Retained>>, +} +enum Held { + Before { + _host: H, + _authority: Box, + }, + Native { + _state: Box>, + }, +} + /// A function Linux can see. Drop unregisters it in the owner it was attached /// in. Other C device references retain the host and DMA roots until the final /// quiescent put in that owner; other final puts quarantine those resources. @@ -416,7 +491,8 @@ impl Attached { /// # Safety /// In an entered Linux owner, on a Linux task, as a driver may bind here. /// That owner and its platform services outlive all escaped device - /// references, including any quarantined final release. + /// references, including any quarantined final release. Refusal returns an + /// errno while retaining the host graph; it proves no native retirement. pub unsafe fn new( host: H, domain: Arc, @@ -425,6 +501,77 @@ impl Attached { where H: 'static, { + // SAFETY: unchanged legacy presentation contract; no canonical + // catalogue authority is inferred for this pre-migration path. + unsafe { Self::attach(host, domain, placement, None) }.map_err(|failure| { + match failure.error { + AttachError::Native(error) => error, + _ => -22, + } + }) + } + + /// Enroll exact original native source metadata before synchronous probe. + /// + /// # Safety + /// H accesses the exact original OwnedConfig allocation/epoch validated + /// when authority was made; its actual native grants stay kept. Its exact + /// manifest target/catalogue were qualified for that same observed native + /// function/board/source epoch by PciAuthority::new, never guessed labels. + /// On this canonical owner's checked Linux task. No borrowed config/entered permit + /// is retained in the authority or held across probe/callback/sleep. + pub unsafe fn new_catalogued( + kernel: &super::kernel::KernelOwner, + host: H, + placement: Placement, + authority: PciAuthority, + ) -> Result> + where + H: 'static, + { + // SAFETY: caller is entered; this checks the same actual canonical owner. + if unsafe { stela_linux_owner() } != kernel.raw() { + return Err(Rejected { + error: AttachError::Native(-1), + _held: Retained::new(Box::new(Held::Before { + _host: host, + _authority: Box::new(authority), + })), + }); + } + let domain = match authority.domain() { + Ok(domain) => domain, + Err(error) => { + return Err(Rejected { + error: AttachError::Catalogue(error), + _held: Retained::new(Box::new(Held::Before { + _host: host, + _authority: Box::new(authority), + })), + }); + } + }; + // SAFETY: caller's exact native source and canonical task proof. + unsafe { + Self::attach( + host, + domain, + placement, + Some(Box::new(Authority::Pci(authority))), + ) + } + } + + unsafe fn attach( + host: H, + domain: Arc, + placement: Placement, + enrollment: Option>, + ) -> Result> + where + H: 'static, + { + let catalogued = enrollment.is_some(); let state = Box::into_raw(Box::new(State { host, mappings: Mappings { @@ -432,6 +579,7 @@ impl Attached { limit: placement.dma_limit, live: BTreeMap::new(), }, + enrollment, })); let raw = RawFunction { context: state.cast(), @@ -447,17 +595,25 @@ impl Attached { irq: placement.irq, regions: placement.regions, release_context: Some(release_context::), + enroll: catalogued.then_some(enroll::), }; - // SAFETY: the caller's contract; C copies the table. - match NonNull::new(unsafe { stela_linux_pci_attach(&raw) }) { + let mut error = 0; + // SAFETY: caller's attach contract; C copies the table and returns a + // reference only after enrollment/publication. Refusal retains State. + match NonNull::new(unsafe { stela_linux_pci_attach(&raw, &raw mut error) }) { Some(device) => Ok(Self { device, _host: PhantomData, }), None => { - // SAFETY: refused, so Linux never saw it. - drop(unsafe { Box::from_raw(state) }); - Err(ENOMEM) + // SAFETY: C refused before publication/probe and explicitly left + // context ownership with this caller. Any enrolled record was + // retired by its real device put before returning NULL. + let state = unsafe { Box::from_raw(state) }; + Err(Rejected { + error: AttachError::Native(error), + _held: Retained::new(Box::new(Held::Native { _state: state })), + }) } } } diff --git a/crates/stela-linux/src/function/tests/fatal.rs b/crates/stela-linux/src/function/tests/fatal.rs index b1e1706f0d..7641f3f30b 100644 --- a/crates/stela-linux/src/function/tests/fatal.rs +++ b/crates/stela-linux/src/function/tests/fatal.rs @@ -11,6 +11,9 @@ struct Reporter { drops: Arc, domain: Arc, map_failure: bool, + irq_failure: bool, + enable_failure: bool, + irq_calls: Arc, } impl Platform for Reporter { fn now_ns(&self) -> i64 { @@ -26,6 +29,30 @@ impl Platform for Reporter { assert_eq!(level, 0); assert_eq!(message.to_str().unwrap(), self.expected); assert_eq!(self.drops.load(Ordering::Relaxed), 0); + if self.irq_failure { + unsafe extern "C" { + fn stela_linux_irq_actions_joined(irq: u32) -> bool; + } + // SAFETY: fatal report remains on the actual entered C free_irq + // stack; its closing request must still exist with joined work. + if self.enable_failure { + // SAFETY: exact entered action list remains on this C stack. + assert!(!unsafe { stela_linux_irq_actions_joined(7) }); + assert_eq!(self.irq_calls.load(Ordering::Relaxed), 1); + unsafe extern "C" { + fn stela_linux_irq_run(irq: u32); + } + // SAFETY: exact bounded C action remains linked on this + // non-returning enable-failure stack with live dev_id storage. + unsafe { stela_linux_irq_run(7) }; + assert_eq!(self.irq_calls.load(Ordering::Relaxed), 2); + } else { + // SAFETY: exact entered closing request remains linked. + assert!(unsafe { stela_linux_irq_actions_joined(7) }); + } + std::fs::write(&self.path, self.expected).unwrap(); + return; + } assert_eq!(dma_quarantine_status().mappings, 1); assert_eq!(dma_quarantine_status().bytes, 0x3000); if self.map_failure { @@ -62,11 +89,26 @@ impl Platform for Reporter { unsafe fn unmap_pages(&self, _: *mut c_void, _: usize) { unreachable!() } - fn irq_enable(&self, _: u32) -> Result<(), Errno> { - unreachable!() + fn irq_enable(&self, irq: u32) -> Result<(), crate::owner::IrqEnableError> { + assert!(self.irq_failure && irq == 7); + if self.enable_failure { + unsafe extern "C" { + fn stela_linux_irq_run(irq: u32); + } + // SAFETY: real bounded synchronous C primary, whose fully linked + // action must already exist before this enable hook can deliver. + unsafe { stela_linux_irq_run(7) }; + return Err(crate::owner::IrqEnableError::retained(-95)); + } + Ok(()) } - fn irq_disable(&self, _: u32) { - unreachable!() + fn irq_disable(&self, irq: u32) -> Result<(), Errno> { + assert!(self.irq_failure && irq == 7); + Ok(()) + } + fn irq_retire(&self, irq: u32) -> Result<(), Errno> { + assert!(self.irq_failure && irq == 7); + Err(-95) } unsafe fn copy_from_user(&self, _: *mut u8, _: *const u8, _: usize) -> usize { unreachable!() @@ -116,6 +158,7 @@ fn terminal(test: &str, map_failure: bool) { fixture.entered.take(); let domain = Arc::new(Identity::default()); let mut state = State { + enrollment: None, host: HostConfig(Config([0; 256])), mappings: mappings(&domain), }; @@ -125,6 +168,9 @@ fn terminal(test: &str, map_failure: bool) { drops: fixture.drops.clone(), domain: domain.clone(), map_failure, + irq_failure: false, + enable_failure: false, + irq_calls: Arc::new(AtomicUsize::new(0)), }); // SAFETY: this isolated subprocess runs no other task; the owner stays // live through the callback and its terminal emergency report. @@ -160,3 +206,151 @@ fn unmap_failure_stops_before_caller_can_reuse_memory() { false, ); } + +struct IrqAttempt<'a> { + path: &'a std::ffi::OsStr, + dev_id: *mut c_void, + primary: unsafe extern "C" fn(core::ffi::c_int, *mut c_void) -> core::ffi::c_int, + enable_failure: bool, +} +unsafe extern "C" fn quiet_primary(_: core::ffi::c_int, _: *mut c_void) -> core::ffi::c_int { + 1 +} +unsafe extern "C" fn counted_primary(_: core::ffi::c_int, dev: *mut c_void) -> core::ffi::c_int { + // SAFETY: the suspended caller retains this exact fixture AtomicUsize dev_id. + unsafe { &*dev.cast::() }.fetch_add(1, Ordering::Relaxed); + 1 +} +unsafe extern "C" fn irq_attempt(context: *mut c_void) { + // SAFETY: the hosted foreground helper keeps this exact attempt and original + // source/dev_id/owner graph through its real TaskBinding/current and trap. + let attempt = unsafe { &*context.cast::>() }; + unsafe extern "C" { + fn request_threaded_irq( + irq: u32, + primary: Option< + unsafe extern "C" fn(core::ffi::c_int, *mut c_void) -> core::ffi::c_int, + >, + thread: Option core::ffi::c_int>, + flags: core::ffi::c_ulong, + name: *const core::ffi::c_char, + dev_id: *mut c_void, + ) -> core::ffi::c_int; + fn free_irq(irq: u32, dev_id: *mut c_void) -> *const core::ffi::c_void; + } + // SAFETY: actual bound task and SAME entered Reporter owner, with exact live + // primary/dev_id. No native IRQ or physical/root capability is installed. + let result = unsafe { + request_threaded_irq( + 7, + Some(attempt.primary), + None, + 0, + if attempt.enable_failure { + c"enable-visible" + } else { + c"retained-action" + } + .as_ptr(), + attempt.dev_id, + ) + }; + if !attempt.enable_failure { + assert_eq!(result, 0); + // SAFETY: exact registered action on its original task stack; refusal + // must trap before unlink/free or returning dev_id to this caller. + unsafe { free_irq(7, attempt.dev_id) }; + } + let returned = if attempt.enable_failure { + "enable failure returned and caller reclaimed dev_id" + } else { + "free_irq returned and caller reclaimed dev_id" + }; + std::fs::write(attempt.path, returned).unwrap(); + std::process::exit(99); +} + +#[test] +fn irq_retirement_refusal_never_reclaims_request_or_returns_to_free_dev_id() { + const TEST: &str = "function::tests::fatal::irq_retirement_refusal_never_reclaims_request_or_returns_to_free_dev_id"; + const EXPECTED: &str = "IRQ action retirement unavailable; request retained"; + let Some(path) = std::env::var_os("STELA_IRQ_FATAL_WITNESS") else { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("irq-fatal.txt"); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST, "--test-threads=1", "--nocapture"]) + .env("STELA_IRQ_FATAL_WITNESS", &path) + .output() + .unwrap(); + assert_eq!(output.status.signal(), Some(libc::SIGILL), "{output:?}"); + assert_eq!(std::fs::read_to_string(path).unwrap(), EXPECTED); + return; + }; + let mut fixture = Fixture::new(); + fixture.entered.take(); + let owner = Owner::new(Reporter { + path: PathBuf::from(&path), + expected: EXPECTED, + drops: fixture.drops.clone(), + domain: Arc::new(Identity::default()), + map_failure: false, + irq_failure: true, + enable_failure: false, + irq_calls: Arc::new(AtomicUsize::new(0)), + }); + let mut attempt = IrqAttempt { + path: &path, + dev_id: Arc::as_ptr(&fixture.drops).cast_mut().cast(), + primary: quiet_primary, + enable_failure: false, + }; + // SAFETY: this isolated caller retains owner, pages and exact action dev_id + // while a real hosted Runtime/TaskBinding enters SAME Reporter on its stack. + // The body never returns: expected C trap or explicit false-return witness. + unsafe { + crate::task::tests::terminal_foreground(owner.raw(), irq_attempt, (&raw mut attempt).cast()) + } +} + +#[test] +fn synchronous_enable_delivery_then_error_retains_linked_action_before_trap() { + const TEST: &str = "function::tests::fatal::synchronous_enable_delivery_then_error_retains_linked_action_before_trap"; + const EXPECTED: &str = "IRQ enable uncertain; published request retained"; + let Some(path) = std::env::var_os("STELA_IRQ_ENABLE_FATAL_WITNESS") else { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("irq-enable-fatal.txt"); + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", TEST, "--test-threads=1", "--nocapture"]) + .env("STELA_IRQ_ENABLE_FATAL_WITNESS", &path) + .output() + .unwrap(); + assert_eq!(output.status.signal(), Some(libc::SIGILL), "{output:?}"); + assert_eq!(std::fs::read_to_string(path).unwrap(), EXPECTED); + return; + }; + let mut fixture = Fixture::new(); + fixture.entered.take(); + let calls = Arc::new(AtomicUsize::new(0)); + let owner = Owner::new(Reporter { + path: PathBuf::from(&path), + expected: EXPECTED, + drops: fixture.drops.clone(), + domain: Arc::new(Identity::default()), + map_failure: false, + irq_failure: true, + enable_failure: true, + irq_calls: calls.clone(), + }); + let mut attempt = IrqAttempt { + path: &path, + dev_id: Arc::as_ptr(&calls).cast_mut().cast(), + primary: counted_primary, + enable_failure: true, + }; + // SAFETY: same retained bounded owner/source/dev_id graph through actual + // TaskBinding/current. Synchronous delivery proves publication before the + // retained-enable fatal report; the body cannot return/reclaim this storage. + unsafe { + crate::task::tests::terminal_foreground(owner.raw(), irq_attempt, (&raw mut attempt).cast()) + } +} diff --git a/crates/stela-linux/src/function/tests/lifetime.rs b/crates/stela-linux/src/function/tests/lifetime.rs index 0697d63b4c..6f6bb9831e 100644 --- a/crates/stela-linux/src/function/tests/lifetime.rs +++ b/crates/stela-linux/src/function/tests/lifetime.rs @@ -134,3 +134,76 @@ fn atomic_final_put_quarantines_host_and_domain_roots() { assert_eq!(Arc::strong_count(&domain), 2); assert_eq!(quarantined_functions(), 1); } + +#[test] +fn retained_refusal_storage_keeps_before_graph() { + if !isolated("function::tests::lifetime::retained_refusal_storage_keeps_before_graph") { + return; + } + let drops = Arc::new(AtomicUsize::new(0)); + let domain = Arc::new(Identity::default()); + let host = CountedHost { + config: CountedConfig { + bytes: Config([0; 256]), + reads: Arc::new(AtomicUsize::new(0)), + }, + drops: drops.clone(), + }; + // This is the actual common retained-graph storage, not a fabricated + // PciAuthority: a model Attachment cannot qualify a native source target. + drop(Retained::new(Box::new((host, domain.clone())))); + assert_eq!(drops.load(Ordering::Relaxed), 0); + assert_eq!(Arc::strong_count(&domain), 2); + assert_eq!(retained_presentations(), 1); +} + +#[test] +fn null_presentation_keeps_actual_host_and_domain_state() { + if !isolated("function::tests::lifetime::null_presentation_keeps_actual_host_and_domain_state") + { + return; + } + unsafe extern "C" { + static stela_linux_bare: crate::owner::RawOwner; + fn stela_linux_kernel_claim(owner: *const crate::owner::RawOwner) -> i32; + fn stela_linux_kernel_environment(owner: *const crate::owner::RawOwner) -> i32; + fn stela_linux_kernel_ready(owner: *const crate::owner::RawOwner) -> i32; + } + let owner = core::ptr::addr_of!(stela_linux_bare); + // SAFETY: isolated cold C bookkeeping model with its actual static bare + // owner. This does not construct/qualify a KernelOwner or native Runtime. + unsafe { + assert_eq!(stela_linux_kernel_claim(owner), 0); + assert_eq!(stela_linux_kernel_environment(owner), 0); + assert_eq!(stela_linux_kernel_ready(owner), 0); + } + let _entered = Entered::try_new().unwrap(); + // SAFETY: every PCI name here is heap-generated; classifier reads nothing. + unsafe { crate::image::register(Arc::new(HeapNames)) } + .ok() + .unwrap(); + let drops = Arc::new(AtomicUsize::new(0)); + let reads = Arc::new(AtomicUsize::new(0)); + let domain = Arc::new(Identity::default()); + let host = CountedHost { + config: CountedConfig { + bytes: Config([0; 256]), + reads: reads.clone(), + }, + drops: drops.clone(), + }; + // SAFETY: isolated memory-only host/domain and actual entered C model + // owner. No driver is registered. Missing enrollment must refuse before + // publication/probe, with Rust State ownership left to this caller. + let result = unsafe { Attached::attach(host, domain.clone(), Placement::default(), None) }; + let rejected = match result { + Ok(_) => panic!("unenrolled presentation accepted"), + Err(value) => value, + }; + assert!(matches!(&rejected.error, AttachError::Native(-1))); + drop(rejected); + assert!(reads.load(Ordering::Relaxed) > 0); + assert_eq!(drops.load(Ordering::Relaxed), 0); + assert_eq!(Arc::strong_count(&domain), 2); + assert_eq!(retained_presentations(), 1); +} diff --git a/crates/stela-linux/src/kernel.rs b/crates/stela-linux/src/kernel.rs new file mode 100644 index 0000000000..8e021244c1 --- /dev/null +++ b/crates/stela-linux/src/kernel.rs @@ -0,0 +1,179 @@ +//! One mount-lifetime canonical Linux execution owner and device catalogue. +//! Failed or abandoned bootstrap retains the actual owner/environment roots; +//! there is no implemented full-kernel cache teardown or reinstallation. +use super::{ + catalogue::{self, Authority, FirmwareTarget}, + owner::{Owner, Platform, RawOwner}, + service::Environment, +}; +use alloc::{boxed::Box, sync::Arc}; +use core::{ffi::c_void, mem::ManuallyDrop, pin::Pin}; +use stela_driver_base::platform::work::{RetainedOwner, Runtime, WorkError, service::Domain}; +use stela_driver_core::firmware::Catalog; + +/// Actual original canonical work queue, which owns its provider/context/code/ +/// root lease. No caller ranges, read-only data classifier or dummy Arc can +/// construct this pin; only the same KernelOwner Runtime supplies it. +#[derive(Clone)] +pub(crate) struct ExecutionPin { + _queue: RetainedOwner, +} +impl ExecutionPin { + fn from_runtime(runtime: Pin<&Runtime>) -> Self { + Self { + _queue: runtime.queue().clone(), + } + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum Error { + Work(WorkError), + Native(i32), +} +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + write!(f, "canonical Linux bootstrap: {self:?}") + } +} +impl core::error::Error for Error {} + +unsafe extern "C" { + fn stela_linux_kernel_claim(owner: *const RawOwner) -> i32; + fn stela_linux_kernel_ready(owner: *const RawOwner) -> i32; +} +/// Real roots survive a refused/partial bootstrap; dropping failure does not +/// make an attached service domain or published RawOwner disappear. +pub struct Failure { + pub error: Error, + _owner: ManuallyDrop>>>, + _environment: ManuallyDrop>>>>, + _domain: ManuallyDrop>>, + _execution: ManuallyDrop, +} +impl Failure { + fn new( + error: Error, + owner: ManuallyDrop>>>, + environment: Option>>>, + domain: Arc>, + execution: ExecutionPin, + ) -> Self { + Self { + error, + _owner: owner, + _environment: ManuallyDrop::new(environment), + _domain: ManuallyDrop::new(domain), + _execution: ManuallyDrop::new(execution), + } + } +} +pub struct KernelOwner { + owner: ManuallyDrop>>>, + environment: ManuallyDrop>>>, + _domain: ManuallyDrop>>, + execution: ManuallyDrop, +} +impl KernelOwner { + /// # Safety + /// In the actual runtime's admitted dispatcher CPU. Runtime/domain, + /// platform services, code/image and global resource owners stay kept for + /// the whole kernel lifetime, including partial failure and abandoned Drop. + /// This Runtime queue's original retained owner covers this compiled + /// shared Linux/driver/provider executable code and all execution roots, + /// not merely runtime metadata. No unload is permitted while pins remain. + /// Cold bootstrap, before any prior Linux environment, task, initcall, + /// work/RCU queue or device activity: adopting old global queues is not + /// implemented. Caller starts this Environment/service before dispatch. + /// This constructor grants no PCI/root/IRQ/device permission. + pub unsafe fn new( + platform: P, + runtime: Pin<&Runtime>, + domain: Arc>, + ) -> Result> { + let execution = ExecutionPin::from_runtime(runtime); + let owner = ManuallyDrop::new(Owner::new(platform)); + // SAFETY: pinned resident owner above; claim is one irreversible registration. + let status = unsafe { stela_linux_kernel_claim(owner.raw()) }; + if status != 0 { + return Err(Failure::new( + Error::Native(status), + owner, + None, + domain, + execution, + )); + } + // SAFETY: caller keeps the real runtime/domain and pinned owner through all tasks. + let environment = match unsafe { Environment::new(owner.raw(), runtime, domain.clone()) } { + Ok(environment) => environment, + Err(error) => { + return Err(Failure::new( + Error::Work(error), + owner, + None, + domain, + execution, + )); + } + }; + // SAFETY: this same claimed owner now has its actual retained Environment. + let status = unsafe { stela_linux_kernel_ready(owner.raw()) }; + if status != 0 { + return Err(Failure::new( + Error::Native(status), + owner, + Some(environment), + domain, + execution, + )); + } + Ok(Self { + owner, + environment: ManuallyDrop::new(environment), + _domain: ManuallyDrop::new(domain), + execution: ManuallyDrop::new(execution), + }) + } + pub(crate) fn execution(&self) -> ExecutionPin { + ExecutionPin::clone(&self.execution) + } + pub fn raw(&self) -> *const RawOwner { + self.owner.raw() + } + pub fn platform(&self) -> &P { + self.owner.platform() + } + pub fn environment(&self) -> Pin<&Environment> { + self.environment.as_ref() + } + + /// Enroll the actual original regulatory faux device before its first + /// firmware request. No name/NULL-device fallback selects this route. + /// + /// # Safety + /// Entered in this canonical process owner, with a real retained original + /// reg_fdev created by the qualified cfg80211/faux path. Original regulatory + /// global state/code/context remains valid through its real release. The + /// exact target/Catalog resources are explicitly approved for this original + /// global regulatory authority; another device's valid manifest or a name + /// match does not qualify this assignment. + pub unsafe fn bind_regulatory( + &self, + device: *mut c_void, + target: FirmwareTarget, + catalog: Arc, + ) -> Result<(), (Box, catalogue::Error)> { + // SAFETY: the caller supplies that exact original object and global authority. + unsafe { + catalogue::bind( + device, + Box::new(Authority::global_regulatory( + target, + catalog, + self.execution(), + )), + ) + } + } +} diff --git a/crates/stela-linux/src/lib.rs b/crates/stela-linux/src/lib.rs index d5cae64ce7..4e77593ad3 100644 --- a/crates/stela-linux/src/lib.rs +++ b/crates/stela-linux/src/lib.rs @@ -10,6 +10,8 @@ use alloc::alloc::{alloc_zeroed, dealloc}; #[cfg(feature = "kernel")] use core::{alloc::Layout, ffi::c_void, ptr}; +#[cfg(all(feature = "kernel", target_arch = "x86_64"))] +pub mod catalogue; #[cfg(feature = "kernel")] pub mod client; #[cfg(all(feature = "kernel", target_arch = "x86_64"))] @@ -18,6 +20,8 @@ pub mod function; pub mod heap; #[cfg(feature = "kernel")] pub mod image; +#[cfg(all(feature = "kernel", target_arch = "x86_64"))] +pub mod kernel; #[cfg(feature = "kernel")] pub mod owner; #[cfg(feature = "kernel")] diff --git a/crates/stela-linux/src/owner.rs b/crates/stela-linux/src/owner.rs index e79922da68..5c47d425ba 100644 --- a/crates/stela-linux/src/owner.rs +++ b/crates/stela-linux/src/owner.rs @@ -35,6 +35,36 @@ impl TryFrom for WorkerKind { /// A negative Linux errno. pub type Errno = i32; +/// IRQ enable failure with an explicit original no-publication proof. +/// Retained is the safe default: errno alone never classifies hardware effects. +#[derive(Debug, Eq, PartialEq)] +pub struct IrqEnableError { + errno: Errno, + unexposed: bool, +} +impl IrqEnableError { + pub const fn retained(errno: Errno) -> Self { + Self { + errno, + unexposed: false, + } + } + /// # Safety + /// This exact original attempt published no native route/callback producer + /// able to reach the already-linked new C action. Actual returned native + /// owners were canceled in their original context; any issued service + /// epoch was closed/joined. A status code or cleared bit proves none of this. + pub unsafe fn unexposed(errno: Errno) -> Self { + Self { + errno, + unexposed: true, + } + } + pub const fn errno(self) -> Errno { + self.errno + } +} + /// What Linux code needs of the machine it runs on. Each method's contract is /// its entry in `stela_linux_services`. pub trait Platform { @@ -70,9 +100,14 @@ pub trait Platform { /// uses it any more. unsafe fn unmap_pages(&self, address: *mut c_void, count: usize); /// Route `irq` to the service, which calls `stela_linux_irq_run`. - fn irq_enable(&self, irq: u32) -> Result<(), Errno>; - /// Mask `irq`, returning once no new firing can reach the service. - fn irq_disable(&self, irq: u32); + fn irq_enable(&self, irq: u32) -> Result<(), IrqEnableError>; + /// Reversibly mask this source. Old queued delivery may still reach its + /// retained service epoch; this grants no action/endpoint retirement. + fn irq_disable(&self, irq: u32) -> Result<(), Errno>; + /// Retire the exact action after the C registry joined its action threads. + /// Return only after root/CPU and actual service-epoch joining; errors + /// retain every owner and C must not return/reclaim its request or dev_id. + fn irq_retire(&self, irq: u32) -> Result<(), Errno>; /// # Safety /// `to` is writable for `size` bytes; `from` is an address in the running /// client. Returns the bytes left uncopied at a fault. @@ -103,15 +138,16 @@ struct Services { unmap_device: unsafe extern "C" fn(*mut c_void, *mut c_void), map_pages: unsafe extern "C" fn(*mut c_void, *const u64, usize) -> *mut c_void, unmap_pages: unsafe extern "C" fn(*mut c_void, *mut c_void, usize), - irq_enable: unsafe extern "C" fn(*mut c_void, c_uint) -> c_int, - irq_disable: unsafe extern "C" fn(*mut c_void, c_uint), + irq_enable: unsafe extern "C" fn(*mut c_void, c_uint, *mut bool) -> c_int, + irq_disable: unsafe extern "C" fn(*mut c_void, c_uint) -> c_int, + irq_retire: unsafe extern "C" fn(*mut c_void, c_uint) -> c_int, copy_from_user: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_void, u64) -> u64, copy_to_user: unsafe extern "C" fn(*mut c_void, *mut c_void, *const c_void, u64) -> u64, map_user: unsafe extern "C" fn(*mut c_void, *mut c_void, u64, u64, u64) -> c_int, unmap_user: unsafe extern "C" fn(*mut c_void, *mut c_void, u64, usize), } -const _: () = assert!(size_of::() == 152); +const _: () = assert!(size_of::() == 160); /// `struct stela_linux_owner`. #[repr(C)] @@ -273,14 +309,35 @@ mod trampolines { unsafe { platform::

(context).unmap_pages(address, count) }; } - pub unsafe extern "C" fn irq_enable(context: *mut c_void, irq: c_uint) -> c_int { - // SAFETY: see the module. - status(unsafe { platform::

(context) }.irq_enable(irq)) + pub unsafe extern "C" fn irq_enable( + context: *mut c_void, + irq: c_uint, + unexposed: *mut bool, + ) -> c_int { + if unexposed.is_null() { + return -22; + } + // SAFETY: C supplies this writable result for the immediate call. It + // starts conservative even if a later native callback aborts/panics. + unsafe { unexposed.write(false) }; + // SAFETY: original entered owner and its classified native attempt. + match unsafe { platform::

(context) }.irq_enable(irq) { + Ok(()) => 0, + Err(error) => { + // SAFETY: the same immediate writable C result checked above. + unsafe { unexposed.write(error.unexposed) }; + error.errno + } + } } - pub unsafe extern "C" fn irq_disable(context: *mut c_void, irq: c_uint) { + pub unsafe extern "C" fn irq_disable(context: *mut c_void, irq: c_uint) -> c_int { // SAFETY: see the module. - unsafe { platform::

(context) }.irq_disable(irq); + status(unsafe { platform::

(context) }.irq_disable(irq)) + } + pub unsafe extern "C" fn irq_retire(context: *mut c_void, irq: c_uint) -> c_int { + // SAFETY: same exact entered owner's C registry/action join contract. + status(unsafe { platform::

(context) }.irq_retire(irq)) } pub unsafe extern "C" fn copy_from_user( @@ -384,6 +441,7 @@ impl Owner

{ unmap_pages: t::unmap_pages::

, irq_enable: t::irq_enable::

, irq_disable: t::irq_disable::

, + irq_retire: t::irq_retire::

, copy_from_user: t::copy_from_user::

, copy_to_user: t::copy_to_user::

, map_user: t::map_user::

, @@ -488,11 +546,21 @@ mod tests { unsafe fn unmap_pages(&self, address: *mut c_void, count: usize) { self.note(std::format!("unmap pages {:#x} {count}", address as usize)); } - fn irq_enable(&self, irq: u32) -> Result<(), Errno> { - if irq == 0 { Err(-22) } else { Ok(()) } + fn irq_enable(&self, irq: u32) -> Result<(), IrqEnableError> { + if irq == 0 { + // SAFETY: this exact model refused before every effect. + Err(unsafe { IrqEnableError::unexposed(-22) }) + } else { + Ok(()) + } } - fn irq_disable(&self, irq: u32) { + fn irq_disable(&self, irq: u32) -> Result<(), Errno> { self.note(std::format!("irq off {irq}")); + Ok(()) + } + fn irq_retire(&self, irq: u32) -> Result<(), Errno> { + self.note(std::format!("irq retire {irq}")); + Ok(()) } unsafe fn copy_from_user(&self, to: *mut u8, from: *const u8, size: usize) -> usize { // SAFETY: the tests pass valid buffers. @@ -556,9 +624,12 @@ mod tests { assert_eq!(pages as usize, 0x2000); (s.unmap_pages)(context, pages, 2); - assert_eq!((s.irq_enable)(context, 0), -22); - assert_eq!((s.irq_enable)(context, 5), 0); - (s.irq_disable)(context, 5); + let mut unexposed = false; + assert_eq!((s.irq_enable)(context, 0, &mut unexposed), -22); + assert!(unexposed); + assert_eq!((s.irq_enable)(context, 5, &mut unexposed), 0); + assert!(!unexposed); + assert_eq!((s.irq_disable)(context, 5), 0); let source = [1u8, 2]; let mut target = [0u8; 2]; diff --git a/crates/stela-linux/src/pages.rs b/crates/stela-linux/src/pages.rs index d85e66142b..c2abb058b3 100644 --- a/crates/stela-linux/src/pages.rs +++ b/crates/stela-linux/src/pages.rs @@ -16,6 +16,10 @@ use stela_driver_base::bus::dma::memory::{CacheAttribute, MemoryError, PinnedPag mod stack; #[cfg(target_arch = "x86_64")] pub use stack::{AdmissionError, StackAdmission}; +#[cfg(target_arch = "x86_64")] +mod mapping; +#[cfg(target_arch = "x86_64")] +pub use mapping::{MappingPagePin, retained_mapping_pins}; const PAGE_SHIFT: u32 = 12; const PAGE_BYTES: usize = 1 << PAGE_SHIFT; @@ -41,6 +45,7 @@ pub enum Error { Busy, GenerationExhausted, Native(c_int), + Memory(MemoryError), } /// The immutable physical and CPU span covered by a descriptor catalog. @@ -258,6 +263,8 @@ unsafe extern "C" { ) -> c_int; fn stela_linux_page_catalog_unregister(generation: u64) -> c_int; fn stela_linux_page_catalog_verify(generation: u64) -> c_int; + fn stela_linux_page_owner_context(owner: *const super::owner::RawOwner) -> c_int; + fn stela_linux_kernel_catalogue_active() -> bool; fn stela_linux_page_request_basic(gfp: u32) -> bool; fn stela_linux_page_request_reclaimable(gfp: u32) -> bool; fn stela_linux_page_request_blocking(gfp: u32) -> bool; @@ -283,9 +290,60 @@ impl Drop for Entered { } } +enum ContextEntry { + Legacy, + #[cfg(target_arch = "x86_64")] + Canonical { + owner: *const super::owner::RawOwner, + execution: super::kernel::ExecutionPin, + }, +} +impl ContextEntry { + fn scope(&self) -> Result, Error> { + match self { + Self::Legacy => { + // SAFETY: pure global phase observation, with no entry attempt. + if unsafe { stela_linux_kernel_catalogue_active() } { + return Err(Error::Busy); + } + Entered::try_new().map(Some) + } + #[cfg(target_arch = "x86_64")] + Self::Canonical { owner, .. } => { + // SAFETY: observational check only, no entry/owner change. + let status = unsafe { stela_linux_page_owner_context(*owner) }; + if status != 0 { + return Err(Error::Native(status)); + } + Ok(None) + } + } + } + fn canonical(&self) -> bool { + match self { + Self::Legacy => false, + #[cfg(target_arch = "x86_64")] + Self::Canonical { .. } => true, + } + } + #[cfg(target_arch = "x86_64")] + fn check( + &self, + kernel: &super::kernel::KernelOwner, + ) -> Result<(), Error> { + match self { + Self::Canonical { owner, .. } if *owner == kernel.raw() => { + self.scope()?; + Ok(()) + } + _ => Err(Error::InvalidReservation), + } + } +} struct Context

{ provider: P, reservations: Vec, + entry: ContextEntry, } struct Pin { @@ -490,9 +548,21 @@ impl Catalog

{ } unsafe fn register_inventory( + provider: P, + reservations: Vec, + annotated: bool, + ) -> Result { + // SAFETY: unchanged legacy registration/exclusion contract. + unsafe { + Self::register_inventory_entry(provider, reservations, annotated, ContextEntry::Legacy) + } + } + + unsafe fn register_inventory_entry( provider: P, mut reservations: Vec, annotated: bool, + entry: ContextEntry, ) -> Result { if reservations.is_empty() { return Err(Error::InvalidReservation); @@ -532,6 +602,7 @@ impl Catalog

{ let mut context = try_box(Context { provider, reservations, + entry, })?; let operations = OperationsV2 { version: 2, @@ -545,7 +616,7 @@ impl Catalog

{ release_ready: release_ready::

, }; let result = { - let _entered = Entered::try_new()?; + let _entered = context.entry.scope()?; // SAFETY: arrays contain their declared number of initialized // repr(C) records. Provider-owned reservations and Context remain // while C validates and copies the selected inventory. @@ -583,6 +654,105 @@ impl Catalog

{ }) } + /// Register in the actual already-entered canonical execution owner. + /// + /// # Safety + /// Checked serialized native dispatcher bootstrap or Linux process task on + /// this KernelOwner's actual CPU/root, quiescent with no native IRQ/reentry + /// or migration. Provider/reservation meet register's original contracts. + /// The real canonical execution pin covers all C/provider callback code. + /// No second entry or invented Linux task/resource is established here. + #[cfg(target_arch = "x86_64")] + pub unsafe fn register_current( + kernel: &super::kernel::KernelOwner, + provider: P, + reservation: Reservation, + ) -> Result { + let mut extents = Vec::new(); + extents + .try_reserve_exact(1) + .map_err(|_| Error::OutOfMemory)?; + extents.push(Extent::ordinary(reservation)); + // SAFETY: same original provider/reservation/canonical context contract. + unsafe { Self::register_current_inventory(kernel, provider, extents, false) } + } + /// Annotated composed catalogue in the same actual entered canonical owner. + /// + /// # Safety + /// register_current's CPU/root/context rules and register_annotated's + /// original disjoint inventory/stack permission contracts all hold. + #[cfg(target_arch = "x86_64")] + pub unsafe fn register_annotated_current( + kernel: &super::kernel::KernelOwner, + provider: P, + extents: Vec, + ) -> Result { + // SAFETY: caller supplies original composed inventory and current owner. + unsafe { Self::register_current_inventory(kernel, provider, extents, true) } + } + #[cfg(target_arch = "x86_64")] + unsafe fn register_current_inventory( + kernel: &super::kernel::KernelOwner, + provider: P, + extents: Vec, + annotated: bool, + ) -> Result { + // SAFETY: observational validation, before C metadata publication. + let status = unsafe { stela_linux_page_owner_context(kernel.raw()) }; + if status != 0 { + return Err(Error::Native(status)); + } + let entry = ContextEntry::Canonical { + owner: kernel.raw(), + execution: kernel.execution(), + }; + // SAFETY: original provider plus exact native owner/code retention. + unsafe { Self::register_inventory_entry(provider, extents, annotated, entry) } + } + /// Diagnose this exact existing catalogue; never create another one. + /// + /// # Safety + /// Already entered in its actual canonical process task/CPU/root, quiescent. + /// The bounded diagnostic's temporary allocations may use the real provider. + #[cfg(target_arch = "x86_64")] + pub unsafe fn verify_current( + &self, + kernel: &super::kernel::KernelOwner, + ) -> Result<(), Error> { + let context = self.context.as_ref().ok_or(Error::InvalidReservation)?; + context.entry.check(kernel)?; + // SAFETY: same retained generation and actual already-entered owner. + let status = unsafe { stela_linux_page_catalog_verify(self.generation) }; + if status == 0 { + Ok(()) + } else { + Err(Error::Native(status)) + } + } + /// Same-owner catalogue retirement after every actual external user ends. + /// + /// # Safety + /// Already entered in its original canonical process CPU/root, quiescent. + /// All producer/config/task/alias users have actually retired; C may still + /// refuse live pages or provider fences. Failure keeps the whole context. + #[cfg(target_arch = "x86_64")] + pub unsafe fn try_retire_current( + &mut self, + kernel: &super::kernel::KernelOwner, + ) -> Result<(), Error> { + let Some(context) = self.context.as_ref() else { + return Ok(()); + }; + context.entry.check(kernel)?; + // SAFETY: original generation and admitted process release scope. + let status = unsafe { stela_linux_page_catalog_unregister(self.generation) }; + if status != 0 { + return Err(Error::Native(status)); + } + self.context.take(); + Ok(()) + } + pub fn generation(&self) -> u64 { self.generation } @@ -593,6 +763,17 @@ impl Catalog

{ if self.context.is_none() { return Err(Error::InvalidReservation); } + if self + .context + .as_ref() + .is_some_and(|context| context.entry.canonical()) + { + return Err(Error::Busy); + } + // SAFETY: pure phase observation before any bare entry attempt. + if unsafe { stela_linux_kernel_catalogue_active() } { + return Err(Error::Busy); + } let _entered = Entered::try_new()?; // SAFETY: the generation/provider remain registered; the // diagnostic owns and retires its temporary page references. @@ -610,6 +791,17 @@ impl Catalog

{ if self.context.is_none() { return Ok(()); } + if self + .context + .as_ref() + .is_some_and(|context| context.entry.canonical()) + { + return Err(Error::Busy); // Only explicit same-owner retirement may release it. + } + // SAFETY: pure phase observation before any bare entry attempt. + if unsafe { stela_linux_kernel_catalogue_active() } { + return Err(Error::Busy); + } let result = { let _entered = Entered::try_new()?; // SAFETY: the handle supplies its unique registered generation. diff --git a/crates/stela-linux/src/pages/mapping.rs b/crates/stela-linux/src/pages/mapping.rs new file mode 100644 index 0000000000..e6882f5be9 --- /dev/null +++ b/crates/stela-linux/src/pages/mapping.rs @@ -0,0 +1,211 @@ +//! Actual catalogue allocation references for native WB RAM aliases. +//! No PFN, cache override, root mapper or hardware permission is created here. +use super::*; +use crate::{ + kernel::{ExecutionPin, KernelOwner}, + owner::{Platform, RawOwner}, +}; +use core::mem::ManuallyDrop; + +#[repr(C)] +struct NativeMappingPage { + record: *mut c_void, + provider_pin: *mut c_void, + cpu_page: *mut c_void, +} +unsafe extern "C" { + fn stela_linux_page_mapping_pin( + generation: u64, + context: *const c_void, + owner: *const RawOwner, + physical: u64, + out: *mut NativeMappingPage, + ) -> c_int; + fn stela_linux_page_mapping_unpin( + generation: u64, + context: *const c_void, + owner: *const RawOwner, + token: *mut c_void, + ) -> c_int; +} +static RETAINED: AtomicU64 = AtomicU64::new(0); +pub fn retained_mapping_pins() -> u64 { + RETAINED.load(Ordering::Relaxed) +} + +/// Exact original allocation/page reference, affine to its native release scope. +/// Exporting backing metadata does not replace keeping this object through all +/// Linux page-descriptor, VMA/alias and CPU mapping users. No Drop unpin occurs. +#[must_use = "retain through all alias users; explicitly release only after actual mapping retirement"] +pub struct MappingPagePin { + pages: ManuallyDrop, + execution: ManuallyDrop, + context: *const c_void, + owner: *const RawOwner, + generation: u64, + record: NonNull, + physical: u64, + cpu: NonNull, + page_index: usize, + released: bool, + local: PhantomData>, +} +impl MappingPagePin { + /// The original actual allocation, never a caller-owned PA list. + pub fn backing(&self) -> &PinnedPages { + &self.pages + } + pub fn physical(&self) -> u64 { + self.physical + } + pub fn cpu_page(&self) -> NonNull { + self.cpu + } + pub fn page_index(&self) -> usize { + self.page_index + } + /// # Safety + /// On the original canonical checked CPU/root/process task, already entered + /// quiescent. Every native root/VMA/alias/CPU user of this claim has actually + /// retired. No outstanding derived view substitutes for this allocation ref. + /// Failure changes nothing and returns the complete held graph for retry. + pub unsafe fn release( + mut self, + kernel: &KernelOwner, + ) -> Result<(), Self> { + if kernel.raw() != self.owner { + return Err(self); + } + // SAFETY: C validates exact generation/Context/owner/token before any + // decrement; success performs no callback, allocator or final free. + let status = unsafe { + stela_linux_page_mapping_unpin( + self.generation, + self.context, + self.owner, + self.record.as_ptr(), + ) + }; + if status != 0 { + return Err(self); + } + self.released = true; + // SAFETY: the original C Pin still owns these pages until later + // pages_finish. Clone release cannot free/recycle its actual backing. + // Actual Context and KernelOwner retain callback/execution code too. + unsafe { + ManuallyDrop::drop(&mut self.pages); + ManuallyDrop::drop(&mut self.execution); + } + Ok(()) + } +} +impl Drop for MappingPagePin { + fn drop(&mut self) { + if !self.released { + // Keep the real C ref, original backing and code/root graph. The + // C ref blocks catalogue unregister; Catalog Drop quarantines its + // original Provider Context, not a substitute allocation. + let _ = RETAINED.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| { + Some(value.saturating_add(1)) + }); + } + } +} +impl Catalog

{ + /// Pin one live ordinary WB allocation page for a separately owned mapper. + /// + /// # Safety + /// Already entered/quiescent on the registered canonical owner's real + /// CPU/root/process task. Caller supplies actual alias/cache/root ownership + /// separately and keeps the affine result through every such user. This + /// exports existing original backing only; it supplies no new cache policy, + /// PFN discovery, native I/O, task-stack or root-mapping permission. + pub unsafe fn pin_mapping( + &self, + kernel: &KernelOwner, + physical: u64, + ) -> Result { + let context = self.context.as_ref().ok_or(Error::InvalidReservation)?; + context.entry.check(kernel)?; + let ContextEntry::Canonical { owner, execution } = &context.entry else { + return Err(Error::InvalidReservation); + }; + let context_pointer = ptr::from_ref(&**context).cast::(); + let mut native = NativeMappingPage { + record: ptr::null_mut(), + provider_pin: ptr::null_mut(), + cpu_page: ptr::null_mut(), + }; + // SAFETY: actual Context/generation owns this provider ABI. C takes + // its real allocation ref before returning any original Pin pointer. + let status = unsafe { + stela_linux_page_mapping_pin( + self.generation, + context_pointer, + *owner, + physical, + &raw mut native, + ) + }; + if status != 0 { + return Err(Error::Native(status)); + } + let record = NonNull::new(native.record).expect("successful allocation ref"); + let provider = + NonNull::new(native.provider_pin.cast::()).expect("original provider Pin"); + let cpu = NonNull::new(native.cpu_page.cast::()).expect("original CPU page"); + // SAFETY: exact registered Rust Context plus C ref keeps its original + // Rust-created Pin alive. This clones actual PageBacking ownership, + // not addresses, a reservation descriptor or an arbitrary caller Arc. + let pages = unsafe { provider.as_ref() }.pages.clone(); + let mut pin = MappingPagePin { + pages: ManuallyDrop::new(pages), + execution: ManuallyDrop::new(execution.clone()), + context: context_pointer, + owner: *owner, + generation: self.generation, + record, + physical, + cpu, + page_index: 0, + released: false, + local: PhantomData, + }; + let validation = (|| { + if pin.pages.page_shift() != PAGE_SHIFT as u8 + || pin.pages.cache_attribute() != CacheAttribute::WriteBack + { + return Err(Error::InvalidReservation); + } + let index = pin + .pages + .physical_pages() + .iter() + .position(|page| *page == physical) + .ok_or(Error::InvalidReservation)?; + let offset = index + .checked_mul(PAGE_BYTES) + .ok_or(Error::InvalidReservation)?; + let mapping = pin + .pages + .cpu_mapping(CacheAttribute::WriteBack) + .map_err(Error::Memory)?; + let address = mapping.address(offset, PAGE_BYTES).map_err(Error::Memory)?; + if address != cpu { + return Err(Error::InvalidReservation); + } + pin.page_index = index; + Ok(()) + })(); + if let Err(error) = validation { + // SAFETY: no mapping was exposed; the same actual release scope + // applies. Refusal keeps the complete graph via its default Drop. + if let Err(retained) = unsafe { pin.release(kernel) } { + drop(retained); + } + return Err(error); + } + Ok(pin) + } +} diff --git a/crates/stela-linux/src/pages/tests.rs b/crates/stela-linux/src/pages/tests.rs index ff86d33a71..a4435bbcf6 100644 --- a/crates/stela-linux/src/pages/tests.rs +++ b/crates/stela-linux/src/pages/tests.rs @@ -336,6 +336,7 @@ fn callback_transfers_only_valid_pins_and_refuses_before_provider_allocation() { let mut context = Context { provider, reservations: alloc::vec![Extent::ordinary(reservation)], + entry: ContextEntry::Legacy, }; let mut output = NativeAllocation { pin: ptr::null_mut(), @@ -446,3 +447,5 @@ fn catalog_retirement_and_nested_drop_preserve_provider_lifetime() { drop(unsafe { Box::from_raw(context.cast_mut()) }); assert_eq!(drops.load(Ordering::Relaxed), 1); } + +mod mapping_pin; diff --git a/crates/stela-linux/src/pages/tests/mapping_pin.rs b/crates/stela-linux/src/pages/tests/mapping_pin.rs new file mode 100644 index 0000000000..426db686e3 --- /dev/null +++ b/crates/stela-linux/src/pages/tests/mapping_pin.rs @@ -0,0 +1,179 @@ +//! Real Rust provider Pin/PinnedPages behind the C allocation-ref bridge. +//! CPU-only existing catalogue models: no fake KernelOwner/code permission, +//! native physical address, cache change or VMA/root admission is established. +use super::*; +use crate::owner::RawOwner; +#[repr(C)] +struct Raw { + record: *mut c_void, + provider_pin: *mut c_void, + cpu_page: *mut c_void, +} +unsafe extern "C" { + fn __alloc_pages_noprof(gfp: u32, order: u32, nid: i32, nodes: *mut c_void) -> *mut c_void; + fn __free_pages(page: *mut c_void, order: u32); + fn stela_linux_pages_finish(); + fn stela_linux_page_mapping_pin( + generation: u64, + context: *const c_void, + owner: *const RawOwner, + physical: u64, + out: *mut Raw, + ) -> c_int; + fn stela_linux_page_mapping_unpin( + generation: u64, + context: *const c_void, + owner: *const RawOwner, + record: *mut c_void, + ) -> c_int; +} +fn isolated(name: &str) -> bool { + if std::env::var_os("STELA_MAPPING_REF_CHILD").is_some() { + return true; + } + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name, "--test-threads=1", "--nocapture"]) + .env("STELA_MAPPING_REF_CHILD", "1") + .output() + .unwrap(); + assert!( + output.status.success(), + "{}\n{}", + std::string::String::from_utf8_lossy(&output.stdout), + std::string::String::from_utf8_lossy(&output.stderr) + ); + false +} +#[test] +fn bridge_clones_original_backing_and_blocks_catalogue_reuse() { + if !isolated( + "pages::tests::mapping_pin::bridge_clones_original_backing_and_blocks_catalogue_reuse", + ) { + return; + } + let (provider, reservation, drops, _) = model(false); + let expected_cpu = reservation.cpu_base; + // SAFETY: actual owned aligned model CPU buffer; symbolic PA never gains + // native/hardware permission. Existing provider/reservation own it fully. + let mut catalog = unsafe { Catalog::register(provider, reservation) }.unwrap(); + let context = ptr::from_ref(&**catalog.context.as_ref().unwrap()).cast::(); + let generation = catalog.generation; + let entered = Entered::try_new().unwrap(); + let owner = ptr::addr_of!(stela_linux_bare).cast::(); + // SAFETY: isolated entered C model, exact registered provider and page API. + let page = unsafe { __alloc_pages_noprof(0, 0, -1, ptr::null_mut()) }; + assert!(!page.is_null()); + let mut raw = Raw { + record: ptr::null_mut(), + provider_pin: ptr::null_mut(), + cpu_page: ptr::null_mut(), + }; + assert_eq!( + // SAFETY: retained registered Context and exact generation, entered bare + // owner, live original C page allocation and writable Raw output. + unsafe { stela_linux_page_mapping_pin(generation, context, owner, PHYSICAL, &raw mut raw) }, + 0 + ); + assert!(!raw.record.is_null() && !raw.provider_pin.is_null()); + assert_eq!(raw.cpu_page.cast::(), expected_cpu.as_ptr()); + // SAFETY: C ref keeps this actual Rust-created provider Pin alive. Clone + // shares its real CPU allocation, not an unrelated Arc or PA descriptor. + let backing = unsafe { &*raw.provider_pin.cast::() }.pages.clone(); + assert_eq!(backing.physical_pages(), [PHYSICAL]); + assert_eq!( + backing + .cpu_mapping(CacheAttribute::WriteBack) + .unwrap() + .address(0, PAGE_BYTES) + .unwrap(), + expected_cpu + ); + // SAFETY: end logical original C page ownership, keep the C allocation ref. + unsafe { + __free_pages(page, 0); + } + assert_eq!(drops.load(Ordering::Relaxed), 0); + assert_eq!( + // SAFETY: same entered owner and live registered generation; the actual + // outstanding C ref must refuse retirement before Context teardown. + unsafe { stela_linux_page_catalog_unregister(generation) }, + -16 + ); + assert_eq!( + // SAFETY: exact live record from this Context/generation, released once + // under its entered owner; no mapping was exposed through this ref. + unsafe { stela_linux_page_mapping_unpin(generation, context, owner, raw.record) }, + 0 + ); + // SAFETY: original logical references and external C ref ended at quiescence. + unsafe { + stela_linux_pages_finish(); + } + assert_eq!(drops.load(Ordering::Relaxed), 0); // Real cloned backing still owns RAM. + drop(backing); + assert_eq!(drops.load(Ordering::Relaxed), 1); + drop(entered); + catalog.try_retire().unwrap(); +} +#[test] +fn outstanding_c_ref_keeps_original_provider_context_after_drop() { + if !isolated( + "pages::tests::mapping_pin::outstanding_c_ref_keeps_original_provider_context_after_drop", + ) { + return; + } + let (provider, reservation, drops, _) = model(false); + // SAFETY: isolated owned CPU model, no actual native root/cache operation. + let catalog = unsafe { Catalog::register(provider, reservation) }.unwrap(); + let context = ptr::from_ref(&**catalog.context.as_ref().unwrap()); + let generation = catalog.generation; + let entered = Entered::try_new().unwrap(); + let owner = ptr::addr_of!(stela_linux_bare).cast::(); + // SAFETY: actual registered model provider receives ordinary page allocation. + let page = unsafe { __alloc_pages_noprof(0, 0, -1, ptr::null_mut()) }; + assert!(!page.is_null()); + let mut raw = Raw { + record: ptr::null_mut(), + provider_pin: ptr::null_mut(), + cpu_page: ptr::null_mut(), + }; + assert_eq!( + // SAFETY: live owned provider Context and original registered generation + // match the entered owner and allocated C page; Raw output is writable. + unsafe { + stela_linux_page_mapping_pin(generation, context.cast(), owner, PHYSICAL, &raw mut raw) + }, + 0 + ); + // SAFETY: release only the logical Linux page reference. + unsafe { + __free_pages(page, 0); + } + drop(entered); + let before = quarantined_catalogs(); + drop(catalog); + assert_eq!(drops.load(Ordering::Relaxed), 0); + assert_eq!(quarantined_catalogs(), before + 1); + let entered = Entered::try_new().unwrap(); + assert_eq!( + // SAFETY: refused Catalog Drop retained this exact Context/generation + // and still-live C record; the same entered owner ends that ref once. + unsafe { stela_linux_page_mapping_unpin(generation, context.cast(), owner, raw.record) }, + 0 + ); + // SAFETY: actual logical and external references now ended; drain/unregister. + unsafe { + stela_linux_pages_finish(); + } + assert_eq!(drops.load(Ordering::Relaxed), 1); + assert_eq!( + // SAFETY: same original generation after logical/external refs ended + // and pages_finish drained their records under the retained owner. + unsafe { stela_linux_page_catalog_unregister(generation) }, + 0 + ); + drop(entered); + // SAFETY: same original Box quarantined by Drop, no C borrow survives the + // successful unregister. This is not a production reset/reclaim pathway. + drop(unsafe { Box::from_raw(context.cast_mut()) }); +} diff --git a/crates/stela-linux/src/service.rs b/crates/stela-linux/src/service.rs index 0dc7978251..6c1408ac20 100644 --- a/crates/stela-linux/src/service.rs +++ b/crates/stela-linux/src/service.rs @@ -3,9 +3,9 @@ //! workqueues and owner run on. All of them share one CPU and take turns, which //! is the uniprocessor, non-preemptible execution Linux's code is built for. //! -//! An interrupt only records its line ([`Environment::raise`]); the handlers +//! An interrupt only records its original epoch ([`IrqEvent::raise`]); the handlers //! run on the service task, which sleeps until a line is raised or the next -//! timer is due (`compat/linux/kernel/service.c`). +//! timer is due (`compat/kernel/service.c`). use super::{ owner::{RawOwner, WorkerKind}, task::TaskBinding, @@ -17,7 +17,7 @@ use core::{ marker::PhantomPinned, pin::Pin, ptr::NonNull, - sync::atomic::{AtomicBool, AtomicU64, Ordering}, + sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}, }; use stela_driver_base::platform::work::{ Callback, Runtime, SwitchBinding, Ticket, WorkError, @@ -31,6 +31,7 @@ struct Call { context: *mut c_void, begin: unsafe extern "C" fn(*mut c_void) -> bool, next_irq: unsafe extern "C" fn(*mut c_void) -> c_int, + complete_irq: unsafe extern "C" fn(*mut c_void), drain: unsafe extern "C" fn(*mut c_void), finish: unsafe extern "C" fn(*mut c_void, i64), done: unsafe extern "C" fn(*mut c_void) -> bool, @@ -57,23 +58,42 @@ pub unsafe fn sleep_us(minimum: u64) { /// Interrupt lines an owner may give Linux. pub const LINES: u32 = 256; -/// The lines raised and not yet served. -struct Lines([AtomicU64; LINES as usize / 64]); - -impl Lines { - fn raise(&self, line: u32) { - self.0[line as usize / 64].fetch_or(1 << (line % 64), Ordering::Release); +const IRQ_OPEN: u8 = 0; +const IRQ_CLOSING: u8 = 1; +const IRQ_JOINED: u8 = 2; +struct IrqEpoch { + line: u32, + state: AtomicU8, + pending: AtomicBool, + active: AtomicUsize, +} +/// One original service notification epoch. Native callbacks retain this exact +/// endpoint instead of rediscovering the current epoch from a numeric line. +#[derive(Clone)] +pub struct IrqEvent { + epoch: Arc, + raised: RaisedWork, +} +impl IrqEvent { + pub fn raise(&self) -> Result<(), WorkError> { + if self.epoch.state.load(Ordering::Acquire) != IRQ_OPEN { + return Err(WorkError::Closed); + } + self.epoch.pending.store(true, Ordering::Release); + if self.epoch.state.load(Ordering::Acquire) != IRQ_OPEN { + return Err(WorkError::Closed); + } + self.raised.raise() } - - fn take(&self) -> Option { - self.0.iter().zip(0..).find_map(|(word, index)| { - let bits = word.load(Ordering::Acquire); - (bits != 0).then(|| { - let bit = bits.trailing_zeros(); - word.fetch_and(!(1 << bit), Ordering::AcqRel); - index * 64 + bit - }) - }) + /// Prevent new old-epoch service entries. This alone proves no hardware, + /// callback, thread or DMA retirement; those owners must join separately. + pub fn begin_close(&self) { + let _ = self.epoch.state.compare_exchange( + IRQ_OPEN, + IRQ_CLOSING, + Ordering::AcqRel, + Ordering::Acquire, + ); } } @@ -119,7 +139,8 @@ pub struct Environment { runtime: NonNull>, domain: Arc>, raised: RaisedWork, - lines: Lines, + lines: UnsafeCell<[Option>; LINES as usize]>, + active_irq: UnsafeCell>>, /// The batch the service task is delivering. batch: UnsafeCell>, stopping: AtomicBool, @@ -153,13 +174,22 @@ impl Environment { if runtime.general_capacity(super::task::stack_requirement()?)? < 5 { return Err(WorkError::Unavailable); } + unsafe extern "C" { + fn stela_linux_kernel_environment(owner: *const RawOwner) -> i32; + } + // SAFETY: caller owns the original resident RawOwner; this only records + // cold bootstrap and rejects a second canonical Environment before effects. + if unsafe { stela_linux_kernel_environment(owner) } != 0 { + return Err(WorkError::Unavailable); + } runtime.attach_service_domain(domain.clone())?; Ok(Box::pin(Self { owner, runtime: NonNull::from(runtime.get_ref()), raised: domain.raised_work()?, domain, - lines: Lines([const { AtomicU64::new(0) }; LINES as usize / 64]), + lines: UnsafeCell::new(core::array::from_fn(|_| None)), + active_irq: UnsafeCell::new(None), batch: UnsafeCell::new(None), stopping: AtomicBool::new(false), service_started: AtomicBool::new(false), @@ -333,12 +363,66 @@ impl Environment { Ok(()) } - /// Record that `line`, below [`LINES`], fired. Safe in an interrupt. - pub fn raise(&self, line: u32) -> Result<(), WorkError> { - self.lines.raise(line); - self.raised.raise() + /// Create one notification epoch for an original inactive IRQ action. + /// # Safety + /// Called on the original process CPU; the actual source/entry owner is + /// exclusive. A prior epoch was joined, not merely masked or root-fenced. + pub unsafe fn irq_epoch(&self, line: u32) -> Result { + self.runtime() + .general_capacity(super::task::stack_requirement()?)?; + if line >= LINES || self.stopping.load(Ordering::Acquire) { + return Err(WorkError::Closed); + } + // SAFETY: checked original process CPU, no yield/callback in this borrow. + let slots = unsafe { &mut *self.lines.get() }; + if slots[line as usize] + .as_ref() + .is_some_and(|old| old.state.load(Ordering::Acquire) != IRQ_JOINED) + { + return Err(WorkError::Busy); + } + let epoch = Arc::new(IrqEpoch { + line, + state: AtomicU8::new(IRQ_OPEN), + pending: AtomicBool::new(false), + active: AtomicUsize::new(0), + }); + slots[line as usize] = Some(epoch.clone()); + Ok(IrqEvent { + epoch, + raised: self.raised.clone(), + }) + } + /// Join/cancel old queued primary service only after real native root/CPU + /// retirement and C action-thread joining. No entered permit spans a wait. + /// # Safety + /// This is the original source/event and its producers cannot resume; + /// actual source mask/action-close and CPU/inflight/EOI join already completed. + /// C primary callbacks cannot sleep; an active callback here would mean + /// reentrant free_irq and is refused instead of pretending to wait itself. + pub unsafe fn join_irq(&self, event: &IrqEvent) -> Result<(), WorkError> { + self.runtime() + .general_capacity(super::task::stack_requirement()?)?; + // SAFETY: original process CPU, no switch while reading this table. + let slots = unsafe { &*self.lines.get() }; + let epoch = slots + .get(event.epoch.line as usize) + .and_then(Option::as_ref) + .ok_or(WorkError::InvalidTicket)?; + if !Arc::ptr_eq(epoch, &event.epoch) { + return Err(WorkError::InvalidTicket); + } + let state = epoch.state.load(Ordering::Acquire); + if state != IRQ_CLOSING && state != IRQ_JOINED { + return Err(WorkError::Pending); + } + if epoch.active.load(Ordering::Acquire) != 0 { + return Err(WorkError::WouldDeadlock); + } + epoch.pending.store(false, Ordering::Release); + epoch.state.store(IRQ_JOINED, Ordering::Release); + Ok(()) } - /// Ask the service task to finish. pub fn stop(&self) -> Result<(), WorkError> { self.stopping.store(true, Ordering::Release); @@ -411,7 +495,34 @@ unsafe extern "C" fn begin(context: *mut c_void) -> bool { unsafe extern "C" fn next_irq(context: *mut c_void) -> c_int { // SAFETY: the service call's context. let this = unsafe { environment::(context) }; - this.lines.take().map_or(-1, |line| line as c_int) + // SAFETY: this one original service task owns the table cursor/active slot. + let active = unsafe { &mut *this.active_irq.get() }; + assert!( + active.is_none(), + "previous IRQ service body did not complete" + ); + // SAFETY: same service CPU; process table mutations cannot interleave here. + for epoch in unsafe { &*this.lines.get() }.iter().flatten() { + if epoch.state.load(Ordering::Acquire) != IRQ_OPEN + || !epoch.pending.swap(false, Ordering::AcqRel) + { + continue; + } + epoch.active.fetch_add(1, Ordering::AcqRel); + *active = Some(epoch.clone()); + return epoch.line as c_int; + } + -1 +} + +unsafe extern "C" fn complete_irq(context: *mut c_void) { + // SAFETY: this original service call remains entered through primary return. + let this = unsafe { environment::(context) }; + // SAFETY: only the same service task owns this active epoch reference. + let epoch = unsafe { &mut *this.active_irq.get() } + .take() + .expect("active original IRQ service body"); + assert_eq!(epoch.active.fetch_sub(1, Ordering::AcqRel), 1); } unsafe extern "C" fn drain(context: *mut c_void) { @@ -472,6 +583,7 @@ unsafe extern "C" fn service(context: *mut c_void) { context, begin: begin::, next_irq: next_irq::, + complete_irq: complete_irq::, drain: drain::, finish: finish::, done: done::, diff --git a/crates/stela-linux/src/task/tests.rs b/crates/stela-linux/src/task/tests.rs index 286a5d6025..792c6d5bff 100644 --- a/crates/stela-linux/src/task/tests.rs +++ b/crates/stela-linux/src/task/tests.rs @@ -1168,6 +1168,9 @@ fn timer_service_roundtrip() { struct Machine { start: core::cell::OnceCell, environment: AtomicPtr>, + irq: Mutex>, + retired_irq: Mutex>, + irq_masked: AtomicBool, } impl Machine { @@ -1223,12 +1226,34 @@ impl Platform for Machine { unsafe fn unmap_pages(&self, _: *mut c_void, _: usize) { unreachable!(); } - fn irq_enable(&self, irq: u32) -> Result<(), Errno> { + fn irq_enable(&self, irq: u32) -> Result<(), crate::owner::IrqEnableError> { assert_eq!(irq, 7); + if self.irq.lock().unwrap().is_none() { + // SAFETY: exact synchronous software-only fixture source, with no + // hardware, root route or alternate native producer. + let event = unsafe { self.environment().irq_epoch(irq) }.unwrap(); + if let Some(old) = self.retired_irq.lock().unwrap().as_ref() { + assert_eq!(old.raise(), Err(WorkError::Closed)); + } + *self.irq.lock().unwrap() = Some(event); + } + self.irq_masked.store(false, Ordering::Release); Ok(()) } - fn irq_disable(&self, irq: u32) { + fn irq_disable(&self, irq: u32) -> Result<(), Errno> { assert_eq!(irq, 7); + self.irq_masked.store(true, Ordering::Release); + Ok(()) + } + fn irq_retire(&self, irq: u32) -> Result<(), Errno> { + assert_eq!(irq, 7); + let event = self.irq.lock().unwrap().take().unwrap(); + event.begin_close(); + // SAFETY: this fixture has no hardware route and its only synchronous + // software raiser is this owner task; C already joined actual IRQ work. + unsafe { self.environment().join_irq(&event) }.unwrap(); + *self.retired_irq.lock().unwrap() = Some(event); + Ok(()) } unsafe fn copy_from_user(&self, _: *mut u8, _: *const u8, _: usize) -> usize { unreachable!(); @@ -1249,12 +1274,23 @@ struct EnvironmentTest { owner: *const RawOwner, context: *mut c_void, raise: unsafe extern "C" fn(*mut c_void, u32), + masked: unsafe extern "C" fn(*mut c_void, u32) -> bool, } unsafe extern "C" fn raise_line(context: *mut c_void, line: u32) { // SAFETY: the test's machine, alive through the task. let machine = unsafe { &*context.cast::() }; - machine.environment().raise(line).unwrap(); + assert_eq!(line, 7); + assert!(!machine.irq_masked.load(Ordering::Acquire)); + let event = machine.irq.lock().unwrap().as_ref().unwrap().clone(); + event.raise().unwrap(); +} + +unsafe extern "C" fn line_masked(context: *mut c_void, line: u32) -> bool { + // SAFETY: exact retained synchronous controller peer of this fixture. + let machine = unsafe { &*context.cast::() }; + assert_eq!(line, 7); + machine.irq_masked.load(Ordering::Acquire) } struct ServicePressure { @@ -1326,6 +1362,7 @@ fn environment_roundtrip() { owner: owner.raw(), context: ptr::from_ref(owner.platform()).cast_mut().cast(), raise: raise_line, + masked: line_masked, }; // SAFETY: the body enters and leaves the owner, and `test` outlives it. let task = unsafe { @@ -2077,3 +2114,63 @@ fn mutex_quarantine_child() { assert_eq!(dropped.load(Ordering::Relaxed), 4); assert_eq!(quarantined(), 2); } + +/// Run a non-returning terminal C fixture on an actual hosted Runtime stack and +/// TaskBinding. Reuses the same guarded stacks and checked CPU as the task tests. +/// # Safety +/// Keep owner/body/context and all source/dev_id products live on the caller's +/// suspended frame. The body must terminate the isolated subprocess, never +/// unwind, return, escape its scoped task loan or install a native IRQ producer. +pub(crate) unsafe fn terminal_foreground( + owner: *const RawOwner, + body: unsafe extern "C" fn(*mut c_void), + context: *mut c_void, +) -> ! { + struct Call { + fixture: Arc, + owner: *const RawOwner, + body: unsafe extern "C" fn(*mut c_void), + context: *mut c_void, + } + unsafe extern "C" fn entered(context: *mut c_void) { + // SAFETY: the outer helper retains this exact stack-local Call and its + // actual owner/source roots throughout this non-returning task scope. + let call = unsafe { &*context.cast::() }; + // SAFETY: run_scoped already installed this Runtime's real task/current; + // the original caller retains the SAME owner through fatal reporting. + let _owner = unsafe { crate::owner::Entered::new(call.owner) }; + // SAFETY: caller's retained body/context and non-return/no-unwind contract. + unsafe { (call.body)(call.context) }; + std::process::exit(98); // a fixture return is never a successful trap + } + unsafe extern "C" fn foreground(context: *mut c_void) { + // SAFETY: helper retains Call and Queue's actual fixture through this job. + let call = unsafe { &*context.cast::() }; + let binding = call.fixture.binding(0); + // SAFETY: pinned executor/guarded stack, original fixture and body live + // through this actual scoped continuation; no owner is entered outside it. + unsafe { binding.run_scoped(call.fixture.runtime(), entered, context) }.unwrap(); + } + let cpu = CpuModel::new(); + let fixture = Fixture::new(cpu.clone()); + // SAFETY: this isolated thread owns the Queue and keeps its original fixture. + let queue = unsafe { Queue::<16>::new(cpu, fixture.clone()) }.unwrap(); + let dropped = Arc::new(AtomicU64::new(0)); + let executor = + Executor::new_hosted_for_test(queue, stacks_count(&dropped, 16 * 1024, 4)).unwrap(); + let runtime = executor.runtime(); + fixture.runtime.store( + runtime.get_ref() as *const Runtime<16> as *mut Runtime<16>, + Ordering::Release, + ); + let mut call = Call { + fixture, + owner, + body, + context, + }; + // SAFETY: the caller retains every borrowed source/owner/dev_id through the + // actual switched foreground stack. The bound body terminates this process. + unsafe { runtime.call_foreground(foreground, (&raw mut call).cast(), 10000) }.unwrap(); + std::process::exit(98); +}