feat(drivers): reserve protected pending GPE admission

This commit is contained in:
Tyler Smith committed 2026-10-29 01:36:45 +00:00
1 parent 62a0258097
commit cab69a0c0d
6 files changed
+307 -27

No files matched your search

@@ -320,8 +320,7 @@ fn aml() -> Vec<u8> {
checksum(&mut dsdt, 9);
dsdt
}
#[test]
fn actual_aml_wait_signal_keeps_portal_notify_and_gpe_progress_with_general_parked() {
fn run_wait_signal(policy: work::ReservationPolicy) {
let _serial = TEST_SERIAL.lock().unwrap();
assert_eq!(CURRENT.load(Ordering::Acquire), 0);
SEMAPHORES.store(0, Ordering::Release);
@@ -349,7 +348,8 @@ fn actual_aml_wait_signal_keeps_portal_notify_and_gpe_progress_with_general_park
units: AtomicU32::new(0),
}),
});
let (executor, cpu, dropped) = work::test_support::executor::<32>(scene.clone());
let (executor, cpu, dropped) =
work::test_support::executor_with_policy::<32>(scene.clone(), policy);
let r = executor.runtime();
scene.runtime.store(
r.get_ref() as *const work::Runtime<32> as u64,
@@ -425,3 +425,14 @@ fn actual_aml_wait_signal_keeps_portal_notify_and_gpe_progress_with_general_park
assert_eq!(counts.allocations.load(Ordering::SeqCst), 0);
assert_eq!(counts.mappings.load(Ordering::SeqCst), 0);
}
#[test]
fn actual_aml_wait_signal_keeps_portal_notify_and_gpe_progress_with_general_parked() {
run_wait_signal(work::ReservationPolicy::NativeFirmware16);
}
#[test]
fn protected_gpe_policy_keeps_actual_aml_wait_signal_progress_with_general_parked() {
run_wait_signal(work::ReservationPolicy::NativeFirmware16Protected {
gpe: work::GpeQueueBudget::QUALIFICATION,
});
}
+14 -6
View File
@@ -40,7 +40,7 @@ mod reservation;
#[cfg(all(test, unix, target_arch = "x86_64"))]
pub(crate) mod test_support;
use reservation::Layout;
pub use reservation::{FirmwareQueue, FirmwareRole, ReservationPolicy};
pub use reservation::{FirmwareQueue, FirmwareRole, GpeQueueBudget, ReservationPolicy};
pub type Callback = unsafe extern "C" fn(*mut c_void);
pub type RetainedOwner = Arc<dyn Any + Send + Sync>;
@@ -853,7 +853,7 @@ impl<const N: usize> Runtime<N> {
// Native worker permits require an empty pre-admission queue: a
// legacy Notify job in an ordinary slot otherwise bypasses the two
// real-worker limit. Legacy constructors keep their prior contract.
if (layout == Layout::NativeFirmware16 && state.jobs.iter().any(Option::is_some))
if (layout.native16() && state.jobs.iter().any(Option::is_some))
|| state.jobs[N - layout.slots()..].iter().any(Option::is_some)
{
return Err(WorkError::Busy);
@@ -1601,6 +1601,16 @@ impl<const N: usize> Runtime<N> {
})
}
}
/// Observe the actual constructor's protected GPE admission budget.
/// None means the legacy layout has no protected pending guarantee. This
/// copy neither synchronizes IRQs nor grants provider/progress authority.
pub fn protected_gpe_budget(&self) -> Result<Option<GpeQueueBudget>, WorkError> {
self.queue.process()?;
if self.retired.get() || self.queue.abandoned.load(Ordering::Acquire) {
return Err(WorkError::Closed);
}
Ok(self.layout.protected_gpe())
}
/// Check actual CPU/policy/lifetime/current-role eligibility for a firmware
/// queue join before a caller mutates C handler state. This does not capture
/// a flush boundary, run/accept work, attest progress or synchronize an IRQ.
@@ -1610,7 +1620,7 @@ impl<const N: usize> Runtime<N> {
if self.retired.get() || self.queue.abandoned.load(Ordering::Acquire) {
return Err(WorkError::Closed);
}
if self.layout != Layout::NativeFirmware16 {
if !self.layout.native16() {
return Err(WorkError::Unavailable);
}
let current = self.current.get();
@@ -1945,9 +1955,7 @@ impl<const N: usize> Executor<N> {
policy: ReservationPolicy,
) -> Result<Self, WorkError> {
Runtime::<N>::validate_stacks(&queue, &stacks)?;
let layout = match policy {
ReservationPolicy::NativeFirmware16 => Layout::NativeFirmware16,
};
let layout = policy.layout();
layout.validate(stacks.len(), N)?;
// SAFETY: same qualified native construction boundary as new().
let controls = unsafe { context::controls()? };
@@ -9,6 +9,43 @@ use core::ops::Range;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ReservationPolicy {
NativeFirmware16,
/// Same sixteen stack roles, with independently reserved pending GPE jobs.
NativeFirmware16Protected {
gpe: GpeQueueBudget,
},
}
/// Preallocated GPE admission budget: one active job plus protected pending jobs.
/// This is a resource bound, not SCI synchronization or a provider capability.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GpeQueueBudget {
pending: usize,
}
impl GpeQueueBudget {
/// Bounded qualification minimum: one active and one protected pending job.
pub const QUALIFICATION: Self = Self { pending: 1 };
pub fn with_pending(pending: usize) -> Result<Self, WorkError> {
if pending == 0 {
return Err(WorkError::Unavailable);
}
pending.checked_add(16).ok_or(WorkError::Exhausted)?;
Ok(Self { pending })
}
pub const fn protected_pending(self) -> usize {
self.pending
}
pub const fn total_jobs(self) -> usize {
self.pending + 1
}
}
#[cfg(target_arch = "x86_64")]
impl ReservationPolicy {
pub(super) fn layout(self) -> Layout {
match self {
Self::NativeFirmware16 => Layout::NativeFirmware16,
Self::NativeFirmware16Protected { gpe } => Layout::NativeFirmware16Protected(gpe),
}
}
}
/// Independently flushed OSL workqueues. Neither queue includes ordinary AML,
/// Linux service/control work or General callbacks.
@@ -46,13 +83,31 @@ pub(super) enum Layout {
LinuxService,
FirmwareControl,
NativeFirmware16,
NativeFirmware16Protected(GpeQueueBudget),
}
impl Layout {
pub(super) fn native16(self) -> bool {
matches!(
self,
Self::NativeFirmware16 | Self::NativeFirmware16Protected(_)
)
}
pub(super) fn protected_gpe(self) -> Option<GpeQueueBudget> {
match self {
Self::NativeFirmware16Protected(gpe) => Some(gpe),
_ => None,
}
}
fn pending_gpe(self) -> usize {
self.protected_gpe()
.map_or(0, GpeQueueBudget::protected_pending)
}
pub(super) fn slots(self) -> usize {
match self {
Self::Ordinary | Self::LinuxService => 0,
Self::FirmwareControl => 2,
Self::NativeFirmware16 => 8,
Self::NativeFirmware16Protected(gpe) => 8 + gpe.protected_pending(),
}
}
#[cfg(target_arch = "x86_64")]
@@ -62,6 +117,9 @@ impl Layout {
Self::LinuxService => stacks >= 5,
Self::FirmwareControl => stacks >= 6 && jobs >= 3,
Self::NativeFirmware16 => stacks == 16 && jobs >= 16,
Self::NativeFirmware16Protected(gpe) => {
stacks == 16 && jobs >= 16 + gpe.protected_pending()
}
};
if valid {
Ok(())
@@ -75,22 +133,22 @@ impl Layout {
0 => Lane::Foreground,
1 => Lane::Notify,
2 if self != Self::Ordinary => Lane::Service,
3 if matches!(self, Self::FirmwareControl | Self::NativeFirmware16) => Lane::Firmware,
4 if self == Self::NativeFirmware16 => Lane::Gpe,
5 | 6 if self == Self::NativeFirmware16 => Lane::Portal,
7 if self == Self::NativeFirmware16 => Lane::Notify,
3 if self == Self::FirmwareControl || self.native16() => Lane::Firmware,
4 if self.native16() => Lane::Gpe,
5 | 6 if self.native16() => Lane::Portal,
7 if self.native16() => Lane::Notify,
_ => Lane::General,
}
}
#[cfg(target_arch = "x86_64")]
pub(super) fn role(self, lane: Lane) -> Option<FirmwareRole> {
match lane {
Lane::Firmware if matches!(self, Self::FirmwareControl | Self::NativeFirmware16) => {
Lane::Firmware if self == Self::FirmwareControl || self.native16() => {
Some(FirmwareRole::Control)
}
Lane::Portal if self == Self::NativeFirmware16 => Some(FirmwareRole::PortalAml),
Lane::Gpe if self == Self::NativeFirmware16 => Some(FirmwareRole::Gpe),
Lane::Notify if self == Self::NativeFirmware16 => Some(FirmwareRole::Notify),
Lane::Portal if self.native16() => Some(FirmwareRole::PortalAml),
Lane::Gpe if self.native16() => Some(FirmwareRole::Gpe),
Lane::Notify if self.native16() => Some(FirmwareRole::Notify),
_ => None,
}
}
@@ -99,10 +157,11 @@ impl Layout {
/// callback/context transfer. Completion releases the slot and marks its
/// worker Idle in one IF0 return path, without an intervening producer.
/// Foreground has its own slot too; General traffic cannot consume it.
/// GPE is serial and may queue into spare ordinary slots after its reserved
/// slot; it never borrows an ordinary continuation or a portal/Notify slot.
/// GPE is serial. The original Native16 policy may use spare ordinary job
/// slots; the protected policy uses only its named fixed GPE budget. Neither
/// borrows an ordinary continuation or a portal/Notify job slot.
pub(super) fn admission(self, lane: Lane, jobs: usize) -> Result<[Range<usize>; 2], WorkError> {
if matches!(lane, Lane::Portal | Lane::Gpe) && self != Self::NativeFirmware16 {
if matches!(lane, Lane::Portal | Lane::Gpe) && !self.native16() {
return Err(WorkError::Unavailable);
}
let reserved = self.slots();
@@ -111,13 +170,13 @@ impl Layout {
}
let start = jobs - reserved;
let primary = match self {
Self::NativeFirmware16 => match lane {
Self::NativeFirmware16 | Self::NativeFirmware16Protected(_) => match lane {
Lane::Service => start..start + 1,
Lane::Firmware => start + 1..start + 2,
Lane::Gpe => start + 2..start + 3,
Lane::Portal => start + 3..start + 5,
Lane::Notify => start + 5..start + 7,
Lane::Foreground => start + 7..jobs,
Lane::Gpe => start + 2..start + 3 + self.pending_gpe(),
Lane::Portal => start + 3 + self.pending_gpe()..start + 5 + self.pending_gpe(),
Lane::Notify => start + 5 + self.pending_gpe()..start + 7 + self.pending_gpe(),
Lane::Foreground => start + 7 + self.pending_gpe()..jobs,
_ => 0..start,
},
Self::FirmwareControl => match lane {
@@ -123,6 +123,12 @@ pub(crate) fn stacks(dropped: &Arc<AtomicUsize>) -> Vec<Stack> {
}
pub(crate) fn executor<const N: usize>(
owner: RetainedOwner,
) -> (Executor<N>, Arc<CpuModel>, Arc<AtomicUsize>) {
executor_with_policy(owner, ReservationPolicy::NativeFirmware16)
}
pub(crate) fn executor_with_policy<const N: usize>(
owner: RetainedOwner,
policy: ReservationPolicy,
) -> (Executor<N>, Arc<CpuModel>, Arc<AtomicUsize>) {
let cpu = CpuModel::new();
// SAFETY: caller retains the actual fixture state via this queue's owner;
@@ -134,8 +140,7 @@ pub(crate) fn executor<const N: usize>(
// SAFETY: unprivileged snapshot of this x86 hosted thread's real x87/SSE
// controls. No native CPL0/IRQ/provider admission is inferred from it.
let controls = unsafe { context::read_controls() };
let runtime =
Runtime::with_layout_controls(queue, stacks, controls, Layout::NativeFirmware16).unwrap();
let runtime = Runtime::with_layout_controls(queue, stacks, controls, policy.layout()).unwrap();
(
Executor {
runtime: ManuallyDrop::new(runtime),
@@ -715,3 +715,5 @@ fn minimum_sixteen_slot_queue_reserves_foreground_after_general_saturation() {
assert_eq!(dropped.load(Ordering::Relaxed), 16);
assert_eq!(cpu.flags(), 0x202);
}
mod protected_gpe;
@@ -0,0 +1,195 @@
//! Protected GPE admission is independent from General queue pressure.
use super::*;
fn policy(budget: GpeQueueBudget) -> ReservationPolicy {
ReservationPolicy::NativeFirmware16Protected { gpe: budget }
}
fn failed_construction<const N: usize>(queued: bool, expected: WorkError) {
let count = Arc::new(core::sync::atomic::AtomicUsize::new(0));
let cpu = test_support::CpuModel::new();
// SAFETY: this same-thread modeled queue retains the actual atomic context.
let queue = unsafe { Queue::<N>::new(cpu.clone(), count.clone()) }.unwrap();
let p = Arc::as_ptr(&count) as *mut c_void;
let ticket = if queued {
// SAFETY: the queue owns count through the subsequent legacy executor join.
Some(unsafe { queue.execute(Kind::Notify, count_queued, p) }.unwrap())
} else {
None
};
let dropped = Arc::new(core::sync::atomic::AtomicUsize::new(0));
let stacks = test_support::stacks(&dropped);
Runtime::validate_stacks(&queue, &stacks).unwrap();
// SAFETY: an unprivileged real x87/SSE snapshot, with no native grant.
let controls = unsafe { context::read_controls() };
let result = Runtime::with_layout_controls(
queue.clone(),
stacks,
controls,
policy(GpeQueueBudget::QUALIFICATION).layout(),
);
assert!(matches!(result,Err(error) if error==expected));
assert_eq!(dropped.load(Ordering::Relaxed), 16);
assert!(!queue.executor_claimed.load(Ordering::Acquire));
assert_eq!(queue.lock().unwrap().state().layout, Layout::Ordinary);
if let Some(ticket) = ticket {
assert_eq!(queue.completed(ticket), Ok(false));
}
assert_eq!(count.load(Ordering::Relaxed), 0);
let runtime =
Runtime::with_controls(queue.clone(), test_support::stacks(&dropped), controls).unwrap();
let executor = Executor {
runtime: ManuallyDrop::new(runtime),
};
assert_eq!(executor.runtime().protected_gpe_budget(), Ok(None));
queue.close().unwrap();
executor
.runtime()
.drain(cpu.ticks() + 1_000_000_000)
.unwrap();
assert_eq!(count.load(Ordering::Relaxed), usize::from(queued));
// SAFETY: no fixture producer exists and every admitted callback joined.
unsafe { executor.runtime().retire() }.unwrap();
drop(executor);
assert_eq!(dropped.load(Ordering::Relaxed), 32);
assert_eq!(cpu.flags(), 0x202);
}
#[test]
fn protected_budget_and_construction_reject_invalid_geometry_without_taking_jobs() {
assert_eq!(GpeQueueBudget::with_pending(0), Err(WorkError::Unavailable));
assert_eq!(
GpeQueueBudget::with_pending(usize::MAX),
Err(WorkError::Exhausted)
);
assert_eq!(GpeQueueBudget::QUALIFICATION.total_jobs(), 2);
assert_eq!(GpeQueueBudget::QUALIFICATION.protected_pending(), 1);
failed_construction::<16>(false, WorkError::Unavailable);
failed_construction::<17>(true, WorkError::Busy);
}
fn full_admission<const N: usize>(budget: GpeQueueBudget, general_capacity: usize) {
let count = Arc::new(core::sync::atomic::AtomicUsize::new(0));
let (executor, cpu, dropped) =
test_support::executor_with_policy::<N>(count.clone(), policy(budget));
let r = executor.runtime();
assert_eq!(r.protected_gpe_budget(), Ok(Some(budget)));
let p = Arc::as_ptr(&count) as *mut c_void;
for _ in 0..budget.total_jobs() {
// SAFETY: all accepted callbacks borrow the queue-retained atomic allocation.
unsafe { r.queue.execute_gpe(count_queued, p) }.unwrap();
}
assert_eq!(
// SAFETY: Full transfers nothing, even though all ordinary slots are still free.
unsafe { r.queue.execute_gpe(count_queued, p) },
Err(WorkError::Full)
);
for _ in 0..general_capacity {
// SAFETY: every General callback retains this exact atomic context through join.
unsafe { r.queue.execute(Kind::General, count_queued, p) }.unwrap();
}
assert_eq!(
// SAFETY: ordinary overflow must not borrow a reserved role or GPE slot.
unsafe { r.queue.execute(Kind::General, count_queued, p) },
Err(WorkError::Full)
);
// SAFETY: queue-owned counter remains valid through each role's real completion.
unsafe { r.start_service(count_queued, p) }.unwrap();
// SAFETY: the independent control frame borrows the same retained counter.
unsafe { r.start_firmware(count_queued, p) }.unwrap();
for _ in 0..2 {
// SAFETY: each accepted Portal owns a distinct actual continuation permit.
unsafe { r.queue.execute_portal(count_queued, p) }.unwrap();
// SAFETY: each accepted Notify owns a distinct actual continuation permit.
unsafe { r.queue.execute(Kind::Notify, count_queued, p) }.unwrap();
}
assert_eq!(count.load(Ordering::Relaxed), 0);
// SAFETY: the protected Foreground slot/context survive all peer stack exchanges.
unsafe { r.call_foreground(count_queued, p, cpu.ticks() + 1_000_000_000) }.unwrap();
r.drain(cpu.ticks() + 1_000_000_000).unwrap();
assert_eq!(count.load(Ordering::Relaxed), N);
// SAFETY: no producer remains and every admitted job actually returned.
unsafe { r.retire() }.unwrap();
assert_eq!(r.protected_gpe_budget(), Err(WorkError::Closed));
assert_eq!(
r.check_firmware_join(FirmwareQueue::Gpe),
Err(WorkError::Closed)
);
drop(executor);
assert_eq!(dropped.load(Ordering::Relaxed), 16);
assert_eq!(cpu.flags(), 0x202);
}
#[test]
fn minimum_seventeen_and_actual_sixty_four_slot_queues_keep_all_roles_admissible() {
full_admission::<17>(GpeQueueBudget::QUALIFICATION, 8);
full_admission::<64>(GpeQueueBudget::QUALIFICATION, 55);
}
#[test]
fn a_larger_named_gpe_budget_remains_fixed_even_with_spare_general_capacity() {
let budget = GpeQueueBudget::with_pending(3).unwrap();
assert_eq!(budget.total_jobs(), 4);
full_admission::<19>(budget, 8);
}
#[test]
fn a_pending_gpe_keeps_its_own_slot_under_full_general_admission_and_stack_saturation() {
let f = Scene::new();
let (executor, cpu, dropped) =
test_support::executor_with_policy::<32>(f.clone(), policy(GpeQueueBudget::QUALIFICATION));
let r = executor.runtime();
f.runtime
.store(r.get_ref() as *const Runtime<32> as u64, Ordering::Release);
let p = Arc::as_ptr(&f) as *mut c_void;
for _ in 0..8 {
// SAFETY: all blocking General frames retain Scene until explicit release.
unsafe { r.queue.execute(Kind::General, general, p) }.unwrap();
}
for _ in 0..15 {
// SAFETY: queued General markers borrow the same retained Scene and do not rebind.
unsafe { r.queue.execute(Kind::General, ordinary_turn, p) }.unwrap();
}
assert_eq!(
// SAFETY: all23 ordinary admission entries are occupied; rejection transfers nothing.
unsafe { r.queue.execute(Kind::General, rejected, p) },
Err(WorkError::Full)
);
// SAFETY: all role callbacks are covered by Scene's retained allocation.
unsafe { r.start_service(service, p) }.unwrap();
// SAFETY: the dedicated control context remains live while parked.
unsafe { r.start_firmware(control, p) }.unwrap();
for _ in 0..2 {
// SAFETY: each portal context survives its actual parked frame.
unsafe { r.queue.execute_portal(portal, p) }.unwrap();
// SAFETY: each Notify context survives its actual parked frame.
unsafe { r.queue.execute(Kind::Notify, notify, p) }.unwrap();
}
// SAFETY: active serial GPE frame retains the same Scene until release.
unsafe { r.queue.execute_gpe(gpe, p) }.unwrap();
assert_eq!(
// SAFETY: Foreground's reserved context remains retained through its pending result.
unsafe { r.call_foreground(foreground, p, cpu.ticks() + 1_000_000_000) },
Err(WorkError::Pending)
);
assert_eq!(f.blocked.lock().unwrap().len(), 16);
assert_eq!(r.step(), Ok(false));
// SAFETY: this second GPE owns the protected pending slot despite full General admission.
let pending = unsafe { r.queue.execute_gpe(marker, p) }.unwrap();
assert_eq!(r.queue.completed(pending), Ok(false));
assert_eq!(
// SAFETY: the named2entry GPE budget is full; no callback/context is accepted.
unsafe { r.queue.execute_gpe(rejected, p) },
Err(WorkError::Full)
);
assert_eq!(r.step(), Ok(false));
r.queue.close().unwrap();
f.release(None);
f.finish();
assert_eq!(r.queue.completed(pending), Ok(true));
let events = f.events.lock().unwrap();
assert_eq!(events.iter().filter(|e| e.0 == 90).count(), 15);
assert_eq!(events.iter().filter(|e| e.0 == 50).count(), 1);
assert!(!events.iter().any(|e| e.0 == 99));
assert_eq!(
events.iter().find(|e| e.0 == 5).unwrap().1,
events.iter().find(|e| e.0 == 50).unwrap().1
);
drop(events);
drop(executor);
assert_eq!(dropped.load(Ordering::Relaxed), 16);
assert_eq!(cpu.flags(), 0x202);
}