//! Hardware observations for the integrated SMP workload. //! //! A completion is recorded by the CPU which actually completed the operation. //! No historical K2100/K2500 result or host supplied duration enters this ledger. //! Starting CPUs and dispatching D3/D4 concurrently are separate ownership //! operations: until those exist, `run` refuses acceptance instead of inventing //! a successful workload from a timer-only loop. use super::super::*; use core::sync::atomic::{AtomicU64, Ordering}; use turkos_kernel::runtime::{cpu_topology, platform::Workspace}; global_asm!(include_str!("d5_smp_vectors.S")); const CPUS: usize = 4; const REQUIRED_SECONDS: u64 = 7_200; const MAX_IDLE_SECONDS: u64 = 30; const AFFINITY_MASK: u64 = 0x0000_00ff_00ff_ffff; struct CpuProgress { sequence: AtomicU64, affinity: AtomicU64, frequency: AtomicU64, first: AtomicU64, last: AtomicU64, d3: AtomicU64, d4: AtomicU64, d3_first: AtomicU64, d4_first: AtomicU64, d3_last: AtomicU64, d4_last: AtomicU64, fault: AtomicU64, } impl CpuProgress { const fn new() -> Self { Self { sequence: AtomicU64::new(0), affinity: AtomicU64::new(0), frequency: AtomicU64::new(0), first: AtomicU64::new(0), last: AtomicU64::new(0), d3: AtomicU64::new(0), d4: AtomicU64::new(0), d3_first: AtomicU64::new(0), d4_first: AtomicU64::new(0), d3_last: AtomicU64::new(0), d4_last: AtomicU64::new(0), fault: AtomicU64::new(0), } } } static PROGRESS: [CpuProgress; CPUS] = [const { CpuProgress::new() }; CPUS]; // No completed/idle receipt exists before an explicit topology owner has // initialized and joined its set. An explicitly initialized one-CPU topology // has an empty secondary set; the BSS default alone is never a stop receipt. static STARTED_SECONDARIES: AtomicU64 = AtomicU64::new(0); static VERIFIED_OFF_SECONDARIES: AtomicU64 = AtomicU64::new(0); static JOINED: AtomicU64 = AtomicU64::new(0); static INITIALIZED_CPUS: AtomicU64 = AtomicU64::new(0); static STOP_REQUESTED: AtomicU64 = AtomicU64::new(0); static START_ATTEMPTED: AtomicU64 = AtomicU64::new(0); // Written only by the fully masked boot CPU, before publishing INITIALIZED. static mut INITIALIZING: bool = false; // The platform parser scratch is ~22 KiB, larger than the initial kernel stack. static mut TOPOLOGY_SCRATCH: Workspace = Workspace::new(); static TOPOLOGY_BUSY: AtomicU64 = AtomicU64::new(0); const ROW_WORDS: usize = 16; const STACK_BYTES: u64 = 69_632; // one guard page plus a 64 KiB EL1h stack const STACK_CANARY: u64 = 0x4435_5354_4143_4b31; const CPU_ON: u64 = 0xc400_0003; const CPU_OFF: u64 = 0x8400_0002; const AFFINITY_INFO: u64 = 0xc400_0004; // Assembly reads this immutable block before translation is enabled. Atomic // operations begin only after the audited Normal Inner-Shareable root is live. // 0 root, 1 TCR, 2 MAIR, 3 SCTLR, 4 callback, 5 conduit, 6..9 contexts. #[used] #[unsafe(no_mangle)] static mut OS_PRODUCT_D5_BOOT: [u64; 16] = [0; 16]; // CPU-owned rows: 0 phase, 1 MPIDR, 2 current EL, 3 root, 4 VBAR, // 5 SP, 6 DAIF, 7 first counter, 8 last counter, 9 callback steps, // 10 timer control at return, 11 callback error, 12..15 reserved. #[used] #[unsafe(no_mangle)] static OS_PRODUCT_D5_CPUS: [AtomicU64; CPUS * ROW_WORDS] = [const { AtomicU64::new(0) }; CPUS * ROW_WORDS]; // Raw exception observations are written by assembly even if translation has // not yet been enabled. They are not atomics or task-completion receipts. #[used] #[unsafe(no_mangle)] static mut OS_PRODUCT_D5_FAULTS: [u64; CPUS * 8] = [0; CPUS * 8]; #[repr(C, align(4096))] struct SecondaryStack { guard: [u8; 4096], usable: [u8; 65536], } #[used] #[unsafe(no_mangle)] static mut OS_PRODUCT_D5_STACKS: [SecondaryStack; CPUS - 1] = [const { SecondaryStack { guard: [0; 4096], usable: [0; 65536], } }; CPUS - 1]; /// A caller-owned, bounded service slice. Returning zero means the slice /// returned safely; it does not manufacture a D3 or D4 completion. The slice /// must record those only after it actually completed and verified the work. pub(super) type WorkSlice = unsafe extern "C" fn(cpu: u64, context: u64) -> u64; fn row(cpu: usize, word: usize) -> &'static AtomicU64 { &OS_PRODUCT_D5_CPUS[cpu * ROW_WORDS + word] } fn primary_context(tables: Option<&mmu::Tables>) -> Result<(), &'static str> { let (cpu, _, _) = hardware()?; let daif: u64; let el: u64; unsafe { asm!("mrs {v}, DAIF", v = out(reg) daif, options(nomem, nostack)); asm!("mrs {v}, CurrentEL", v = out(reg) el, options(nomem, nostack)); } if cpu != 0 || el != 4 || daif & 0x3c0 != 0x3c0 || tables.is_some_and(|t| os_k940_registers().0 != t.root) { return Err("product-smp-primary-context"); } Ok(()) } fn normal_range(tables: &mmu::Tables, start: u64, bytes: usize) -> bool { let Some(end) = start.checked_add(bytes as u64) else { return false; }; if bytes == 0 { return false; } let mut page = start & !4095; while page < end { if !tables.normal_shareable_identity(page.max(start)) { return false; } let Some(next) = page.checked_add(4096) else { return false; }; page = next; } true } fn shared_data_valid(tables: &mmu::Tables) -> bool { let ranges = [ ( core::ptr::addr_of!(PROGRESS) as u64, core::mem::size_of_val(&PROGRESS), ), ( core::ptr::addr_of!(OS_PRODUCT_D5_CPUS) as u64, core::mem::size_of_val(&OS_PRODUCT_D5_CPUS), ), (core::ptr::addr_of!(OS_PRODUCT_D5_BOOT) as u64, 128), (core::ptr::addr_of!(OS_PRODUCT_D5_FAULTS) as u64, 256), (core::ptr::addr_of!(STARTED_SECONDARIES) as u64, 8), (core::ptr::addr_of!(VERIFIED_OFF_SECONDARIES) as u64, 8), (core::ptr::addr_of!(JOINED) as u64, 8), (core::ptr::addr_of!(INITIALIZED_CPUS) as u64, 8), (core::ptr::addr_of!(STOP_REQUESTED) as u64, 8), (core::ptr::addr_of!(START_ATTEMPTED) as u64, 8), (core::ptr::addr_of!(TOPOLOGY_BUSY) as u64, 8), ]; ranges .into_iter() .all(|(address, bytes)| normal_range(tables, address, bytes)) } /// Initialize a real, immutable topology without starting a secondary. This is /// deliberately separate from SMP acceptance and from `stop_join`. pub(super) fn initialize_primary( tables: &mmu::Tables, boot: &BootData, ) -> Result { primary_context(Some(tables))?; if !shared_data_valid(tables) { return Err("product-smp-shared-data-not-normal-shareable"); } let existing = INITIALIZED_CPUS.load(Ordering::Acquire); if existing != 0 { return Ok(existing as usize); } // No secondary has been published, and primary_context rejects every // other CPU. This reentry guard therefore needs no exclusive operation. if unsafe { read_volatile(core::ptr::addr_of!(INITIALIZING)) } { return Err("product-smp-initialize-reentry"); } unsafe { write_volatile(core::ptr::addr_of_mut!(INITIALIZING), true); } let result = (|| { let bytes = unsafe { core::slice::from_raw_parts(boot.dtb_address as *const u8, boot.dtb_size) }; let mut topology = cpu_topology::Topology::EMPTY; cpu_topology::parse_into(&mut topology, bytes, 0, unsafe { &mut *core::ptr::addr_of_mut!(TOPOLOGY_SCRATCH) }) .map_err(|_| "product-smp-topology")?; let count = topology.enabled as usize; if !matches!(count, 1 | 2 | 4) || topology.count != topology.enabled || topology.boot_index != 0 || topology .entries() .iter() .enumerate() .any(|(i, c)| c.affinity != i as u64) { return Err("product-smp-unsupported-topology"); } let conduit = turkos_kernel::runtime::psci_call::discover_conduit(bytes, unsafe { &mut *core::ptr::addr_of_mut!(TOPOLOGY_SCRATCH) }) .map_err(|_| "product-smp-psci-conduit")? as u64; let (root, tcr, _, _) = os_k940_registers(); let mair: u64; let sctlr: u64; unsafe { asm!("mrs {v}, MAIR_EL1", v = out(reg) mair, options(nomem, nostack)); asm!("mrs {v}, SCTLR_EL1", v = out(reg) sctlr, options(nomem, nostack)); } if root != tables.root || sctlr & 0x1005 != 0x1005 { return Err("product-smp-kernel-translation"); } for (index, value) in [(0, root), (1, tcr), (2, mair), (3, sctlr), (5, conduit)] { unsafe { write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D5_BOOT) .cast::() .add(index), value, ); } } unsafe { asm!("dsb sy", options(nostack)); } INITIALIZED_CPUS.store(count as u64, Ordering::Release); Ok(count) })(); unsafe { write_volatile(core::ptr::addr_of_mut!(INITIALIZING), false); } result } unsafe fn firmware(function: u64, target: u64, arg2: u64, arg3: u64) -> u64 { let conduit = unsafe { read_volatile(core::ptr::addr_of!(OS_PRODUCT_D5_BOOT).cast::().add(5)) }; let mut result = function; match conduit { 1 => unsafe { asm!("hvc #0", inout("x0") result, in("x1") target, in("x2") arg2, in("x3") arg3, clobber_abi("C"), options(nostack)); }, 2 => unsafe { asm!("smc #0", inout("x0") result, in("x1") target, in("x2") arg2, in("x3") arg3, clobber_abi("C"), options(nostack)); }, _ => return u64::MAX, } result } fn faulted(cpu: usize) -> bool { unsafe { read_volatile( core::ptr::addr_of!(OS_PRODUCT_D5_FAULTS) .cast::() .add(cpu * 8 + 4), ) != 0 } } /// Start only the service slices whose owner has already reserved all of their /// per-CPU state. Stack guards are unmapped before the first CPU_ON; this API /// never mutates page tables after publishing a secondary. /// /// # Safety /// Each context and slice remains valid until `stop_join` succeeds. The slice /// must own or correctly serialize every D3/D4 frame, process, device and queue /// it touches, must return boundedly with full DAIF masked and CNTP disabled, /// and may not leave a live IRQ/DMA/timer owner local to a stopped CPU. The /// current boot-CPU-only D3 dispatcher is not a valid slice for this interface. pub(super) unsafe fn start_owned( tables: &mmu::Tables, boot: &BootData, work: WorkSlice, contexts: [u64; CPUS], ) -> Result { let count = initialize_primary(tables, boot)?; primary_context(Some(tables))?; if START_ATTEMPTED.load(Ordering::Acquire) != 0 || JOINED.load(Ordering::Acquire) != 0 { return Err("product-smp-start-already-owned"); } unsafe extern "C" { static _image_start: u8; static _image_end: u8; fn __os_product_d5_secondary_entry(); } let image_start = core::ptr::addr_of!(_image_start) as u64; let image_end = core::ptr::addr_of!(_image_end) as u64; let callback = work as *const () as u64; let entry = __os_product_d5_secondary_entry as *const () as u64; if callback & 3 != 0 || callback < image_start || callback >= image_end || entry & 3 != 0 || entry < image_start || entry >= image_end { return Err("product-smp-callback-outside-image"); } for cpu in 1..count { let guard = core::ptr::addr_of!(OS_PRODUCT_D5_STACKS) as u64 + (cpu as u64 - 1) * STACK_BYTES; let low = guard + 4096; let end = guard + STACK_BYTES; if !normal_range(tables, low, 65536) { return Err("product-smp-stack-mapping"); } if unsafe { firmware(AFFINITY_INFO, cpu as u64, 0, 0) } != 1 { return Err("product-smp-secondary-not-firmware-off"); } unsafe { tables.unmap_metadata_stack_guard(guard, low, end, image_start, image_end) } .map_err(|_| "product-smp-stack-guard")?; if !tables.task_stack_guard_unmapped(guard) { return Err("product-smp-stack-guard-live"); } unsafe { write_volatile(low as *mut u64, STACK_CANARY); write_volatile((end - 8) as *mut u64, !STACK_CANARY); } } unsafe { write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D5_BOOT) .cast::() .add(4), callback, ); for (cpu, context) in contexts.into_iter().enumerate() { write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D5_BOOT) .cast::() .add(6 + cpu), context, ); } asm!("dsb sy", options(nostack)); } START_ATTEMPTED.store(1, Ordering::Release); for cpu in 1..count { let owned = STARTED_SECONDARIES.load(Ordering::Acquire) | (1 << cpu); // Retain ownership even if firmware returns an unknown result. STARTED_SECONDARIES.store(owned, Ordering::Release); let raw = unsafe { firmware(CPU_ON, cpu as u64, entry, cpu as u64) }; if raw as u32 as i32 != 0 { return Err("product-smp-cpu-on-refused-or-unknown"); } } let deadline = os_k960_counter() .checked_add( os_k960_frequency() .checked_mul(5) .ok_or("product-smp-start-deadline")?, ) .ok_or("product-smp-start-deadline")?; for cpu in 1..count { while row(cpu, 0).load(Ordering::Acquire) != 1 { if faulted(cpu) || row(cpu, 11).load(Ordering::Acquire) != 0 { return Err("product-smp-secondary-entry-fault"); } if os_k960_counter() >= deadline { return Err("product-smp-secondary-entry-timeout"); } core::hint::spin_loop(); } } Ok(count) } /// Stop every owned secondary only after its bounded service slice has /// returned, then require a fresh firmware OFF result. Failure retains all /// ownership; no resource reclamation is authorized by a timeout or CPU_ON. pub(super) fn stop_join() -> Result<(), &'static str> { primary_context(None)?; let count = INITIALIZED_CPUS.load(Ordering::Acquire) as usize; if !matches!(count, 1 | 2 | 4) { return Err("product-smp-stop-without-topology"); } if JOINED.load(Ordering::Acquire) == 1 { return Ok(()); } let started = STARTED_SECONDARIES.load(Ordering::Acquire); if count == 1 { if started != 0 { return Err("product-smp-primary-only-owned-secondary"); } JOINED.store(1, Ordering::Release); return Ok(()); } STOP_REQUESTED.store(1, Ordering::Release); unsafe { asm!("dsb sy", "sev", options(nostack)); } let deadline = os_k960_counter() .checked_add( os_k960_frequency() .checked_mul(30) .ok_or("product-smp-stop-deadline")?, ) .ok_or("product-smp-stop-deadline")?; let mut verified = VERIFIED_OFF_SECONDARIES.load(Ordering::Acquire); for cpu in 1..count { if started & (1 << cpu) == 0 { continue; } loop { if faulted(cpu) || row(cpu, 11).load(Ordering::Acquire) != 0 { return Err("product-smp-secondary-work-or-stop-fault"); } if row(cpu, 0).load(Ordering::Acquire) == 2 && unsafe { firmware(AFFINITY_INFO, cpu as u64, 0, 0) } == 1 { break; } if os_k960_counter() >= deadline { return Err("product-smp-secondary-off-timeout"); } core::hint::spin_loop(); } let guard = core::ptr::addr_of!(OS_PRODUCT_D5_STACKS) as u64 + (cpu as u64 - 1) * STACK_BYTES; let low = guard + 4096; let end = guard + STACK_BYTES; if unsafe { read_volatile(low as *const u64) } != STACK_CANARY || unsafe { read_volatile((end - 8) as *const u64) } != !STACK_CANARY { return Err("product-smp-secondary-stack-corruption"); } verified |= 1 << cpu; VERIFIED_OFF_SECONDARIES.store(verified, Ordering::Release); } if started != ((1u64 << count) - 2) { // Any actually started CPUs have still been stopped above; incomplete // startup cannot become a successful topology-wide join receipt. return Err("product-smp-incomplete-secondary-ownership"); } JOINED.store(1, Ordering::Release); Ok(()) } /// Read-only lifecycle diagnostics. These identify real start/stop resources; /// the caller must separately capture per-CPU work and raw task/device proof. pub(super) fn lifecycle_snapshot(out: &mut [u64; 32]) -> Result<(), &'static str> { primary_context(None)?; *out = [0; 32]; out[0] = 0x4435_4c49_4645_3031; out[1] = 1; out[2] = INITIALIZED_CPUS.load(Ordering::Acquire); out[3] = STARTED_SECONDARIES.load(Ordering::Acquire); out[4] = VERIFIED_OFF_SECONDARIES.load(Ordering::Acquire); out[5] = JOINED.load(Ordering::Acquire); out[6] = STOP_REQUESTED.load(Ordering::Acquire); out[7] = START_ATTEMPTED.load(Ordering::Acquire); out[8] = core::ptr::addr_of!(OS_PRODUCT_D5_CPUS) as u64; out[9] = (CPUS * ROW_WORDS) as u64; out[10] = core::ptr::addr_of!(OS_PRODUCT_D5_FAULTS) as u64; out[11] = (CPUS * 8) as u64; out[12] = core::ptr::addr_of!(OS_PRODUCT_D5_BOOT) as u64; out[13] = 16; out[14] = core::ptr::addr_of!(OS_PRODUCT_D5_STACKS) as u64; out[15] = STACK_BYTES; out[16] = os_k960_counter(); out[17] = u64::from(stopped()); Ok(()) } #[unsafe(no_mangle)] unsafe extern "C" fn os_product_d5_secondary(cpu: u64) -> ! { let fail = |code: u64| -> ! { if (cpu as usize) < CPUS { row(cpu as usize, 11).store(code, Ordering::Release); } loop { unsafe { asm!("wfe", options(nomem, nostack)); } } }; let index = cpu as usize; let (actual, _, first) = hardware().unwrap_or_else(|_| fail(1)); if actual != index || index == 0 || index >= INITIALIZED_CPUS.load(Ordering::Acquire) as usize { fail(2); } let sp: u64; let el: u64; let controls = os_k940_registers(); unsafe { asm!("mov {v}, sp", v = out(reg) sp, options(nomem, nostack)); asm!("mrs {v}, CurrentEL", v = out(reg) el, options(nomem, nostack)); } let config = core::ptr::addr_of!(OS_PRODUCT_D5_BOOT).cast::(); let root = unsafe { read_volatile(config) }; let guard = core::ptr::addr_of!(OS_PRODUCT_D5_STACKS) as u64 + (cpu - 1) * STACK_BYTES; if controls.0 != root || controls.3 & 0x3c0 != 0x3c0 || el != 4 || sp <= guard + 4096 || sp >= guard + STACK_BYTES - 8 { fail(3); } let callback = unsafe { read_volatile(config.add(4)) }; let context = unsafe { read_volatile(config.add(6 + index)) }; if callback == 0 { fail(4); } let work: WorkSlice = unsafe { core::mem::transmute(callback as usize) }; for (word, value) in [ (1, cpu), (2, el), (3, controls.0), (4, controls.2), (5, sp), (6, controls.3), (7, first), (8, first), ] { row(index, word).store(value, Ordering::Relaxed); } row(index, 0).store(1, Ordering::Release); while STOP_REQUESTED.load(Ordering::Acquire) == 0 { let result = unsafe { work(cpu, context) }; if result != 0 { fail(result | 0x100); } let previous = row(index, 9).load(Ordering::Relaxed); let Some(next) = previous.checked_add(1) else { fail(5); }; row(index, 9).store(next, Ordering::Relaxed); row(index, 8).store(os_k960_counter(), Ordering::Release); } let timer: u64; unsafe { asm!("mrs {v}, CNTP_CTL_EL0", v = out(reg) timer, options(nomem, nostack)); } row(index, 10).store(timer, Ordering::Relaxed); if os_k940_registers().3 & 0x3c0 != 0x3c0 || timer & 1 != 0 { fail(6); } row(index, 0).store(2, Ordering::Release); unsafe { asm!("dsb sy", "sev", options(nostack)); } let result = unsafe { firmware(CPU_OFF, 0, 0, 0) }; fail(result | 0x200) } fn hardware() -> Result<(usize, u64, u64), &'static str> { let affinity: u64; unsafe { core::arch::asm!("mrs {value}, MPIDR_EL1", value = out(reg) affinity, options(nomem, nostack, preserves_flags)); } let affinity = affinity & AFFINITY_MASK; if affinity >= CPUS as u64 { return Err("product-smp-nonflat-or-unsupported-cpu"); } let frequency = os_k960_frequency(); let counter = os_k960_counter(); if frequency == 0 || counter == 0 { return Err("product-smp-hardware-clock"); } Ok((affinity as usize, frequency, counter)) } /// Call only after this CPU completed a real, verified D3 operation. The caller /// must retain its task/stack/root ownership while this function runs. pub(super) fn record_d3_completion() -> Result<(), &'static str> { record(true) } /// Call only after this CPU completed a real, verified D4 operation, including /// its network/IPC result. A queue submission alone is not a completion. pub(super) fn record_d4_completion() -> Result<(), &'static str> { record(false) } fn record(d3: bool) -> Result<(), &'static str> { let (cpu, frequency, counter) = hardware()?; let count = INITIALIZED_CPUS.load(Ordering::Acquire) as usize; let daif: u64; let el: u64; unsafe { asm!("mrs {v}, DAIF", v = out(reg) daif, options(nomem, nostack)); asm!("mrs {v}, CurrentEL", v = out(reg) el, options(nomem, nostack)); } let root = unsafe { read_volatile(core::ptr::addr_of!(OS_PRODUCT_D5_BOOT).cast::()) }; if !matches!(count, 1 | 2 | 4) || cpu >= count || JOINED.load(Ordering::Acquire) != 0 || el != 4 || daif & 0x3c0 != 0x3c0 || os_k940_registers().0 != root || (cpu != 0 && row(cpu, 0).load(Ordering::Acquire) != 1) { return Err("product-smp-progress-outside-owned-kernel-slice"); } let row = &PROGRESS[cpu]; let sequence = row.sequence.load(Ordering::Acquire); if sequence & 1 != 0 || sequence > u64::MAX - 2 || row .sequence .compare_exchange(sequence, sequence + 1, Ordering::AcqRel, Ordering::Acquire) .is_err() { return Err("product-smp-concurrent-progress-writer"); } let result = (|| { let previous = row.last.load(Ordering::Relaxed); let old_frequency = row.frequency.load(Ordering::Relaxed); if row.fault.load(Ordering::Relaxed) != 0 || counter < previous || (old_frequency != 0 && old_frequency != frequency) { return Err("product-smp-clock-or-latched-fault"); } let units = if d3 { &row.d3 } else { &row.d4 }; let first = if d3 { &row.d3_first } else { &row.d4_first }; let last = if d3 { &row.d3_last } else { &row.d4_last }; let prior = last.load(Ordering::Relaxed); let maximum_idle = frequency .checked_mul(MAX_IDLE_SECONDS) .ok_or("product-smp-idle-overflow")?; if prior != 0 && counter - prior > maximum_idle { return Err("product-smp-starved-workload"); } let next = units .load(Ordering::Relaxed) .checked_add(1) .ok_or("product-smp-progress-overflow")?; if previous == 0 { row.first.store(counter, Ordering::Relaxed); } if prior == 0 { first.store(counter, Ordering::Relaxed); } row.affinity.store(cpu as u64, Ordering::Relaxed); row.frequency.store(frequency, Ordering::Relaxed); row.last.store(counter, Ordering::Relaxed); units.store(next, Ordering::Relaxed); last.store(counter, Ordering::Relaxed); Ok(()) })(); if result.is_err() { row.fault.store(1, Ordering::Relaxed); } row.sequence.store(sequence + 2, Ordering::Release); result } /// D7 observes an explicit join of the immutable topology. A single-CPU boot /// needs an initialized topology and successful empty-set `stop_join`; a /// multi-CPU boot additionally needs every owned secondary firmware-OFF. pub(super) fn stopped() -> bool { let count = INITIALIZED_CPUS.load(Ordering::Acquire); let started = STARTED_SECONDARIES.load(Ordering::Acquire); matches!(count, 1 | 2 | 4) && started == ((1u64 << count) - 2) && JOINED.load(Ordering::Acquire) == 1 && VERIFIED_OFF_SECONDARIES.load(Ordering::Acquire) == started } pub(super) fn run( _runtime: &mut super::super::OsK660Runtime, tables: &super::super::mmu::Tables, boot: &super::super::BootData, out: &mut [u64; 32], ) -> Result<(), &'static str> { *out = [0; 32]; initialize_primary(tables, boot)?; let (cpu, frequency, counter) = hardware()?; out[0] = REQUIRED_SECONDS; out[1] = frequency; out[2] = counter; if cpu != 0 || os_k940_registers().0 != tables.root { return Err("product-smp-primary-context"); } let bytes = unsafe { core::slice::from_raw_parts(boot.dtb_address as *const u8, boot.dtb_size) }; let mut topology = cpu_topology::Topology::EMPTY; if TOPOLOGY_BUSY .compare_exchange(0, 1, Ordering::Acquire, Ordering::Relaxed) .is_err() { return Err("product-smp-topology-busy"); } let parsed = cpu_topology::parse_into(&mut topology, bytes, 0, unsafe { &mut *core::ptr::addr_of_mut!(TOPOLOGY_SCRATCH) }); TOPOLOGY_BUSY.store(0, Ordering::Release); parsed.map_err(|_| "product-smp-topology")?; let count = topology.enabled as usize; out[3] = count as u64; if !matches!(count, 1 | 2 | 4) || topology.count != topology.enabled || topology.boot_index != 0 || topology .entries() .iter() .enumerate() .any(|(i, c)| c.affinity != i as u64) { return Err("product-smp-unsupported-topology"); } // Observe real CPU-owned counters for diagnostics, even when dispatch is // absent. The sequence bracket prevents accepting a torn concurrent write. let mut common_first = 0; let mut common_last = u64::MAX; let mut complete_cpus = 0; for (index, row) in PROGRESS[..count].iter().enumerate() { let before = row.sequence.load(Ordering::Acquire); let d3 = row.d3.load(Ordering::Relaxed); let d4 = row.d4.load(Ordering::Relaxed); let first = row.first.load(Ordering::Relaxed); let last = row.last.load(Ordering::Relaxed); let d3_first = row.d3_first.load(Ordering::Relaxed); let d4_first = row.d4_first.load(Ordering::Relaxed); let d3_last = row.d3_last.load(Ordering::Relaxed); let d4_last = row.d4_last.load(Ordering::Relaxed); let sampled_frequency = row.frequency.load(Ordering::Relaxed); let affinity = row.affinity.load(Ordering::Relaxed); let fault = row.fault.load(Ordering::Relaxed); core::sync::atomic::fence(Ordering::Acquire); let after = row.sequence.load(Ordering::Acquire); out[4 + index * 4] = d3; out[5 + index * 4] = d4; out[6 + index * 4] = first; out[7 + index * 4] = last; if before != after || after & 1 != 0 { return Err("product-smp-snapshot-busy"); } if fault != 0 { return Err("product-smp-latched-worker-fault"); } if d3 >= 2 && d4 >= 2 && d3_first != 0 && d4_first != 0 { if affinity != index as u64 || sampled_frequency != frequency { return Err("product-smp-worker-clock-binding"); } common_first = common_first.max(d3_first.max(d4_first)); common_last = common_last.min(d3_last.min(d4_last)); complete_cpus += 1; } } out[20] = common_first; out[21] = if common_last == u64::MAX { 0 } else { common_last }; out[22] = complete_cpus; let required_ticks = frequency .checked_mul(REQUIRED_SECONDS) .ok_or("product-smp-duration-overflow")?; out[23] = required_ticks; if complete_cpus != count as u64 { return Err("product-smp-missing-percpu-d3-d4-dispatch-and-stop-receipts"); } let measured_ticks = common_last .checked_sub(common_first) .ok_or("product-smp-no-common-workload-interval")?; out[24] = measured_ticks; out[25] = measured_ticks / frequency; if measured_ticks < required_ticks { return Err("product-smp-real-duration-not-yet-7200-seconds"); } // A counter loop, CPU_ON acknowledgement, or old workload report cannot // establish per-CPU D3/D4 execution, timer IRQ delivery or safe teardown. // Keep this gate explicit until the native dispatcher owns those resources. Err("product-smp-missing-percpu-d3-d4-dispatch-and-stop-receipts") }