//! Persistent same-boot D4 IPC/UDP service coordinator. //! //! INIT and SHELL are the actual retained EL0 residents, not scheduler-model //! identities. Only their checked syscall callbacks admit channel work. INIT //! may exchange a packet only after receiving that exact request over the //! retained channel. Every response is copied from an actual RX used buffer. //! Device ownership, DMA release and channel capabilities remain in their //! respective owners; none is held by reference while an EL0 frame is resumed. //! //! NET_IPC v1, 128 little-endian u64 words (unassigned words are zero): //! 0 magic,1 version,2 boot,3 state(1 ready,2 active,3 drained), //! 4/5/6 INIT slot/generation/PID,7/8/9 SHELL slot/generation/PID, //! 10 real dispatch rounds,11 request sends,12 service receives,13 real UDP //! exchanges,14/15 successful request/reply application bytes,16/17 last //! exchange sequence/length,18/19 first sequence/length,20/21 start/finish, //! 22 frequency,23 malformed RX refusals,24 wrong destination refusals, //! 25 reserved,26 channel full refusals,27 closed send refusals,28 timeout, //! 29 protocol refusals,30 reserved,31 last syscall caller PID, //! 32/33 device address/words,34/35 channel address/words, //! 36/37 EXCHANGE address/bytes,38/39/40 free before/live/drained, //! 41 last INIT received sequence,42 last INIT exchanged sequence, //! 43 last INIT replied sequence,44/45 actual bad send/receive user pointer //! refusals,46 SHELL response receives,47 last SHELL response sequence, //! 48 first malformed RX length (at EXCHANGE offset32, maximum224), //! 49 reserved,50 captured malformed frame count(0/1),51 closing, //! 52 reserved,53/54 INIT/SHELL config calls,55 successful close syscalls, //! 56 reserved,57 stale destination refusals,58 foreign destination refusals, //! 59 reserved,60 post-close refusals,61 channel drained,62 device drained, //! 63 finalizing,64..127 zero. //! //! EXCHANGE bytes: first request [0..32], first malformed RX [32..256], //! first response [256..512], last request [512..768], last response //! [768..1024]. Application messages are exactly32 bytes and contain the //! actual EL0 `TURKD4V1`, bootLE, sequenceLE, SHELL-PIDLE fields. use super::super::*; use super::{d3_shell, d4_channel as channel, d4_device as device, d4_protocol as wire}; use super::process_owner::{self as owner, Id}; const MAGIC: u64 = 0x4434_4e45_5449_5043; const MESSAGE: usize = 32; #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D4_NET_IPC: [u64; 128] = [0; 128]; #[used] #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D4_EXCHANGE: [u8; 1024] = [0; 1024]; fn put(i: usize, value: u64) { unsafe { write_volatile(core::ptr::addr_of_mut!(OS_PRODUCT_D4_NET_IPC).cast::().add(i), value); } } fn get(i: usize) -> u64 { unsafe { read_volatile(core::ptr::addr_of!(OS_PRODUCT_D4_NET_IPC).cast::().add(i)) } } fn add(i: usize, value: u64) -> Result<(), &'static str> { put(i, get(i).checked_add(value).ok_or("d4-counter-overflow")?); Ok(()) } fn copy_out(offset: usize, bytes: &[u8]) -> Result<(), &'static str> { if offset.checked_add(bytes.len()).filter(|end| *end <= 1024).is_none() { return Err("d4-evidence-buffer-bounds"); } for (i, byte) in bytes.iter().copied().enumerate() { unsafe { write_volatile(core::ptr::addr_of_mut!(OS_PRODUCT_D4_EXCHANGE).cast::().add(offset + i), byte); } } Ok(()) } fn clock() -> u64 { let tick: u64; unsafe { asm!("mrs {v}, CNTPCT_EL0", v=out(reg)tick, options(nomem,nostack,preserves_flags)); } tick } fn guard() -> Result<(), &'static str> { let daif: u64; let mpidr: u64; let el: u64; unsafe { asm!("mrs {v}, DAIF", v=out(reg)daif, options(nomem,nostack,preserves_flags)); asm!("mrs {v}, MPIDR_EL1", v=out(reg)mpidr, options(nomem,nostack,preserves_flags)); asm!("mrs {v}, CurrentEL", v=out(reg)el, options(nomem,nostack,preserves_flags)); } if daif & 0x3c0 != 0x3c0 || mpidr & turkos_kernel::runtime::psci_call::AFFINITY_MASK != 0 || el != 4 { return Err("d4-owner-context"); } Ok(()) } fn identities() -> Result<(Id, Id), &'static str> { let (init, shell) = d3_shell::d4_identities()?; if get(2) != owner::snapshot()?.boot_id || owner::pid(init) != get(6) || owner::pid(shell) != get(9) { return Err("d4-process-binding"); } Ok((init, shell)) } fn current(caller: Id) -> Result<(Id, Id), &'static str> { guard()?; let ids = identities()?; if caller != ids.0 && caller != ids.1 { return Err("d4-foreign-caller"); } if owner::snapshot()?.current != Some(caller) || owner::state(caller)? != owner::State::Running { return Err("d4-caller-not-running"); } put(31, owner::pid(caller)); Ok(ids) } fn message(bytes: &[u8], sequence: u64) -> Result<(), &'static str> { if sequence == 0 || bytes.len() != MESSAGE || &bytes[..8] != b"TURKD4V1" || u64::from_le_bytes(bytes[8..16].try_into().map_err(|_| "d4-message-boot")?) != get(2) || u64::from_le_bytes(bytes[16..24].try_into().map_err(|_| "d4-message-sequence")?) != sequence || u64::from_le_bytes(bytes[24..32].try_into().map_err(|_| "d4-message-shell")?) != get(9) { return Err("d4-message-binding"); } Ok(()) } fn bytes_equal(offset: usize, bytes: &[u8]) -> bool { bytes.iter().copied().enumerate().all(|(i, b)| unsafe { read_volatile(core::ptr::addr_of!(OS_PRODUCT_D4_EXCHANGE).cast::().add(offset + i)) == b }) } pub(super) fn run( runtime: &mut OsK660Runtime, tables: &mmu::Tables, boot: &BootData, out: &mut [u64; 32], ) -> Result<(), &'static str> { guard()?; if get(0) != 0 { return Err("d4-duplicate-service"); } let snap = owner::snapshot()?; let (init, shell) = d3_shell::d4_identities()?; if snap.current.is_some() || snap.live != 2 || snap.exited != 0 || init == shell { return Err("d4-initial-process-state"); } let free = runtime.memory().ok_or("d4-memory")?.allocator.remaining_pages(); for (i, value) in [ (0,MAGIC),(1,1),(2,snap.boot_id),(4,u64::from(init.slot)),(5,init.generation),(6,owner::pid(init)), (7,u64::from(shell.slot)),(8,shell.generation),(9,owner::pid(shell)), (32,core::ptr::addr_of!(device::OS_PRODUCT_D4_DEVICE) as u64),(33,256), (34,core::ptr::addr_of!(channel::OS_PRODUCT_D4_CHANNEL) as u64),(35,128), (36,core::ptr::addr_of!(OS_PRODUCT_D4_EXCHANGE) as u64),(37,1024),(38,free), ] { put(i,value); } let hz: u64; unsafe { asm!("mrs {v}, CNTFRQ_EL0",v=out(reg)hz,options(nomem,nostack)); } if hz == 0 { return Err("d4-zero-frequency"); } put(22,hz); channel::open(snap.boot_id, init, shell)?; device::init(runtime, tables, boot, snap.boot_id)?; if device::mac()? != wire::GUEST_MAC { return Err("d4-device-mac-binding"); } put(39,runtime.memory().ok_or("d4-memory")?.allocator.remaining_pages()); put(3,1); snapshot(out) } pub(super) fn user_config(caller: Id) -> Result<[u64; 4], &'static str> { let (init, shell) = current(caller)?; if !matches!(get(3),1|2) { return Err("d4-service-not-active"); } add(if caller == init {53} else {54},1)?; Ok([1, owner::pid(if caller == init {shell} else {init}), get(2), get(63)]) } pub(super) fn user_send(caller: Id, destination: u64, sequence: u64, payload: &[u8]) -> Result<(), &'static str> { let (init, shell) = current(caller)?; let expected = if caller == shell { init } else { shell }; // Feed the supplied destination into the real owner so its negative // receipt includes this actual rejected operation. Opaque PIDs are the // generation token; a known own PID is a foreign endpoint, all other // unknown tokens denote a stale generation at the expected endpoint. let requested = if destination == owner::pid(caller) { caller } else { Id { slot: expected.slot, generation: destination } }; if destination != owner::pid(expected) { match channel::send(caller, requested, sequence, payload) { Err(_) => {}, Ok(()) => return Err("d4-wrong-destination-was-admitted"), } add(24,1)?; add(if requested.slot == caller.slot {58} else {57},1)?; return Err("d4-wrong-destination"); } if caller == init { if sequence != get(42) || !bytes_equal(768,payload) { return Err("d4-response-without-rx"); } } else { message(payload,sequence)?; } match channel::send(caller, expected, sequence, payload) { Err("d4-channel-full") => { add(26,1)?; return Err("d4-channel-full"); }, Err("d4-channel-closed") => { add(27,1)?; add(60,1)?; return Err("d4-channel-closed"); }, Err(error) => return Err(error), Ok(()) => {}, } if caller == shell { add(11,1)?; } else { put(43,sequence); } Ok(()) } pub(super) fn user_receive(caller: Id, out: &mut [u8]) -> Result<(usize, u64, u64), &'static str> { let (init, shell) = current(caller)?; let receipt = channel::receive(caller,out)?; if receipt.destination != caller || receipt.source != if caller == init {shell} else {init} { return Err("d4-channel-receipt-binding"); } message(&out[..receipt.length],receipt.sequence)?; if caller == init { add(12,1)?; put(41,receipt.sequence); } else { add(46,1)?; put(47,receipt.sequence); } Ok((receipt.length, owner::pid(receipt.source), receipt.sequence)) } pub(super) fn note_invalid_buffer(caller: Id, receive: bool) -> Result<(), &'static str> { current(caller)?; add(if receive {45} else {44},1) } pub(super) fn user_exchange(caller: Id, sequence: u64, payload: &mut [u8], length: usize) -> Result { let (init, _) = current(caller)?; if caller != init || get(51) != 0 || sequence != get(41) || sequence <= get(42) { return Err("d4-exchange-without-receive"); } if length > payload.len() { return Err("d4-exchange-buffer"); } let request = &payload[..length]; message(request,sequence)?; let mut frame = [0u8; 2048]; let bytes = wire::build_udp_request(sequence,request,&mut frame).map_err(|_| "d4-build-udp")?; device::send(&frame[..bytes])?; let deadline = clock().checked_add(get(22).checked_mul(2).ok_or("d4-deadline-overflow")?).ok_or("d4-deadline-overflow")?; loop { if clock() >= deadline { add(28,1)?; return Err("d4-udp-reply-timeout"); } let Some(n) = device::poll_receive(&mut frame)? else { core::hint::spin_loop(); continue; }; let reply = match wire::validate_udp_reply(&frame[..n],sequence,request) { Ok(reply) => reply, Err(_) => { add(23,1)?; add(29,1)?; if get(50) == 0 { if n > 224 { return Err("d4-malformed-evidence-too-large"); } copy_out(32,&frame[..n])?; put(48,n as u64); put(50,1); } continue; }, }; if reply.payload.len() != MESSAGE { return Err("d4-reply-length"); } if get(13) == 0 { copy_out(0,request)?; copy_out(256,reply.payload)?; put(18,sequence); put(19,length as u64); } copy_out(512,request)?; copy_out(768,reply.payload)?; let mut received = [0u8; MESSAGE]; received.copy_from_slice(reply.payload); payload[..MESSAGE].copy_from_slice(&received); add(13,1)?; add(14,length as u64)?; add(15,MESSAGE as u64)?; put(16,sequence); put(17,MESSAGE as u64); put(42,sequence); return Ok(MESSAGE); } } pub(super) fn user_close(caller: Id) -> Result<(), &'static str> { let (_, shell) = current(caller)?; if caller != shell || get(63) != 1 || get(11) != get(46) || get(11) != get(13) { return Err("d4-client-close-pending"); } channel::close_client(caller)?; add(55,1) } pub(super) fn service_begin(runtime: *mut OsK660Runtime, tables: *const mmu::Tables, boot: *const BootData) -> Result<(), &'static str> { guard()?; if get(3) != 1 { return Err("d4-service-begin-state"); } d3_shell::d4_begin(runtime,tables,boot)?; put(20,clock()); put(3,2); Ok(()) } pub(super) fn service_step(runtime: *mut OsK660Runtime, tables: *const mmu::Tables, boot: *const BootData) -> Result<(), &'static str> { guard()?; if get(3) != 2 || get(51) != 0 { return Err("d4-service-step-state"); } d3_shell::d4_step(runtime,tables,boot)?; put(10,d3_shell::service_rounds()); device::snapshot() } pub(super) fn service_finish(runtime: *mut OsK660Runtime, tables: *const mmu::Tables, boot: *const BootData) -> Result<(), &'static str> { guard()?; if get(3) != 2 || get(11) == 0 { return Err("d4-service-finish-state"); } put(63,1); d3_shell::d4_finish(runtime,tables,boot)?; put(10,d3_shell::service_rounds()); if get(11) != get(12) || get(11) != get(13) || get(11) != get(46) || get(43) != get(47) || get(44) == 0 || get(45) == 0 || get(24) == 0 || get(26) == 0 || get(27) == 0 || get(55) != 1 || get(23) == 0 || get(28) != 0 { return Err("d4-service-finish-receipts"); } unsafe { begin_shutdown(&mut *runtime,&*tables,&*boot)?; } put(21,clock()); Ok(()) } pub(super) fn service_rounds() -> u64 { get(10) } pub(super) fn close_admission() -> Result<(), &'static str> { guard()?; if get(0) != MAGIC { return Err("d4-service-not-initialized"); } put(51,1); Ok(()) } pub(super) fn begin_shutdown(runtime: &mut OsK660Runtime, _tables: &mmu::Tables, _boot: &BootData) -> Result<(), &'static str> { close_admission()?; if get(3) == 3 { return require_drained(); } // A pending user request must remain owned. Reset does not authorize // manufacturing a reply, dropping a live channel or reporting clean. if get(11) == 0 || get(11) != get(46) || get(11) != get(13) || get(55) != 1 { return Err("d4-shutdown-pending-work"); } channel::drain()?; if !channel::is_drained()? { return Err("d4-channel-drain-receipt"); } put(61,1); device::drain(runtime)?; device::require_drained()?; put(62,1); put(40,runtime.memory().ok_or("d4-memory")?.allocator.remaining_pages()); if get(40) != get(38) { return Err("d4-drain-free-page-balance"); } put(3,3); require_drained() } pub(super) fn require_drained() -> Result<(), &'static str> { guard()?; if get(3) != 3 || get(61) != 1 || get(62) != 1 || !channel::is_drained()? { return Err("native-d4-missing-live-service-drain-receipt"); } device::require_drained() } pub(super) fn snapshot(out: &mut [u64; 32]) -> Result<(), &'static str> { guard()?; if !matches!(get(3),1|2|3) { return Err("d4-snapshot-state"); } device::snapshot()?; let _ = channel::snapshot()?; *out = [0;32]; for (i,v) in [ (0,MAGIC),(1,1),(2,get(2)),(3,get(3)),(4,get(6)),(5,get(9)), (6,get(11)),(7,get(13)),(8,get(46)),(9,get(10)),(10,get(23)), (11,get(26)),(12,get(27)),(13,get(38)),(14,get(39)),(15,get(40)), (16,core::ptr::addr_of!(OS_PRODUCT_D4_NET_IPC) as u64),(17,128), (18,core::ptr::addr_of!(OS_PRODUCT_D4_EXCHANGE) as u64),(19,1024), (20,get(32)),(21,get(33)),(22,get(34)),(23,get(35)), (24,get(44)),(25,get(45)),(26,get(24)),(27,get(61)),(28,get(62)), (29,get(51)),(30,get(20)),(31,get(21)), ] { out[i]=v; } Ok(()) }