//! The new product entry. Unsupported native services retain diagnostic evidence //! and fail; they never inherit success from the historical experiment chain. use super::*; use core::sync::atomic::{AtomicU64, Ordering}; pub(super) mod abi; mod d2_startup; mod d2_rollback; mod d2_leases; mod d3_shell; mod d4_net_ipc; mod d4_device; mod d4_protocol; mod d4_channel; mod d5_smp; mod d6_accounting; mod d7_shutdown; mod i2_turkish; mod process_owner; #[used] #[unsafe(no_mangle)] static mut PRODUCT_NATIVE_EVIDENCE: [u64; abi::WORDS] = [0; abi::WORDS]; #[used] #[unsafe(no_mangle)] static mut PRODUCT_NATIVE_SHUTDOWN_RELEASE: u64 = 0; // The boot CPU alone owns initialization while IRQs are masked. Secondary // dispatch is a separate D5 responsibility, not an atomic emulation here. static mut ENTRIES:u64=0; #[repr(C,align(4096))] struct NativeStack { guard:[u8;4096], usable:[u8;65536] } #[used] #[unsafe(no_mangle)] static mut PRODUCT_NATIVE_STACK:NativeStack=NativeStack{guard:[0;4096],usable:[0;65536]}; static mut NATIVE_ERROR:Option<&'static str>=None; const STACK_CANARY:u64=0x5052_4f44_5354_414b; // Published once before CPU_ON, read only by an owned D5 callback, and kept // alive until the complete join. The D5 global lease serializes every actual // process/device access through these pointers. static mut SMP_SERVICE_CONTEXT: [u64; 4] = [0; 4]; static mut SMP_SERVICE_ERRORS: [Option<&'static str>; 4] = [None; 4]; // Only a real lease holder observes the ordinary D3/D4 owner records. The // unleased primary sees this monotonic publication, never a racy owner read. static SMP_LOCAL_PROBES_READY: AtomicU64 = AtomicU64::new(0); static SMP_REQUIRE_POST_DURATION: AtomicU64 = AtomicU64::new(0); global_asm!(r#" .section .text.product_native_stack,"ax" .balign 4 .global __product_native_enter_stack __product_native_enter_stack: stp x19, x30, [sp, #-16]! mov x19, sp mov sp, x3 bl __product_native_body mov sp, x19 ldp x19, x30, [sp], #16 ret "#); fn put(index: usize, value: u64) { assert!(index < abi::WORDS); unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(PRODUCT_NATIVE_EVIDENCE).cast::().add(index), value); } } fn get(index: usize) -> u64 { unsafe { core::ptr::read_volatile(core::ptr::addr_of!(PRODUCT_NATIVE_EVIDENCE).cast::().add(index)) } } fn commit(index: usize, out: &[u64; 32]) { for (word, value) in out.iter().enumerate() { put(abi::BLOCK_BASE+index*abi::BLOCK_WORDS+word,*value); } } fn counter() -> u64 { let v:u64;unsafe{asm!("mrs {v}, CNTPCT_EL0",v=out(reg)v,options(nomem,nostack));}v } fn frequency() -> u64 { let v:u64;unsafe{asm!("mrs {v}, CNTFRQ_EL0",v=out(reg)v,options(nomem,nostack));}v } fn current_el() -> u64 { let v:u64;unsafe{asm!("mrs {v}, CurrentEL",v=out(reg)v,options(nomem,nostack));}v } /// The stopped host baseline observes the unchanged bounded D3 lifecycle. /// A UART acknowledgement releases actual continuing dispatch; host inspection /// time is excluded from the measured service duration. fn service_capture_release(tables: &mmu::Tables, boot: &BootData) -> Result<(), &'static str> { let uart = boot.hardware.uart_base; if uart == 0 || uart & 4095 != 0 || !tables.device_page_matches(uart) { return Err("native-product-service-uart"); } let deadline = abi::service_deadline(counter(), frequency(), abi::MAX_CAPTURE_WAIT_SECONDS)?; unsafe { asm!("dsb sy", options(nostack)); } write_line("TURKOS/PRODUCT: SERVICE_READY"); loop { if counter() >= deadline { return Err("native-product-service-capture-timeout"); } // SAFETY: the retained PL011 page was validated above. UART receive is // owned by this masked boot CPU during the single capture handshake. let flags = unsafe { core::ptr::read_volatile((uart + 0x18) as *const u32) }; if flags & (1 << 4) == 0 { let value = unsafe { core::ptr::read_volatile(uart as *const u32) }; if value & 0xf00 != 0 { return Err("native-product-service-capture-uart-error"); } if value as u8 != b'R' { return Err("native-product-service-capture-ack"); } return Ok(()); } core::hint::spin_loop(); } } unsafe extern "C" fn native_smp_slice(cpu: u64, context: u64) -> u64 { if context != core::ptr::addr_of!(SMP_SERVICE_CONTEXT) as u64 { return 1; } let actual_cpu: u64; unsafe { asm!("mrs {v}, MPIDR_EL1", v=out(reg)actual_cpu, options(nomem,nostack)); } if cpu >= 4 || actual_cpu & turkos_kernel::runtime::psci_call::AFFINITY_MASK != cpu { return 1; } let fields = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(SMP_SERVICE_CONTEXT)) }; if counter() >= fields[3] { return 0; } let result = (|| { let Some(lease) = d5_smp::try_service_lease()? else { return Ok(()); }; d4_net_ipc::service_step(fields[0] as *mut OsK660Runtime, fields[1] as *const mmu::Tables, fields[2] as *const BootData)?; // These credits follow a successful actual EL0 and network/IPC round. d5_smp::record_d3_completion()?; d5_smp::record_d4_completion()?; d4_net_ipc::service_probes(fields[0] as *mut OsK660Runtime, fields[1] as *const mmu::Tables, fields[2] as *const BootData)?; let cpus = d5_smp::initialized_cpu_count(); let require_post = SMP_REQUIRE_POST_DURATION.load(Ordering::Acquire) != 0; if d3_shell::stale_observations_complete(cpus, require_post)? { d5_smp::begin_closing_observation()?; } if d4_net_ipc::local_probes_complete()? && d5_smp::local_probes_complete()? && d3_shell::service_probes_complete(cpus, require_post)? && d5_smp::closing_observation_complete()? { SMP_LOCAL_PROBES_READY.store(1, Ordering::Release); } put(abi::SERVICE_COMPLETED_ROUNDS, d4_net_ipc::service_rounds()); lease.finish() })(); if let Err(reason) = result { // Each real CPU has its own error slot. The primary reads these only // after a complete join, so simultaneous failures never race a shared // fat pointer or manufacture an ownership release. unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(SMP_SERVICE_ERRORS) .cast::>().add(cpu as usize), Some(reason)); } 2 } else { 0 } } fn continuing_smp( runtime: *mut OsK660Runtime, tables: *const mmu::Tables, boot: *const BootData, config: abi::BootConfig, start: u64, deadline: u64, hard_deadline: u64, ) -> Result<(), &'static str> { let window = if config.service_seconds >= 7200 { 2400 } else { u64::from(config.service_seconds / 3).max(1) }; let (init, shell) = d3_shell::d4_identities()?; SMP_LOCAL_PROBES_READY.store(0, Ordering::Release); SMP_REQUIRE_POST_DURATION.store(u64::from(config.service_seconds >= 7200), Ordering::Release); unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(SMP_SERVICE_CONTEXT), [runtime as u64, tables as u64, boot as u64, hard_deadline]); d5_smp::configure_service(&*tables, &*boot, init, shell, window)?; d5_smp::configure_request_policy(config.service_seconds, config.shutdown_fault_case)?; if let Err(error) = d5_smp::start_owned(&*tables, &*boot, native_smp_slice, [core::ptr::addr_of!(SMP_SERVICE_CONTEXT) as u64; 4], core::mem::size_of::<[u64; 4]>() as u64) { // A partial start still owns its CPU resources. Attempt an actual // join; failure remains an error and never permits a clean drain. let _ = d5_smp::stop_join(); return Err(error); } } let work = (|| { let mut observed = start; loop { let now = counter(); if now < observed { return Err("native-product-service-clock-regressed"); } observed = now; let progress = d5_smp::service_progress()?; if progress.fault != 0 { return Err("native-product-smp-service-fault"); } let total: u64 = progress.rounds[..progress.cpus].iter().sum(); let complete = progress.rounds[..progress.cpus].iter().all(|v| *v >= 2) && progress.exec_windows[..progress.cpus].iter().all(|v| v & 7 == 7) && SMP_LOCAL_PROBES_READY.load(Ordering::Acquire) == 1; if complete && abi::service_complete(now, deadline, total, config.service_work_rounds) { break; } if now >= hard_deadline { return Err("native-product-service-work-timeout"); } if unsafe { native_smp_slice(0, core::ptr::addr_of!(SMP_SERVICE_CONTEXT) as u64) } != 0 { return Err("native-product-primary-service-failed"); } core::hint::spin_loop(); } Ok(()) })(); // No process/device owner can be inspected by the primary outside the // lease until every secondary really returned and firmware reports OFF. let joined = d5_smp::stop_join(); joined?; if let Err(error) = work { for cpu in 0..4 { let reason = unsafe { core::ptr::read_volatile(core::ptr::addr_of!(SMP_SERVICE_ERRORS) .cast::>().add(cpu)) }; if let Some(reason) = reason { return Err(reason); } } return Err(error); } d5_smp::end_service_mode()?; d4_net_ipc::service_quiesce(runtime, tables, boot)?; let mut out = [0; 32]; d4_net_ipc::snapshot(&mut out)?; commit(3, &out); put(abi::SERVICE_COMPLETED_ROUNDS, d4_net_ipc::service_rounds()); put(abi::SERVICE_FINISH, counter()); put(abi::SERVICE_STATE, 2); Ok(()) } fn continuing_service( runtime: *mut OsK660Runtime, tables: *const mmu::Tables, boot: *const BootData, config: abi::BootConfig, ) -> Result<(), &'static str> { put(abi::SERVICE_RECORD, core::ptr::addr_of!(d3_shell::OS_PRODUCT_D3_SERVICE) as u64); put(abi::SERVICE_RECORD_WORDS, 64); let network = config.stage_mask & (1 << 3) != 0; if network { d4_net_ipc::service_begin(runtime, tables, boot)?; } else { d3_shell::service_begin(runtime, tables, boot)?; } put(abi::SERVICE_STATE, 1); // Global status describes the requested bounded stage blocks. Continuing // service completion is reported independently by SERVICE_STATE=2. put(7, 1); unsafe { service_capture_release(&*tables, &*boot)?; } let start = counter(); let timer_frequency = frequency(); let deadline = abi::service_deadline(start, timer_frequency, config.service_seconds)?; let hard_deadline = abi::service_hard_deadline(start, timer_frequency, config.service_seconds)?; let interval = abi::service_interval(timer_frequency)?; put(abi::SERVICE_START, start); put(abi::SERVICE_DEADLINE, deadline); put(abi::SERVICE_INTERVAL, interval); if config.stage_mask & (1 << 4) != 0 { return continuing_smp(runtime, tables, boot, config, start, deadline, hard_deadline); } let mut completed = 0u64; let mut observed = start; let mut next_dispatch = start; loop { let now = counter(); if now < observed { return Err("native-product-service-clock-regressed"); } observed = now; if abi::service_complete(now, deadline, completed, config.service_work_rounds) { break; } if now >= hard_deadline { return Err("native-product-service-work-timeout"); } if now < next_dispatch { // Waiting changes neither process counters nor completed rounds. // The boot CPU waits between real EL0 work rounds at this cadence. core::hint::spin_loop(); continue; } // No allocator or other runtime reference is held across the resumed // exception frames. Each step closes its temporary callback bindings. if network { d4_net_ipc::service_step(runtime, tables, boot)?; } else { d3_shell::service_step(runtime, tables, boot)?; } completed = completed.checked_add(1).ok_or("native-product-service-round-overflow")?; put(abi::SERVICE_COMPLETED_ROUNDS, completed); let finished = counter(); if finished < observed { return Err("native-product-service-clock-regressed"); } observed = finished; if finished >= hard_deadline { return Err("native-product-service-work-timeout"); } next_dispatch = finished.checked_add(interval).ok_or("native-product-service-clock-overflow")?; } if network { d4_net_ipc::service_finish(runtime, tables, boot)?; // D4 closes its client by resuming one final real INIT/shell round. // Count that work from its dispatcher receipt rather than inventing // a host-side or elapsed-time credit for the additional round. put(abi::SERVICE_COMPLETED_ROUNDS, d4_net_ipc::service_rounds()); let mut out = [0; 32]; d4_net_ipc::snapshot(&mut out)?; commit(3, &out); } else { d3_shell::service_finish()?; } let finish = counter(); if finish < observed { return Err("native-product-service-clock-regressed"); } put(abi::SERVICE_FINISH, finish); put(abi::SERVICE_STATE, 2); Ok(()) } fn d1(runtime:&mut OsK660Runtime,tables:&mmu::Tables,boot:&BootData,config:abi::BootConfig,out:&mut[u64;32])->Result<(),&'static str>{ unsafe extern "C" { static _image_start:u8; static _image_end:u8; } let start=core::ptr::addr_of!(_image_start) as u64; let end=core::ptr::addr_of!(_image_end) as u64; let magic=unsafe{core::ptr::read_volatile((start+0x38) as *const u32)}; let manifest=runtime.manifest(); let mpidr:u64;let daif:u64;unsafe{asm!("mrs {v},MPIDR_EL1",v=out(reg)mpidr,options(nomem,nostack));asm!("mrs {v},DAIF",v=out(reg)daif,options(nomem,nostack));} if mpidr & turkos_kernel::runtime::psci_call::AFFINITY_MASK != 0 || daif & 0x80 == 0 {return Err("native-product-initializer-owner");} if manifest.profile!=os_k660_policy::Profile::Product || manifest.probes!=0 {return Err("native-product-profile");} if current_el()!=4 || start!=0x40080000 || end<=start || end-start>8*1024*1024 || magic!=0x644d5241 {return Err("native-product-image-entry");} if !tables.owns_table_frame(tables.root) || runtime.snapshot().map_err(os_k660_policy::Error::tag)?.registered != [true;4] {return Err("native-product-foundation");} let free=runtime.memory().ok_or("native-product-memory")?.allocator.remaining_pages(); out[0]=abi::D1_MAGIC;out[1]=1;out[2]=start;out[3]=end-start; out[4]=boot.dtb_address as u64;out[5]=config.boot_id;out[6]=u64::from(config.route);out[7]=1; let entries=unsafe{core::ptr::read_volatile(core::ptr::addr_of!(ENTRIES))}.checked_add(1).ok_or("native-product-entry-overflow")?; unsafe{core::ptr::write_volatile(core::ptr::addr_of_mut!(ENTRIES),entries);} out[8]=entries;out[9]=u64::from(magic); out[10]=free;out[11]=boot.dtb_size as u64;out[12]=current_el();out[13]=1; if out[8]!=1 {return Err("native-product-duplicate-entry");} put(13,free);Ok(()) } pub(super) fn boot_id()->Result{let value=get(2);if value==0{Err("native-product-no-boot-id")}else{Ok(value)}} pub(super) fn require_shutdown_prerequisites()->Result<(),&'static str>{ if get(4)&0xbf!=0xbf {return Err("native-product-shutdown-prerequisites");} if !d5_smp::stopped(){return Err("native-product-cpus-not-stopped");} d6_accounting::require_reconciled() } /// D7 calls this after its real final EL0 drain round, before retiring either /// parent. Preserve that observed work in both the stage and global records. pub(super) fn checkpoint_d4_shutdown() -> Result<(), &'static str> { let mut out = [0; 32]; d4_net_ipc::snapshot(&mut out)?; commit(3, &out); put(abi::SERVICE_COMPLETED_ROUNDS, d4_net_ipc::service_rounds()); Ok(()) } pub(super) fn checkpoint_shutdown(out:&[u64;32], tables:&mmu::Tables, boot:&BootData)->Result<(),&'static str>{ require_shutdown_prerequisites()?;commit(6,out);put(7,3);put(8,counter()); let uart = boot.hardware.uart_base; if uart == 0 || uart & 4095 != 0 || !tables.device_page_matches(uart) { return Err("native-product-shutdown-uart"); } if unsafe { core::ptr::read_volatile(core::ptr::addr_of!(PRODUCT_NATIVE_SHUTDOWN_RELEASE)) } != 0 { return Err("native-product-shutdown-release-reused"); } unsafe{asm!("dsb sy",options(nostack));}write_line("TURKOS/PRODUCT: EVIDENCE_READY"); let deadline = abi::service_deadline(counter(), frequency(), abi::MAX_CAPTURE_WAIT_SECONDS)?; loop { if counter() >= deadline { return Err("native-product-shutdown-capture-timeout"); } let flags = unsafe { core::ptr::read_volatile((uart + 0x18) as *const u32) }; if flags & (1 << 4) == 0 { let value = unsafe { core::ptr::read_volatile(uart as *const u32) }; if value & 0xf00 != 0 { return Err("native-product-shutdown-uart-error"); } if value as u8 != b'P' { return Err("native-product-shutdown-capture-ack"); } // The host releases a capture checkpoint through the UART. It // neither writes guest result memory nor supplies a success bit. unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(PRODUCT_NATIVE_SHUTDOWN_RELEASE), 1); } break; } unsafe{asm!("yield",options(nomem,nostack));} } Ok(()) } #[inline(never)] pub(super) fn run(runtime:&mut OsK660Runtime,tables:&mmu::Tables,boot:&BootData)->Result<(),&'static str>{ unsafe extern "C" { static _image_start:u8;static _image_end:u8; fn __product_native_enter_stack(runtime:*mut OsK660Runtime,tables:*const mmu::Tables,boot:*const BootData,top:u64)->u64; } let guard=core::ptr::addr_of!(PRODUCT_NATIVE_STACK) as u64; let low=guard+4096;let end=low+65536; unsafe{tables.unmap_metadata_stack_guard(guard,low,end,core::ptr::addr_of!(_image_start) as u64,core::ptr::addr_of!(_image_end) as u64)}.map_err(|_|"native-product-stack-guard")?; if !tables.task_stack_guard_unmapped(guard){return Err("native-product-stack-still-mapped");} let before:u64;unsafe{asm!("mov {v},sp",v=out(reg)before,options(nomem,nostack)); core::ptr::write_volatile(low as *mut u64,STACK_CANARY); core::ptr::write_volatile((end-8) as *mut u64,!STACK_CANARY); core::ptr::write_volatile(core::ptr::addr_of_mut!(NATIVE_ERROR),None); } let code=unsafe{__product_native_enter_stack(runtime,tables,boot,end-16)}; let after:u64;unsafe{asm!("mov {v},sp",v=out(reg)after,options(nomem,nostack));} let lower=unsafe{core::ptr::read_volatile(low as *const u64)}; let upper=unsafe{core::ptr::read_volatile((end-8) as *const u64)}; if before!=after || lower!=STACK_CANARY || upper!=!STACK_CANARY{return Err("native-product-stack-corruption");} for (index,value) in [(14,guard),(15,low),(16,end),(17,before),(19,after),(20,lower),(21,upper)]{put(index,value);} unsafe{asm!("dsb sy",options(nostack));}write_line("TURKOS/PRODUCT: EVIDENCE_READY"); if code==0{Ok(())}else{Err(unsafe{core::ptr::read_volatile(core::ptr::addr_of!(NATIVE_ERROR))}.unwrap_or("native-product-stage-failed"))} } #[unsafe(no_mangle)] unsafe extern "C" fn __product_native_body(runtime:*mut OsK660Runtime,tables:*const mmu::Tables,boot:*const BootData)->u64{ let result=unsafe{run_inner(&mut *runtime,&*tables,&*boot)}; match result{Ok(())=>0,Err(reason)=>{unsafe{core::ptr::write_volatile(core::ptr::addr_of_mut!(NATIVE_ERROR),Some(reason));}1}} } #[inline(never)] fn run_inner(runtime:&mut OsK660Runtime,tables:&mmu::Tables,boot:&BootData)->Result<(),&'static str>{ let blob=unsafe{core::slice::from_raw_parts(boot.dtb_address as *const u8,boot.dtb_size)}; let config=abi::BootConfig::parse(blob)?; for i in 0..abi::WORDS {put(i,0);} for (i,v) in [abi::MAGIC,abi::VERSION,config.boot_id,u64::from(config.route),0,0,u64::from(config.stage_mask),0,counter(),frequency(),boot.dtb_address as u64,boot.dtb_size as u64,current_el()].iter().enumerate(){put(i,*v);} put(abi::SERVICE_SECONDS, u64::from(config.service_seconds)); put(abi::SERVICE_MIN_ROUNDS, if config.service_seconds == 0 { 0 } else { u64::from(config.service_work_rounds) }); let body_sp:u64;unsafe{asm!("mov {v},sp",v=out(reg)body_sp,options(nomem,nostack));}put(18,body_sp); let mut out=[0u64;32]; d1(runtime,tables,boot,config,&mut out)?;commit(0,&out);put(4,1); // I2 executes before the final shutdown checkpoint even though its block is 7. for stage in [1usize,2,3,4,5,7,6] { if config.stage_mask&(1<d2_startup::run(runtime,tables,boot,config.d2_diagnostics,&mut out), 2=>d3_shell::run(runtime,tables,boot,&mut out), 3=>d4_net_ipc::run(runtime,tables,boot,&mut out), // A short native integration run is explicitly a diagnostic // observation, with physical D5 word27=false. The full 7200-second // gate and its remaining fault proofs retain their own admission. 4 if config.service_seconds > 0 && config.service_seconds < 7200 => d5_smp::diagnostic_observe(runtime,tables,boot,&mut out), 4=>d5_smp::run(runtime,tables,boot,&mut out), 5=>d6_accounting::run(runtime,tables,boot,&mut out), 6=>d7_shutdown::run(runtime,tables,boot,&mut out), 7=>i2_turkish::run(runtime,tables,boot,&mut out), _=>Err("native-product-stage"), }; commit(stage,&out); if let Err(reason)=result { put(5,(stage+1) as u64);put(7,2);put(8,counter()); unsafe{asm!("dsb sy",options(nostack));} write_str("TURKOS/PRODUCT: INCOMPLETE reason=");write_line(reason); return Err(reason); } put(4,get(4)|(1<