fix(platform): preserve native IRQ and resident resource ownership

This commit is contained in:
Tyler Smith committed 2026-11-01 22:46:15 +00:00
1 parent 9b60cafdbb
commit 24352e48c8
113 files changed
+9135 -1400

No files matched your search

Generated
+2
View File
@@ -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",
]
+1
View File
@@ -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 }
+222 -15
View File
@@ -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<Self, IrqError> {
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<R: Registers, P: Platform> {
registers: R,
platform: P,
domain: Arc<dyn NotificationDomain>,
registry: RegistryIdentity,
version: u8,
id: u8,
gsi_base: u32,
pins: u16,
@@ -112,13 +124,18 @@ impl<R: Registers, P: Platform> Unit<R, P> {
/// 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<dyn NotificationDomain>,
registry: RegistryIdentity,
id: u8,
gsi_base: u32,
) -> Result<Arc<Self>, 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<R: Registers, P: Platform> Unit<R, P> {
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<R: Registers, P: Platform> Unit<R, P> {
Ok(Arc::new(Self {
registers,
platform,
domain,
registry,
version: version as u8,
id,
gsi_base,
pins,
@@ -264,6 +284,10 @@ impl<R: Registers, P: Platform> Unit<R, P> {
epoch,
target: None,
retired: true,
lifetime: Arc::new(PinLifetime {
phase: AtomicU8::new(CLAIMED),
failed: AtomicBool::new(false),
}),
})
}
}
@@ -290,6 +314,136 @@ pub struct Pin<R: Registers, P: Platform> {
epoch: u64,
target: Option<Target>,
retired: bool,
lifetime: Arc<PinLifetime>,
}
const CLAIMED: u8 = 0;
const PROGRAMMED: u8 = 1;
const RETIRED: u8 = 2;
const RELEASED: u8 = 3;
struct PinLifetime {
phase: AtomicU8,
failed: AtomicBool,
}
struct PinDomain<R: Registers, P: Platform> {
unit: ManuallyDrop<Arc<Unit<R, P>>>,
lifetime: ManuallyDrop<Arc<PinLifetime>>,
}
impl<R: Registers, P: Platform> Drop for PinDomain<R, P> {
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<R: Registers, P: Platform> NotificationDomain for PinDomain<R, P> {
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<R: Registers, P: Platform> {
unit: ManuallyDrop<Arc<Unit<R, P>>>,
lifetime: ManuallyDrop<Arc<PinLifetime>>,
pin: u8,
epoch: u64,
target: Target,
line: LineRoute,
}
impl<R: Registers, P: Platform> Drop for PinEoi<R, P> {
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<R: Registers, P: Platform> PinEoi<R, P> {
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<R: Registers, P: Platform> ChipEoi for PinEoi<R, P> {
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<R: Registers, P: Platform> Pin<R, P> {
/// Pre-bind a real parent mask endpoint in process context before callback
@@ -305,6 +459,7 @@ impl<R: Registers, P: Platform> Pin<R, P> {
unit: Arc::clone(&self.unit),
pin: self.pin,
epoch: self.epoch,
lifetime: self.lifetime.clone(),
})
}
}
@@ -315,6 +470,7 @@ pub struct ParentMask<R: Registers, P: Platform> {
unit: Arc<Unit<R, P>>,
pin: u8,
epoch: u64,
lifetime: Arc<PinLifetime>,
}
impl<R: Registers, P: Platform> ParentMask<R, P> {
/// Rearm the same claimed route after its deferred source has been drained.
@@ -329,6 +485,9 @@ impl<R: Registers, P: Platform> ParentMask<R, P> {
/// 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<R: Registers, P: Platform> 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<R: Registers, P: Platform> Source for Pin<R, P> {
unsafe impl<R: Registers + 'static, P: Platform + 'static> Source for Pin<R, P> {
fn notification_domain(&self) -> Result<Arc<dyn NotificationDomain>, 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<Option<Arc<dyn ChipEoi>>, 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<R: Registers, P: Platform> Source for Pin<R, P> {
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<R: Registers, P: Platform> Source for Pin<R, P> {
{
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<R: Registers, P: Platform> Source for Pin<R, P> {
}
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<R: Registers, P: Platform> Source for Pin<R, P> {
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<R: Registers, P: Platform> Drop for Pin<R, P> {
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 {
+370 -50
View File
@@ -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<Registry<Cpu>>,
vector: core::sync::atomic::AtomicU8,
domain_live: AtomicBool,
arming_old_edge: AtomicBool,
}
impl Board {
fn new() -> Arc<Self> {
@@ -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<Board>);
// 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<Board>);
// 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<bool, IrqError> {
Ok(self.0.hw.lock().unwrap().pending)
}
fn eoi(&self) {
self.0.hw.lock().unwrap().eoi();
fn eoi(&self, _: u8) -> Result<Trigger, IrqError> {
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<ParentMask<Io, Cpu>>);
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<dyn Handler> = 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<ParentMask<Io, Cpu>>);
@@ -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<dyn Handler> = Arc::new(Member(b.clone(), 1, false));
let second: Arc<dyn Handler> = 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<dyn stela_drivers::bus::irq::Source>) {
// 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);
}
+1
View File
@@ -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;
@@ -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<u64>,
image_bytes: usize,
alignment: u64,
virtual_base: u64,
) -> Result<Self, Error> {
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<u64> {
self.allocation.0..self.allocation.1
}
pub fn physical(self) -> Range<u64> {
self.physical..self.physical + self.bytes
}
pub fn virtual_range(self) -> Range<u64> {
self.virtual_base..self.virtual_base + self.bytes
}
pub fn overlaps(self, other: Range<u64>) -> 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)
);
}
}
}
+7
View File
@@ -1142,6 +1142,13 @@ impl<R: Registers> RequesterDomain<R> {
.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<bool, DmaError> {
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
+1
View File
@@ -1165,6 +1165,7 @@ dependencies = [
"stela-c-build",
"stela-crypto",
"stela-driver-base",
"stela-driver-core",
"zeroize",
]
+1 -1
View File
@@ -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"]
+15 -2
View File
@@ -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(())
}
}
+175 -91
View File
@@ -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<usize>);
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<Self> {
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<Msi>,
registration: Option<Box<dyn IrqRegistration>>,
retired: Option<stela_drivers::bus::irq::RetiredSource<dyn Source>>,
}
/// 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<Claimed>) -> 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<Claimed>) -> 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<Claimed>) -> 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);
+1 -1
View File
@@ -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;
@@ -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();
}
}
+1 -1
View File
@@ -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),
}
@@ -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<RootIdentity>,
_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<Reservation>,
ranges: Vec<Range<usize>>,
}
// 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<Reservation>,
bounds: Range<usize>,
@@ -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<Arc<ReadOnlyImage>, 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<dyn Cpu> {
self.cpu.clone()
+24 -5
View File
@@ -483,7 +483,7 @@ unsafe impl stela_drivers::bus::pci::requester::preparation::Root for ColdRoot {
unsafe fn bind(
&self,
binding: RequesterBinding,
) -> Result<Box<dyn stela_drivers::bus::pci::requester::preparation::Attachment>, DmaError>
) -> Result<Box<dyn stela_drivers::bus::pci::requester::preparation::AttachmentBackend>, 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<Option<Box<dyn stela_drivers::bus::irq::posted_msi::RouteOwner>>, 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<dyn DmaDomain> {
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))
})
}
}
@@ -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<Box<dyn Attachment>, DmaError> {
unsafe fn bind(
&self,
binding: RequesterBinding,
) -> Result<Box<dyn stela_drivers::bus::pci::requester::preparation::AttachmentBackend>, 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<Option<Box<dyn stela_drivers::bus::irq::posted_msi::RouteOwner>>, 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<dyn DmaDomain> {
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",
+10 -4
View File
@@ -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 {
+3
View File
@@ -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
+1
View File
@@ -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(
+211
View File
@@ -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<Self, Error> {
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<CodePin, Error> {
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<alloc::vec::Vec<core::ops::Range<usize>>, 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)
}
}
}
+54 -3
View File
@@ -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<u32, IrqError> {
Ok(if apic.is_x2apic() { raw } else { raw >> 24 })
}
fn in_service_vector(apic: &Apic) -> Result<Option<u8>, 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<Trigger, IrqError> {
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())
+133 -8
View File
@@ -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<Edu>,
}
// 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<Edu>,
message: Option<MsiMessage>,
}
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<MsiMessage, AllocationError> {
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<Arc<dyn posted_msi::NotificationDomain>, 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<Edu>) -> 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: _,
@@ -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<ioapic::Mmio, super::NativePlatform>;
@@ -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))?;
+10 -1
View File
@@ -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<dyn stela_drivers::bus::irq::posted_msi::NotificationDomain>,
) -> Result<Self, Error> {
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,
)
@@ -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,
@@ -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<dyn stela_drivers::bus::irq::posted_msi::NotificationDomain>,
>,
) -> Result<alloc::sync::Arc<dyn stela_drivers::bus::irq::posted_msi::NotificationDomain>, 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<dyn stela_drivers::bus::irq::posted_msi::NotificationDomain>,
) -> 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!(
+31 -4
View File
@@ -379,6 +379,7 @@ pub(crate) struct Source {
/// Each claimed ECAM bus, by its window and bus.
buses: core::cell::RefCell<Vec<Bus>>,
ioapics: core::cell::RefCell<Vec<(crate::native_irq::madt::Unit, Arc<IoapicUnit>)>>,
irq_domain: Option<Arc<dyn stela_drivers::bus::irq::posted_msi::NotificationDomain>>,
}
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<IoapicRegisters, crate::native_irq::NativePlatform>;
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<Arc<IoapicUnit>, 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)
}
+2
View File
@@ -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
+14 -9
View File
@@ -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<Framebuffer>,
pub apic_base: u64,
@@ -47,15 +48,6 @@ pub(super) fn prepare_image() -> Result<EngineImage> {
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<EngineImage> {
"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<EngineImage> {
snapshot,
image,
engine,
resident,
ram,
screen,
apic_base,
+2
View File
@@ -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" }
File diff suppressed because it is too large. Load diff
+403 -190
View File
@@ -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<Box<dyn DeliveryOwner>>,
message: Option<MsiMessage>,
binding_error: Option<Error>,
drained: Cell<bool>,
}
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<dyn DeliveryOwner>) -> 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<MsiMessage, AllocationError>;
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<Arc<dyn NotificationDomain>, 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<State>);
// 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<Option<Box<dyn RouteOwner>>>,
origin: Origin,
requester: Option<RequesterId>,
action_joined: bool,
route: Option<RouteId>,
message: Option<MsiMessage>,
published: bool,
domain: ManuallyDrop<Option<Arc<dyn NotificationDomain>>>,
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<Box<dyn RouteOwner>>,
) -> Result<Self, Error> {
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<dyn RouteOwner>) -> 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<MsiMessage, AllocationError> {
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<Arc<dyn NotificationDomain>, 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.
}
}
File diff suppressed because it is too large. Load diff
@@ -859,6 +859,14 @@ pub struct MappingView {
range: Range<usize>,
}
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<bool, Error> {
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
+17 -10
View File
@@ -202,9 +202,12 @@ impl<C: MsiConfigSpace> MsiConfig<C> {
/// 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<C>,
@@ -297,11 +300,13 @@ impl<C: MsiConfigSpace> MsiConfig<C> {
///
/// # 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<C: MsiConfigSpace> MsiConfig<C> {
/// 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<Released<C>, MsiError> {
self.disable()?;
self.owner.take().ok_or(MsiError::Released)
@@ -58,9 +58,12 @@ impl<C: MsiConfigSpace> DisabledMsiConfig<C> {
/// 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.
@@ -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);
}
+44 -20
View File
@@ -122,14 +122,31 @@ pub struct MsixConfig<C: MsiConfigSpace = EcamConfig, B: BarAccess = MappedBar>
open: bool,
poisoned: bool,
}
impl<B: BarAccess> MsixConfig<super::owned::OwnedConfig, B> {
/// 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<super::owned::ConfigRetention, Error> {
self.owners
.as_ref()
.ok_or(Error::Released)?
.0
.config
.retain_epoch()
.map_err(|_| Error::Mapping)
}
}
impl<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
/// # 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<C>,
@@ -348,7 +365,7 @@ impl<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
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<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
/// # 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<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
/// # 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<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
}
/// 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<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
/// 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<C: MsiConfigSpace, B: BarAccess> MsixConfig<C, B> {
}
/// 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<Owners<C, B>, Error> {
self.disable()?;
@@ -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());
}
@@ -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, MappingError> {
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<bool, MappingError> {
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<bool, MappingError> {
mapping.shares_authority(&self.view)
}
/// Compare kept permissions, never caller-supplied numeric IDs.
pub fn matches_mapping(&self, mapping: &Mapping) -> Result<bool, MappingError> {
mapping.shares_mapping(&self.view)
@@ -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;
@@ -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<Identity>);
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(())
}
}
@@ -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<DmaError> 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<dyn DmaDomain>;
/// 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<Option<Box<dyn crate::bus::irq::posted_msi::RouteOwner>>, 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<Box<dyn Attachment>, DmaError>;
unsafe fn bind(
&self,
binding: RequesterBinding,
) -> Result<Box<dyn AttachmentBackend>, 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<dyn Attachment>,
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) => {
@@ -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<RouteId>,
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<Option<Box<dyn AttachmentBackend>>>,
retention: ManuallyDrop<Option<Retention>>,
domain: ManuallyDrop<Arc<dyn DmaDomain>>,
requester: RequesterId,
retired: ManuallyDrop<Vec<RetiredRoute>>,
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<dyn AttachmentBackend>, 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<dyn AttachmentBackend>) -> 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<bool, DmaError> {
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<bool, DmaError> {
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<dyn DmaDomain> {
Arc::clone(&self.domain)
}
pub fn requester(&self) -> &RequesterId {
&self.requester
}
pub fn irq_route(&mut self) -> Result<MsiRoute, DmaError> {
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<DetachedRequester, DmaError> {
self.check()?;
self.validate_irq_actions()
.map_err(|_| DmaError::DrainUnavailable)?;
self.requester
.check_detach()
.map_err(|_| DmaError::DrainUnavailable)?;
let routes: Vec<RouteId> = 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.
}
}
@@ -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<Vec<irq_actions::Entry>>,
action_records: Mutex<Vec<u8>>,
action_pins_released: AtomicUsize,
}
struct RootOwner(Arc<State>);
impl Drop for RootOwner {
@@ -65,7 +70,10 @@ unsafe impl Root for OldRoot {
Ok(())
}
}
unsafe fn bind(&self, binding: RequesterBinding) -> Result<Box<dyn Attachment>, DmaError> {
unsafe fn bind(
&self,
binding: RequesterBinding,
) -> Result<Box<dyn crate::bus::pci::requester::preparation::AttachmentBackend>, 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<dyn DmaDomain> {
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<Option<Box<dyn crate::bus::irq::posted_msi::RouteOwner>>, 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;
@@ -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<u8>,
masked: bool,
cause: bool,
fenced: bool,
joined: bool,
}
struct ActionDomain {
pin: ConfigRetention,
domain: Arc<Domain>,
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<Domain>,
pin: Option<ConfigRetention>,
epoch: u64,
thread: std::thread::ThreadId,
vector: Option<u8>,
}
pub(super) fn owner(domain: Arc<Domain>) -> Result<Box<dyn irq::posted_msi::RouteOwner>, 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<irq::MsiMessage, irq::posted_msi::AllocationError> {
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<Arc<dyn irq::posted_msi::NotificationDomain>, 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<irq::Target, irq::IrqError> {
self.check_cpu()?;
Ok(irq::Target {
destination: 0,
vector,
})
}
fn pending(&self, _: u8) -> Result<bool, irq::IrqError> {
self.check_cpu()?;
Ok(false)
}
fn eoi(&self, _vector: u8) -> Result<crate::bus::irq::Trigger, crate::bus::irq::IrqError> {
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<State>,
requester: RequesterId,
number: u8,
}
impl EntrySource {
fn new(state: Arc<State>, 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<EntrySource>) {
// 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();
}
+15 -7
View File
@@ -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<R: Registers> ParentSource<R> {
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<R: Registers> Source for ParentSource<R> {
}
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<R: Registers> Source for ParentSource<R> {
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(())
}
+13 -8
View File
@@ -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.
@@ -28,7 +28,7 @@ struct FailedBinding<R: RetirableRegisters, T: Timer + 'static> {
}
pub(super) struct Bound<R: RetirableRegisters, T: Timer + 'static> {
pub requester: StoppedRequester,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
pub hardware: Hardware<R, T>,
pub profile: Profile,
pub firmware: firmware::Firmware,
@@ -15,7 +15,7 @@ use core::{mem::ManuallyDrop, ops::Deref};
struct Resources<R: RetirableRegisters, T: Timer + 'static> {
core: Aqtion<R, T>,
attachment: Box<dyn Attachment>,
attachment: Attachment,
retention: Option<ConfigRetention>,
configuration: Option<owned::Mapping>,
}
@@ -5,7 +5,7 @@ use crate::{
aqtion::native as adapter,
bus::pci::requester::{
FunctionRole, RequesterBinding,
preparation::{self, Attachment, Root},
preparation::{self, Root},
},
};
mod domain;
@@ -69,7 +69,10 @@ unsafe impl Root for OldRoot {
unsafe fn bind(
&self,
binding: RequesterBinding,
) -> core::result::Result<Box<dyn Attachment>, DmaError> {
) -> core::result::Result<
Box<dyn crate::bus::pci::requester::preparation::AttachmentBackend>,
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<dyn DmaDomain> {
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);
+1 -2
View File
@@ -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<OwnedConfig>,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
}
/// Failed finalization keeps the original root and BAR graph indefinitely.
@@ -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<Box<dyn Attachment>, DmaError> {
unsafe fn bind(
&self,
binding: RequesterBinding,
) -> Result<Box<dyn crate::bus::pci::requester::preparation::AttachmentBackend>, 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<dyn DmaDomain> {
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()
+3 -3
View File
@@ -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<R: Registers, D: Delay> {
hardware: Hardware<R, D>,
memory: Option<Memory>,
domain: Arc<dyn DmaDomain>,
attachment: Option<Box<dyn Attachment>>,
attachment: Option<Attachment>,
mac: Mac,
board: Option<super::transport::board::Board>,
carrier_up: bool,
@@ -148,7 +148,7 @@ impl<R: Registers, D: Delay> Packet<R, D> {
pub unsafe fn attach_bound(
hardware: Hardware<R, D>,
pages: &dyn PageSource,
attachment: Box<dyn Attachment>,
attachment: Attachment,
) -> Result<Self, (Error, Self)> {
// SAFETY: the caller supplies the same original stopped hardware,
// IRQ/work exclusion and unique attachment. Keep it through all errors.
@@ -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<dyn DmaDomain> {
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) }
+1
View File
@@ -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"]
@@ -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<C>,
pub registers: R,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
pub pages: Box<dyn PageSource>,
pub board: Board,
/// Original values read from this same requester's firmware node.
pub properties: Vec<(&'static str, Vec<u8>)>,
pub clock: T,
pub interrupts: &'static dyn IrqController,
pub msi_completion: MsiCompletion,
}
struct Allocator {
domain: Arc<dyn DmaDomain>,
@@ -180,7 +177,7 @@ struct ConfigurationState<C: Configuration> {
struct NativeSource<C: Configuration> {
config: Rc<RefCell<ConfigurationState<C>>>,
signals: Arc<Signals>,
delivery: Rc<RefCell<MsiCompletion>>,
requester: crate::bus::pci::requester::RequesterId,
}
impl<C: Configuration> NativeSource<C> {
fn checked(&self, result: Result<(), Error>, kind: irq::IrqError) -> Result<(), irq::IrqError> {
@@ -192,9 +189,10 @@ impl<C: Configuration> NativeSource<C> {
}
}
// 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<C: Configuration> Source for NativeSource<C> {
fn mask(&mut self) -> Result<(), irq::IrqError> {
let result = {
@@ -214,20 +212,26 @@ unsafe impl<C: Configuration> Source for NativeSource<C> {
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<R>,
domain: Option<Arc<dyn DmaDomain>>,
allocator: Option<Allocator>,
attachment: Option<Box<dyn Attachment>>,
attachment: Option<Attachment>,
retention: Option<ConfigRetention>,
quiesced: bool,
resources_attempted: bool,
@@ -269,7 +273,9 @@ pub struct NativePlatform<
registration: Option<Box<dyn IrqRegistration>>,
signals: Arc<Signals>,
mappings: Vec<Mapping>,
delivery: Option<Rc<RefCell<MsiCompletion>>>,
msi_route: Option<MsiRoute>,
requester: crate::bus::pci::requester::RequesterId,
irq_retirement: Option<irq::RetiredRoute>,
prepared: bool,
admission_attempted: bool,
retirement_attempted: bool,
@@ -368,6 +374,23 @@ impl<C: Configuration, R: Registers, T: Time> NativePlatform<C, R, T> {
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<C: Configuration, R: Registers, T: Time> NativePlatform<C, R, T> {
properties,
clock,
interrupts,
msi_completion,
} = inputs;
let domain = attachment.domain();
Ok(Self {
@@ -409,7 +431,9 @@ impl<C: Configuration, R: Registers, T: Time> NativePlatform<C, R, T> {
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<C: Configuration, R: Registers, T: Time> NativePlatform<C, R, T> {
// 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<C: Configuration, R: Registers, T: Time> NativePlatform<C, R, T> {
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<C: Configuration, R: Registers, T: Time> 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<C: Configuration, R: Registers, T: Time> 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<C: Configuration, R: Registers, T: Time> 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<C: Configuration, R: Registers, T: Time> Drop for NativePlatform<C, R, T> {
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<C: Configuration, R: Registers, T: Time> Drop for NativePlatform<C, R, T> {
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(..) {
@@ -30,7 +30,7 @@ pub(crate) unsafe trait Preparation: 'static {
}
pub(crate) struct Finalized<C: Configuration> {
pub function: Function<C>,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
}
pub(crate) struct FinalizeFailure {
pub error: preparation::Error,
@@ -81,7 +81,7 @@ pub(crate) struct Cold<P: Preparation, R: Registers, T: Time> {
}
pub(crate) struct Bound<C: Configuration, R: Registers, T: Time> {
pub function: Function<C>,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
pub topology: native_aspm::Topology<C>,
pub registers: R,
pub clock: T,
@@ -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<dyn DmaDomain> {
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<Option<Box<dyn irq::posted_msi::RouteOwner>>, 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<State>);
// 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<State>,
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<State>,
pin: Option<ConfigRetention>,
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<irq::MsiMessage, irq::posted_msi::AllocationError> {
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<Arc<dyn irq::posted_msi::NotificationDomain>, 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<State>);
// 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<crate::bus::irq::Trigger, crate::bus::irq::IrqError> {
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);
}
@@ -76,6 +76,7 @@ pub enum State {
Rom,
Iml,
Operational,
Closing,
Closed,
Failed,
}
@@ -242,7 +243,18 @@ impl<P: Platform> Transport<P> {
&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<P: Platform> Transport<P> {
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<P: Platform> Transport<P> {
}
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<P: Platform> Transport<P> {
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)
}
@@ -34,6 +34,12 @@ pub fn initialize<P: Platform>(
provider: &dyn Provider,
platform: intel::PlatformInputs,
) -> Result<Report, Error> {
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(),
@@ -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<C: MsiConfigSpace, B: BarAccess, R: Registers> {
pub clock: Clock,
pub interrupts: &'static dyn IrqController,
pub domain: Arc<dyn crate::bus::dma::mapping::DmaDomain>,
pub msi_completion: irq::posted_msi::MsiCompletion,
pub msi_route: irq::posted_msi::MsiRoute,
}
struct Signals<R: Registers> {
registers: R,
@@ -220,9 +218,8 @@ struct NativeSource<C: MsiConfigSpace, B: BarAccess, R: Registers> {
configuration: Rc<RefCell<Configuration<C, B>>>,
signals: Arc<Signals<R>>,
domain: Arc<dyn crate::bus::dma::mapping::DmaDomain>,
delivery: Rc<RefCell<irq::posted_msi::MsiCompletion>>,
requester: Option<crate::bus::pci::requester::RequesterId>,
programmed: bool,
drained: bool,
}
impl<C: MsiConfigSpace, B: BarAccess, R: Registers> NativeSource<C, B, R> {
fn checked(
@@ -239,8 +236,8 @@ impl<C: MsiConfigSpace, B: BarAccess, R: Registers> NativeSource<C, B, R> {
}
// 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<C: MsiConfigSpace, B: BarAccess, R: Registers> Source for NativeSource<C, B, R> {
fn mask(&mut self) -> core::result::Result<(), irq::IrqError> {
let result = self
@@ -254,7 +251,7 @@ unsafe impl<C: MsiConfigSpace, B: BarAccess, R: Registers> 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<C: MsiConfigSpace, B: BarAccess, R: Registers> 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<C: MsiConfigSpace, B: BarAccess, R: Registers> {
signals: Option<Arc<Signals<R>>>,
interrupts: &'static dyn IrqController,
domain: Option<Arc<dyn crate::bus::dma::mapping::DmaDomain>>,
delivery: Option<Rc<RefCell<irq::posted_msi::MsiCompletion>>>,
msi_route: Option<irq::posted_msi::MsiRoute>,
requester: Option<crate::bus::pci::requester::RequesterId>,
irq_retirement: Option<irq::RetiredRoute>,
clock: Clock,
clock_origin: u64,
registration: Option<Box<dyn IrqRegistration>>,
@@ -324,8 +329,10 @@ impl<C: MsiConfigSpace + 'static, B: BarAccess + 'static, R: Registers> 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<C: MsiConfigSpace + 'static, B: BarAccess + 'static, R: Registers> 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<C: MsiConfigSpace + 'static, B: BarAccess + 'static, R: Registers> NativePl
clock,
interrupts,
domain,
msi_completion,
msi_route,
},
));
}
@@ -437,7 +444,9 @@ impl<C: MsiConfigSpace + 'static, B: BarAccess + 'static, R: Registers> 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<C: MsiConfigSpace + 'static, B: BarAccess + 'static, R: Registers> 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<C: MsiConfigSpace + 'static, B: BarAccess + 'static, R: Registers> 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<C: MsiConfigSpace, B: BarAccess, R: Registers> Drop for NativePlatform<C, B
core::mem::forget(signals);
}
core::mem::forget(self.domain.take());
core::mem::forget(self.delivery.take());
core::mem::forget(self.msi_route.take());
core::mem::forget(self.irq_retirement.take());
}
// Successful physical retirement permits owner Drop. Owned mappings
// keep/quarantine their boot-lifetime native reservations.
@@ -665,6 +698,48 @@ unsafe impl RetirableRegisters for MappedRegisters {
impl<B: BarAccess + 'static, R: Registers>
NativePlatform<crate::bus::pci::owned::OwnedConfig, B, R>
{
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<irq::posted_msi::MsiRoute> {
self.msi_route.take()
}
fn take_retired_irq(&mut self) -> Option<irq::RetiredRoute> {
self.irq_retirement.take()
}
fn stop_requester(
&mut self,
seal: &crate::bus::pci::owned::ConfigRetention,
@@ -38,7 +38,7 @@ pub struct Cold<R: Registers> {
pub struct Bound<R: Registers> {
pub requester: StoppedRequester,
pub registers: R,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
}
/// Failed cold preparation never releases the original root/BAR graph.
pub struct Failure<R: Registers> {
@@ -25,12 +25,12 @@ pub enum DmaOperation {
pub struct Inputs<B: BarAccess + 'static, R: RetirableRegisters> {
pub platform: NativePlatform<OwnedConfig, B, R>,
pub allocator: DomainAllocator<'static>,
pub attachment: Box<dyn Attachment>,
pub attachment: Attachment,
pub retention: ConfigRetention,
}
struct Allocations {
allocator: DomainAllocator<'static>,
attachment: Box<dyn Attachment>,
attachment: Attachment,
retention: Option<ConfigRetention>,
}
struct AllocationOwner(Option<Box<Allocations>>);
@@ -85,10 +85,23 @@ impl<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
fn transport_mut(&mut self) -> &mut Transport<NativePlatform<OwnedConfig, B, R>> {
&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<alloc::vec::Vec<super::super::Packet>> {
self.admission()?;
self.transport_mut().poll()
}
pub fn send(
@@ -96,9 +109,11 @@ impl<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
kind: super::super::Kind,
bytes: &[u8],
) -> Result<super::super::TxReceipt> {
self.admission()?;
self.transport_mut().send(kind, bytes)
}
pub fn enter_d0(&mut self) -> Result<super::super::Snapshot> {
self.admission()?;
self.transport_mut().enter_d0()
}
pub fn initialize_firmware(
@@ -106,6 +121,12 @@ impl<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
provider: &dyn crate::firmware::Provider,
platform: crate::bluetooth::intel::PlatformInputs,
) -> core::result::Result<super::super::firmware::Report, super::super::firmware::Error> {
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<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
/// exclusions and the original processor/root context remain held.
pub unsafe fn new(inputs: Inputs<B, R>) -> core::result::Result<Self, Failure> {
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<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
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<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
.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<B: BarAccess + 'static, R: RetirableRegisters> OwnedTransport<B, R> {
match result {
Ok(()) => {
self.completed = true;
self.failure = None;
Ok(())
}
Err(error) => {
@@ -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<usize>,
write_error: Option<(usize, usize)>,
panic_write: Option<usize>,
byte_error: Option<usize>,
context: u64,
posted: BTreeMap<u16, u64>,
@@ -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::Image<'_>, 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);
}
@@ -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<u64>,
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<crate::bus::irq::Trigger, crate::bus::irq::IrqError> {
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<Inputs> {
},
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]
@@ -50,26 +50,77 @@ unsafe impl DmaDomain for Payload {
}
}
}
struct Delivery(Arc<Mutex<Hardware>>);
// 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<Mutex<Hardware>>,
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<Mutex<Hardware>>,
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<irq::MsiMessage, irq::posted_msi::AllocationError> {
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<Arc<dyn irq::posted_msi::NotificationDomain>, 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<Mutex<Hardware>>) -> irq::posted_msi::MsiCompletion {
irq::posted_msi::MsiCompletion::model(Box::new(Delivery(h)))
pub(super) fn completion(hardware: Arc<Mutex<Hardware>>) -> 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));
}
@@ -14,7 +14,7 @@ use crate::bus::{
owned::test_support::{Counters, fixture},
requester::{
FunctionRole, RequesterBinding,
preparation::{self, Attachment, Root},
preparation::{self, Root},
},
},
};
@@ -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);
@@ -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}");
}
}
@@ -5,6 +5,9 @@ pub(super) struct RootState {
pub events: Mutex<Vec<&'static str>>,
pub fail_config: Mutex<Option<Arc<Counters>>>,
pub fail: Mutex<Option<&'static str>>,
pub panic_phase: Mutex<Option<&'static str>>,
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<Box<dyn Attachment>, DmaError> {
) -> core::result::Result<
Box<dyn crate::bus::pci::requester::preparation::AttachmentBackend>,
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<dyn DmaDomain> {
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<dyn irq::Source>,
_: Arc<dyn irq::Handler>,
) -> core::result::Result<Box<dyn irq::IrqRegistration>, irq::IrqError> {
request: irq::Request<Box<dyn irq::Source>>,
) -> core::result::Result<Box<dyn irq::IrqRegistration>, 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<RootState>,
) -> (native::lifetime::Inputs<Bar, Registers>, Arc<Counters>) {
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 =
+49 -23
View File
@@ -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<dyn DmaDomain>,
pub interrupts: &'static dyn IrqController,
pub msi_route: irq::posted_msi::MsiRoute,
pub clock: T,
}
struct Signals {
@@ -152,8 +151,9 @@ struct NativeSource<C: Configuration, R: Registers> {
shared: Arc<Shared<R>>,
}
// 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<C: Configuration, R: Registers> Source for NativeSource<C, R> {
fn mask(&mut self) -> core::result::Result<(), irq::IrqError> {
let result = (|| {
@@ -177,11 +177,17 @@ unsafe impl<C: Configuration, R: Registers> Source for NativeSource<C, R> {
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<Arc<Shared<R>>>,
config: Option<Rc<RefCell<ConfigState<C>>>>,
registration: Option<Box<dyn IrqRegistration>>,
msi_route: Option<irq::posted_msi::MsiRoute>,
interrupts: &'static dyn IrqController,
clock: T,
engine: Engine,
@@ -259,6 +266,10 @@ impl<C: Configuration, R: Registers, T: Time> Native<C, R, T> {
/// 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<C, R, T>,
) -> core::result::Result<Self, (Error, Inputs<C, R, T>)> {
@@ -337,6 +348,7 @@ impl<C: Configuration, R: Registers, T: Time> Native<C, R, T> {
registers,
domain,
interrupts,
msi_route,
clock,
} = inputs;
Ok(Self {
@@ -356,6 +368,7 @@ impl<C: Configuration, R: Registers, T: Time> Native<C, R, T> {
})),
config: None,
registration: None,
msi_route: Some(msi_route),
interrupts,
clock,
engine: Engine::new(),
@@ -529,18 +542,28 @@ impl<C: Configuration, R: Registers, T: Time> Native<C, R, T> {
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<C: Configuration, R: Registers, T: Time> Native<C, R, T> {
// 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<C: Configuration, R: Registers, T: Time> Drop for Native<C, R, T> {
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);
}
+86 -1
View File
@@ -656,12 +656,85 @@ unsafe impl DmaDomain for Domain {
}
}
}
struct NotificationPeer {
peer: Arc<Peer>,
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<Peer>,
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<irq::MsiMessage, irq::posted_msi::AllocationError> {
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<Arc<dyn irq::posted_msi::NotificationDomain>, 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<Peer>);
// 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<bool, irq::IrqError> {
Ok(false)
}
fn eoi(&self) {
fn eoi(
&self,
_vector: u8,
) -> core::result::Result<crate::bus::irq::Trigger, crate::bus::irq::IrqError> {
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,
+38 -6
View File
@@ -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
@@ -6,7 +6,7 @@ pub(super) enum Requester {
Preparing(PreparingRequester),
Bound {
pci: Function<OwnedConfig>,
attachment: Box<dyn preparation::Attachment>,
attachment: preparation::Attachment,
},
Retired {
pci: Function<OwnedConfig>,
+6 -1
View File
@@ -37,6 +37,9 @@ struct Owner {
// Neither a replacement domain nor HCRST certifies old-route retirement.
resources: RefCell<ManuallyDrop<Resources>>,
register_failure: Rc<Cell<Option<usize>>>,
// Keep the exact retired action/source/route graph through subsequent
// device work; IRQ action retirement does not release endpoint resources.
retired_irq: RefCell<Option<crate::bus::irq::RetiredSource<dyn crate::bus::irq::Source>>>,
}
struct Access(Rc<Owner>);
@@ -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 {
+2 -1
View File
@@ -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"] }
+20
View File
@@ -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"),
+378
View File
@@ -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<String>,
}
impl FirmwareTarget {
pub fn new(
driver: String,
hardware: String,
revision: String,
board: Option<String>,
) -> Result<Self, Error> {
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<Attachment>,
requester: RequesterId,
}
impl FunctionCustody {
pub fn new(attachment: Attachment) -> Rc<Self> {
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<R>(
&self,
operation: impl FnOnce(&mut Attachment) -> R,
) -> Result<R, Error> {
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<Self>) -> Result<Attachment, Rc<Self>> {
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<FunctionCustody>,
requester: RequesterId,
target: FirmwareTarget,
catalog: Arc<Catalog>,
}
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<P: super::owner::Platform, const N: usize>(
kernel: &super::kernel::KernelOwner<P, N>,
source: Rc<FunctionCustody>,
original: &OwnedConfig,
target: FirmwareTarget,
catalog: Arc<Catalog>,
) -> Result<Self, Error> {
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<Arc<dyn stela_driver_base::bus::dma::mapping::DmaDomain>, 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<Catalog>,
_execution: super::kernel::ExecutionPin,
}
pub enum Authority {
Pci(PciAuthority),
GlobalRegulatory(GlobalAuthority),
}
impl Authority {
pub(crate) fn global_regulatory(
target: FirmwareTarget,
catalog: Arc<Catalog>,
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::<Authority>()) });
}
/// # 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<Authority>,
) -> Result<(), (Box<Authority>, 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<Self, Error> {
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::<Authority>())
.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));
}
}
}
@@ -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 <linux/device.h>
#include <linux/errno.h>
#include <linux/kobject.h>
#include <linux/list.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <stela/catalogue.h>
#include <stela/linux.h>
#include <stela/pci.h>
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 <linux/pci.h>
#include <stela/test.h>
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 <stela/test.h>
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 <stela/test.h>
#include <stela/task.h>
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 <linux/workqueue.h>
#include <stela/test.h>
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
+14 -1
View File
@@ -12,11 +12,15 @@
#include <linux/property.h>
#include <linux/slab.h>
#include <stela/device.h>
#include <stela/catalogue.h>
#include <unsupported.h>
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);
+185 -32
View File
@@ -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 <linux/interrupt.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <stela/atomic_callback.h>
#include <stela/irq.h>
#include <stela/linux.h>
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);
+2 -1
View File
@@ -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 <stela/catalogue.h>
#include <linux/bug.h>
#include <linux/irqflags.h>
#include <linux/panic.h>
@@ -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,
+101
View File
@@ -17,6 +17,7 @@
#include <linux/sched/task_stack.h>
#include <stela/linux.h>
#include <stela/page.h>
#include <stela/task.h>
#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)<<PAGE_SHIFT)};
return 0;
}
int stela_linux_page_mapping_unpin(u64 generation, const void *context,
const struct stela_linux_owner *owner, void *token)
{
int error=stela_linux_page_owner_context(owner);
if (error) return error;
if (!catalog.pages || generation!=catalog.generation || context!=catalog.context)
return -EINVAL;
unsigned long address=(unsigned long)token, base=(unsigned long)catalog.allocations;
size_t bytes=catalog.page_count*sizeof(*catalog.allocations);
if (address<base || address-base>=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);
+13 -3
View File
@@ -10,6 +10,7 @@
#include <linux/slab.h>
#include <stela/device.h>
#include <stela/pci.h>
#include <stela/catalogue.h>
#include <unsupported.h>
/* 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)));
@@ -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};
@@ -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<STELA_LINUX_STAGE_DONE;++stage)
assert(stela_linux_registry_run_stage(test_registry,stage,NULL)==
(stage==STELA_LINUX_STAGE_FS ? expected : 0));
/* The actual registry continues into5s on failure; the explicit prerequisite
* is what prevents a source-owned hook from borrowing a destroyed object. */
assert(dependency_hooks==1 && dependency_borrows==(dependency_result ? 0U : 1U));
assert(stela_linux_registry_require_success(test_registry,&f.image,dependency_record)==expected);
stela_linux_exit();
}
static void dependency_success_case(void) { dependency_result=0; dependency_case(); }
static void dependency_failure_case(void) { dependency_result=-ENOMEM; dependency_case(); }
static void dependency_positive_case(void) { dependency_result=3; dependency_case(); }
#include <stela/registry_setup_test.h>
int main(void)
{
for(setup_differential_index=0;setup_differential_index<ARRAY_SIZE(setup_differential_inputs);++setup_differential_index)
assert(stela_test_registry_case(setup_differential_case));
assert(stela_test_registry_case(dependency_success_case));
assert(stela_test_registry_case(dependency_failure_case));
assert(stela_test_registry_case(dependency_positive_case));
assert(stela_test_registry_case(lifecycle_case));
assert(stela_test_registry_case(ordering_case));
assert(stela_test_registry_case(option_case));
@@ -67,8 +67,10 @@ void stela_linux_service_loop(const struct stela_linux_service_call *call)
stela_linux_atomic_process_leaf_begin(&leaf);
call->drain(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();
@@ -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 <stela/catalogue.h>
#include <linux/errno.h>
#include <linux/irqflags.h>
#include <linux/limits.h>
@@ -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;
@@ -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 <stela/catalogue.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/sprintf.h>
@@ -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;
@@ -0,0 +1,36 @@
/* SPDX-License-Identifier: MIT */
#ifndef STELA_LINUX_CATALOGUE_H
#define STELA_LINUX_CATALOGUE_H
#include <linux/types.h>
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
@@ -1,7 +1,9 @@
/* SPDX-License-Identifier: MIT */
#ifndef STELA_IRQ_H
#define STELA_IRQ_H
#include <linux/types.h>
/* 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
+10 -6
View File
@@ -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");
@@ -2,6 +2,9 @@
#ifndef STELA_PAGE_H
#define STELA_PAGE_H
#include <linux/types.h>
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);
+13 -7
View File
@@ -3,9 +3,10 @@
#define STELA_PCI_H
#include <linux/pci.h>
/* 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);
@@ -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.
@@ -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);
@@ -7,6 +7,7 @@
#include <linux/workqueue.h>
#include <stela/atomic_callback.h>
#include <stela/linux.h>
#include <stela/irq.h>
#include <stela/test.h>
#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();
}
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff. Show more