//! The new product entry. Unsupported native services retain diagnostic evidence //! and fail; they never inherit success from the historical experiment chain. use super::*; pub(super) mod abi; mod d2_startup; mod d2_rollback; mod d2_leases; mod d3_shell; mod d4_net_ipc; 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; 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_SERVICE_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(); } } 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); 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); 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. 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")?; } 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() } pub(super) fn checkpoint_shutdown(out:&[u64;32])->Result<(),&'static str>{ require_shutdown_prerequisites()?;commit(6,out);put(7,3);put(8,counter()); unsafe{asm!("dsb sy",options(nostack));}write_line("TURKOS/PRODUCT: EVIDENCE_READY"); while unsafe{core::ptr::read_volatile(core::ptr::addr_of!(PRODUCT_NATIVE_SHUTDOWN_RELEASE))}!=1{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), 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<