//! Native product startup adapter. //! //! The K660 registry owns the real UART, allocator, GIC and cooperative task //! scheduler. The product process owner separately retains the process table //! and the initial PID1 identity. D2 establishes that ownership boundary; D3 //! must still prove real EL0 INIT execution and process lifecycle behavior. //! Separate retained diagnostic owners record actual partial-startup recovery //! and hardware lease refusal; the inherited core snapshot is never used as //! evidence that either failure path executed. use super::super::*; use turkos_kernel::runtime::services::{Error, Profile, Snapshot, Stage}; const UNOBSERVED: u64 = u64::MAX; const TTBR_ADDRESS: u64 = 0x0000_ffff_ffff_f000; fn free_pages(runtime: &OsK660Runtime) -> Result { Ok(runtime .memory() .ok_or("native-d2-memory-owner-missing")? .allocator .remaining_pages()) } fn devices_mapped(tables: &mmu::Tables, base: u64, size: u64) -> bool { if base == 0 || base & 0xffff != 0 { return false; } let Some(end) = base.checked_add(size) else { return false; }; let mut address = base; while address < end { if !tables.device_page_matches(address) { return false; } address += 4096; } true } /// Recover only acquisitions retained by a genuinely failing initializer. /// No ownership is reconstructed, no live-DMA flag is cleared, and a refusal /// keeps the partial owner in Runtime. Recovery success still does not accept /// the startup attempt that failed. fn rollback_partial( runtime: &mut OsK660Runtime, before: Snapshot, pages: u64, out: &mut [u64; 32], ) -> Result<(), &'static str> { out[25] = free_pages(runtime)?; out[26] = 0; runtime .rollback_failed(&mut OsK660Rollback { clear_synthetic_dma: false, }) .map_err(Error::tag)?; out[26] = 1; out[27] = free_pages(runtime)?; if runtime.snapshot().map_err(Error::tag)? != before || out[27] != pages { return Err("native-d2-partial-rollback-mismatch"); } Ok(()) } fn require_diagnostic_context(tables: &mmu::Tables) -> Result<(), &'static str> { let daif: u64; let mpidr: u64; let ttbr: u64; let sctlr: u64; // SAFETY: the boot CPU owns startup. These observations do not change its // exception state; a diagnostic may temporarily unmask IRQ only while its // own real interrupt handler retains all resources needed by that IRQ. unsafe { asm!("mrs {v}, DAIF", v = out(reg) daif, options(nomem, nostack)); asm!("mrs {v}, MPIDR_EL1", v = out(reg) mpidr, options(nomem, nostack)); asm!("mrs {v}, TTBR0_EL1", v = out(reg) ttbr, options(nomem, nostack)); asm!("mrs {v}, SCTLR_EL1", v = out(reg) sctlr, options(nomem, nostack)); } if mpidr & turkos_kernel::runtime::psci_call::AFFINITY_MASK != 0 || daif & 0x80 == 0 { return Err("native-d2-diagnostic-context-owner"); } if sctlr & 1 == 0 || ttbr & TTBR_ADDRESS != tables.root { return Err("native-d2-diagnostic-context-root"); } if unsafe { read_volatile(core::ptr::addr_of!(OS_K660_IRQ_ACTIVE)) } as u64 != 0 { return Err("native-d2-diagnostic-context-active-irq"); } Ok(()) } /// Execute real diagnostic initializers without replacing the inherited K660 /// owner. Each module publishes its own failure/refusal/recovery observations. /// In particular, the healthy core fields 25..27 remain unobserved when the /// inherited initializer did not fail; the separate records describe the /// actual diagnostic acquisitions rather than rewriting that history. pub(super) fn run_diagnostics( runtime: &mut OsK660Runtime, tables: &mmu::Tables, boot: &BootData, ) -> Result<(), &'static str> { require_diagnostic_context(tables)?; let inherited = runtime.snapshot().map_err(Error::tag)?; let pages = free_pages(runtime)?; if inherited.stage != Stage::Tasks || inherited.failure.is_some() { return Err("native-d2-diagnostic-core-owner-missing"); } // This initializer retains real frames until the frame authority refuses // another ownership record at metadata capacity. Physical free pages still // remain; this is not a claim of physical-memory exhaustion. super::d2_rollback::run(runtime, tables)?; require_diagnostic_context(tables)?; if runtime.snapshot().map_err(Error::tag)? != inherited || free_pages(runtime)? != pages { return Err("native-d2-partial-diagnostic-owner-not-restored"); } // The hardware adapter retains real timer/DMA owners across rollback // refusals, and may recover them only after IRQ exit / device quiescence. super::d2_leases::run(runtime, tables, boot)?; require_diagnostic_context(tables)?; if runtime.snapshot().map_err(Error::tag)? != inherited || free_pages(runtime)? != pages { return Err("native-d2-hardware-diagnostic-owner-not-restored"); } Ok(()) } pub(super) fn run( runtime: &mut super::super::OsK660Runtime, tables: &super::super::mmu::Tables, boot: &super::super::BootData, diagnostics: bool, out: &mut [u64; 32], ) -> Result<(), &'static str> { // Process fields remain unknown until the retained owner is validated. *out = [UNOBSERVED; 32]; let daif: u64; let sctlr: u64; let ttbr: u64; let counter: u64; // SAFETY: this is called on the boot CPU at EL1; these are read-only // observations. No interrupt is unmasked by the adapter. unsafe { asm!("mrs {v}, DAIF", v = out(reg) daif, options(nomem, nostack)); asm!("mrs {v}, SCTLR_EL1", v = out(reg) sctlr, options(nomem, nostack)); asm!("mrs {v}, TTBR0_EL1", v = out(reg) ttbr, options(nomem, nostack)); asm!("mrs {v}, CNTPCT_EL0", v = out(reg) counter, options(nomem, nostack)); } out[0] = daif; out[1] = sctlr; out[2] = ttbr; out[3] = tables.root; out[4] = tables.frame_count() as u64; out[5] = counter; if daif & 0x80 == 0 { return Err("native-d2-irq-not-masked"); } if sctlr & 1 == 0 || ttbr & TTBR_ADDRESS != tables.root { return Err("native-d2-kernel-root-not-active"); } if !tables.owns_table_frame(tables.root) || !tables.normal_shareable_identity(tables.root) { return Err("native-d2-kernel-root-owner-mismatch"); } let manifest = runtime.manifest(); out[6] = manifest.profile as u64; out[7] = manifest.probes as u64; if manifest.profile != Profile::Product || manifest.probes != 0 { return Err("native-d2-product-manifest-required"); } let initial = runtime.snapshot().map_err(Error::tag)?; out[8] = initial.stage as u64; out[9] = free_pages(runtime)?; if initial.failure.is_some() { return Err("native-d2-prior-initializer-unrecovered"); } if !matches!(initial.stage, Stage::Memory | Stage::Irq | Stage::Tasks) || out[9] == 0 { return Err("native-d2-startup-prerequisites-missing"); } let gicd = boot.interrupts.gic_distributor; let gicr = boot.interrupts.gic_redistributor; out[10] = gicd; out[11] = gicr; if !devices_mapped(tables, gicd, 0x1_0000) || !devices_mapped(tables, gicr, 0x2_0000) || boot.interrupts.nonsecure_phys_timer_ppi != 30 { return Err("native-d2-gic-mappings-missing"); } if initial.stage == Stage::Memory { let before = runtime.snapshot().map_err(Error::tag)?; let pages = free_pages(runtime)?; if runtime.start_irq(|_| os_k660_install_irq(boot)).is_err() { rollback_partial(runtime, before, pages, out)?; return Err("native-d2-irq-start-failed-rolled-back"); } } let scheduler_started = runtime.snapshot().map_err(Error::tag)?.stage == Stage::Irq; if scheduler_started { let before = runtime.snapshot().map_err(Error::tag)?; let pages = free_pages(runtime)?; if runtime.start_tasks(os_k660_tasks).is_err() { rollback_partial(runtime, before, pages, out)?; return Err("native-d2-scheduler-start-failed-rolled-back"); } } let started = runtime.snapshot().map_err(Error::tag)?; out[12] = started.stage as u64; out[13] = started.ownership.frames; out[14] = started.ownership.irq_bindings as u64; out[15] = started.ownership.tasks as u64; out[16] = started.ownership.dma_buffers as u64; if started.stage != Stage::Tasks || started.registered != [true; 4] || started.failure.is_some() { return Err("native-d2-core-service-publication-incomplete"); } { let (_, memory, irq, tasks) = runtime.running().map_err(Error::tag)?; let id = tasks.id.ok_or("native-d2-scheduler-task-owner-missing")?; let frame = tasks .frame .ok_or("native-d2-scheduler-frame-owner-missing")?; out[17] = frame; out[18] = id.slot as u64; out[19] = id.generation; out[20] = tasks.scheduler.ready_len() as u64; out[21] = tasks.progress; out[22] = memory.allocator.remaining_pages(); // SAFETY: every page in this redistributor window was checked above, // and the boot CPU still owns it with interrupts masked. out[23] = unsafe { read_volatile((gicr + 0x1_0100) as *const u32) } as u64; out[24] = unsafe { read_volatile(core::ptr::addr_of!(OS_K660_IRQ_ACTIVE)) } as u64; if !irq.installed || irq.gicr != gicr || out[23] & (1 << 30) == 0 || out[24] != 0 { return Err("native-d2-irq-hardware-owner-mismatch"); } if frame & 4095 != 0 || !tables.normal_shareable_identity(frame) || tasks.synthetic_dma_active || started.ownership.dma_buffers != 0 { return Err("native-d2-task-frame-or-dma-mismatch"); } let state = tasks .scheduler .state(id) .map_err(|_| "native-d2-stale-task-id")?; match state { turkos_kernel::task::State::Ready => { if tasks.scheduler.running().is_some() || out[20] != 1 { return Err("native-d2-ready-queue-owner-mismatch"); } } turkos_kernel::task::State::Running => { if tasks.scheduler.running() != Some(id) || out[20] != 0 { return Err("native-d2-running-task-owner-mismatch"); } } _ => return Err("native-d2-scheduler-not-runnable"), } if out[22].checked_add(u64::from(scheduler_started)) != Some(out[9]) { return Err("native-d2-startup-frame-account-mismatch"); } } if diagnostics { run_diagnostics(runtime, tables, boot)?; } // The process table is a separate retained owner: a cooperative TaskId is // never converted into a ProcessId. Initialization acquires no physical // pages or device resources. Diagnostic acquisitions remain governed by // their recorded owners, and must restore the inherited registry before // this process metadata is published. let boot_id = super::boot_id()?; super::process_owner::initialize(boot_id)?; let owner = super::process_owner::snapshot()?; if owner.boot_id != boot_id || owner.init.slot != 0 || owner.init.generation == 0 || owner.live != 1 || owner.current.is_some() || owner.execs != 0 || owner.spawns != 0 || owner.waits != 0 || owner.exits != 0 || owner.reaps != 0 || owner.stale_rejections != 0 { return Err("native-d2-initial-process-owner-mismatch"); } // These are identity/occupancy observations, not an INIT-ready handshake // or an EL0 entry receipt. D3 records those from the actual exception path. out[28] = u64::from(owner.init.slot) + 1; out[29] = owner.init.generation; out[30] = owner.live; unsafe { asm!("mrs {v}, CNTPCT_EL0", v = out(reg) out[31], options(nomem, nostack)); } Ok(()) }