//! 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 v2, 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 actual pending-work drain refusals,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 actual ARP requests,50 captured malformed frame count(0/1),51 closing, //! 52 validated actual ARP replies,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 real heap enabled,65/66/67 actual heap allocate/read/ //! release calls,68 pending heap sequence,69 last heap payload length, //! 70 pending heap token,71 last heap owner PID,72 quiesced,73 quiesce //! counter,74 real timeout-probe sequence,75/76 probe begin/recovery counter, //! 77 classified-and-recovered completion receipts,78 actual retired-ID IPC //! probes,79/80 D6 probe metadata address/words,81/82 D6 probe inventory //! address/words,83 timeout inventory sequence,84 timeout owners exactly equal, //! 85 stall inventory sequence,86 stall owners exactly equal,87 withheld CPU, //! 88/89/90 stall begin/classified/recovered counters,91 real peer recovery, //! 92..95/96..99 stall before/after typed inventory digests, //! 100..103/104..107 timeout before/after digests;108..127 zero. //! Digests only bind the separate complete D6 records; admission compares all //! source-owned typed inventory bytes, never digests alone. //! //! 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; // Access is serialized by the real D5 service lease when that mode is active. // A failed device transaction leaves the move-only physical heap token here; // neither a timeout nor a reset can silently turn it into a completed request. static mut HEAP_PAYLOAD: Option = None; static mut CALLBACK_RUNTIME: *mut OsK660Runtime = core::ptr::null_mut(); static mut CALLBACK_TABLES: *const mmu::Tables = core::ptr::null(); static mut STALL_FINGERPRINT: Option = None; struct RuntimeBinding; impl RuntimeBinding { fn bind(runtime: *mut OsK660Runtime, tables: *const mmu::Tables) -> Result { if runtime.is_null() || tables.is_null() || unsafe { !read_volatile(core::ptr::addr_of!(CALLBACK_RUNTIME)).is_null() || !read_volatile(core::ptr::addr_of!(CALLBACK_TABLES)).is_null() } { return Err("d4-runtime-binding-reentry"); } unsafe { write_volatile(core::ptr::addr_of_mut!(CALLBACK_RUNTIME),runtime); write_volatile(core::ptr::addr_of_mut!(CALLBACK_TABLES),tables); } Ok(Self) } } impl Drop for RuntimeBinding { fn drop(&mut self) { unsafe { write_volatile(core::ptr::addr_of_mut!(CALLBACK_RUNTIME),core::ptr::null_mut()); write_volatile(core::ptr::addr_of_mut!(CALLBACK_TABLES),core::ptr::null()); } } } fn callback_runtime() -> Result<*mut OsK660Runtime, &'static str> { let runtime = unsafe { read_volatile(core::ptr::addr_of!(CALLBACK_RUNTIME)) }; if runtime.is_null() { Err("d4-runtime-not-bound") } else { Ok(runtime) } } fn callback_tables() -> Result<*const mmu::Tables, &'static str> { let tables = unsafe { read_volatile(core::ptr::addr_of!(CALLBACK_TABLES)) }; if tables.is_null() { Err("d4-tables-not-bound") } else { Ok(tables) } } #[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 el: u64; unsafe { asm!("mrs {v}, DAIF", v=out(reg)daif, options(nomem,nostack,preserves_flags)); asm!("mrs {v}, CurrentEL", v=out(reg)el, options(nomem,nostack,preserves_flags)); } if daif & 0x3c0 != 0x3c0 || el != 4 { return Err("d4-owner-context"); } super::d5_smp::authorize_service_cpu()?; 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,2),(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), (79,core::ptr::addr_of!(super::d6_accounting::OS_PRODUCT_D6_PROBE_OWNERSHIP) as u64),(80,768), (81,core::ptr::addr_of!(super::d6_accounting::OS_PRODUCT_D6_PROBE_INVENTORY) as u64),(82,49152), ] { 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)?; if get(51) != 0 && get(63) == 0 { return Err("d4-admission-closed"); } 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)?; if get(11) == 1 { // This is the live retained channel with the actual first EL0 // request pending. A failed drain must preserve that request and // its capabilities; this is not a throwaway negative model. if channel::drain() != Err("d4-channel-not-drained") { return Err("d4-live-channel-drain-was-admitted"); } add(25,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) } /// D3 invokes this from the real INIT syscall while the exact old identity has /// been reaped and a new generation occupies the same physical resident slot. /// The caller remains Running; permitting this probe does not relax the normal /// D4 two-resident admission rule while the transient child is actually live. pub(super) fn probe_stale_identity(caller: Id, stale: Id, replacement: Id) -> Result<(), &'static str> { guard()?; let live = owner::snapshot()?; if live.boot_id != get(2) || live.init != caller || live.current != Some(caller) || owner::state(caller)? != owner::State::Running || owner::pid(caller) != get(6) || u64::from(caller.slot) != get(4) || caller.generation != get(5) || stale == replacement || stale.slot != replacement.slot || stale.generation >= replacement.generation { return Err("d4-stale-probe-caller-binding"); } let _receipt = channel::validate_stale(caller,stale,replacement)?; add(78,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"); } message(&payload[..length],sequence)?; let mut physical_payload = [0u8; MESSAGE]; if super::d6_accounting::initialized()? { if unsafe { (&*core::ptr::addr_of!(HEAP_PAYLOAD)).is_some() } { return Err("d4-pending-heap-token-retained"); } let runtime = callback_runtime()?; let token = unsafe { super::d6_accounting::heap_allocate(&mut *runtime,caller,&payload[..length])? }; unsafe { core::ptr::write(core::ptr::addr_of_mut!(HEAP_PAYLOAD),Some(token)); } put(64,1); add(65,1)?; put(68,sequence); put(69,length as u64); put(70,1); put(71,owner::pid(caller)); let token = unsafe { (&*core::ptr::addr_of!(HEAP_PAYLOAD)).as_ref() }.ok_or("d4-heap-token-missing")?; if super::d6_accounting::heap_read(token,caller,&mut physical_payload)? != length { return Err("d4-physical-payload-length"); } add(66,1)?; } else { physical_payload.copy_from_slice(&payload[..length]); } let request = &physical_payload[..length]; // The bytes handed to VirtIO below were read from this real heap object // when full accounting is initialized, not from an accounting-only dummy. message(request,sequence)?; let mut frame = [0u8; 2048]; if get(49) == 0 { let arp_length = wire::build_arp_request(&mut frame).map_err(|_| "d4-build-arp")?; device::send(&frame[..arp_length])?; add(49,1)?; let arp_deadline = clock().checked_add(get(22).checked_mul(2).ok_or("d4-deadline-overflow")?).ok_or("d4-deadline-overflow")?; loop { if clock() >= arp_deadline { add(28,1)?; return Err("d4-arp-reply-timeout"); } let Some(length) = device::poll_receive(&mut frame)? else { core::hint::spin_loop(); continue; }; wire::validate_arp_reply(&frame[..length]).map_err(|_| "d4-arp-reply-invalid")?; add(52,1)?; break; } } // The second real datagram has no deliberately malformed predecessor. // Its existing RX descriptor is registered before publishing the UDP TX; // the isolated peer withholds that matching response beyond the actual // completion deadline. The stack-local non-Send ticket cannot outlive // this exclusive lease or migrate across an EL0 callback. let tracked = super::d5_smp::service_mode_active() && get(13) == 1; let mut completion = if tracked { let tables = callback_tables()?; let ticket = unsafe { device::begin_receive_completion(&*tables,caller)? }; put(74,sequence); put(75,clock()); Some(ticket) } else { None }; let timeout_fingerprint = if tracked { let inventory = device::accounting_inventory()?; let runtime = callback_runtime()?; let before = unsafe { super::d6_accounting::probe_ownership_begin(&mut *runtime,&inventory,5,None)? }; put(83,before.sequence); for (index,value) in before.words.into_iter().enumerate() { put(100+index,value); } Some(before) } else { None }; let bytes = wire::build_udp_request(sequence,request,&mut frame).map_err(|_| "d4-build-udp")?; device::send(&frame[..bytes])?; let seconds = if tracked { 8 } else { 2 }; let deadline = clock().checked_add(get(22).checked_mul(seconds).ok_or("d4-deadline-overflow")?).ok_or("d4-deadline-overflow")?; loop { if clock() >= deadline { add(28,1)?; return Err("d4-udp-reply-timeout"); } let received = match completion.as_mut() { Some(ticket) => device::poll_receive_with_completion(ticket,&mut frame)?, None => device::poll_receive(&mut frame)?, }; let Some(n) = received 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 tracked { device::require_completion_timeout_recovered()?; let before = timeout_fingerprint.ok_or("d4-timeout-inventory-token")?; let inventory = device::accounting_inventory()?; let runtime = callback_runtime()?; let after = unsafe { super::d6_accounting::probe_ownership_finish(&mut *runtime,&inventory,before,None)? }; for (index,value) in after.words.into_iter().enumerate() { put(104+index,value); } put(84,1); put(76,clock()); add(77,1)?; } 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); if get(70) == 1 { let token = unsafe { (&*core::ptr::addr_of!(HEAP_PAYLOAD)).as_ref() }.ok_or("d4-heap-token-missing")?; let runtime = callback_runtime()?; unsafe { super::d6_accounting::heap_release(&mut *runtime,caller,token)?; } // Clear only after actual heap release succeeded. All error paths // above preserve the original noncopy ownership token in place. let released = unsafe { core::ptr::replace(core::ptr::addr_of_mut!(HEAP_PAYLOAD),None) }; drop(released); add(67,1)?; put(68,0); put(70,0); } 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 || get(72) != 0 { return Err("d4-service-step-state"); } let _binding = RuntimeBinding::bind(runtime,tables)?; d3_shell::d4_step(runtime,tables,boot)?; put(10,d3_shell::service_rounds()); device::snapshot() } /// Called after a verified real D3/D4 round and its actual completion records, /// while the caller still holds RUNQUEUE rank10 and the global service lease. /// The peer is genuinely productive before it is withheld. Other CPUs keep /// dispatching; only the withheld CPU's own scheduler inventory must freeze. /// D6 separately compares all physical owners at stable round boundaries. pub(super) fn service_probes(runtime: *mut OsK660Runtime, _tables: *const mmu::Tables, _boot: *const BootData) -> Result<(), &'static str> { guard()?; if runtime.is_null() || get(3) != 2 || get(72) != 0 || !super::d5_smp::service_mode_active() || owner::snapshot()?.current.is_some() { return Err("d4-probe-service-boundary"); } // Complete the actual descriptor-timeout scenario first. Holding the // global lease during that bounded RX wait cannot count as another CPU // continuing to execute, so it is never mixed with the withheld-peer test. if get(77) != 1 { return Ok(()); } let phase = super::d5_smp::stall_probe_phase(); if phase == 0 { let Some(target) = super::d5_smp::stall_probe_candidate()? else { return Ok(()); }; if unsafe { read_volatile(core::ptr::addr_of!(STALL_FINGERPRINT)) }.is_some() { return Err("d4-stall-inventory-already-pending"); } let inventory = device::accounting_inventory()?; let before = unsafe { super::d6_accounting::probe_ownership_begin(&mut *runtime,&inventory,4,None)? }; unsafe { write_volatile(core::ptr::addr_of_mut!(STALL_FINGERPRINT),Some(before)); } put(85,before.sequence); for (index,value) in before.words.into_iter().enumerate() { put(92+index,value); } // No EL0 resume or lease release can intervene between the inventory // capture and this actual admission of the already validated target. super::d5_smp::begin_stall_probe(target)?; put(87,target as u64); put(88,clock()); } else if phase == 2 { if get(86) == 0 { let before = unsafe { read_volatile(core::ptr::addr_of!(STALL_FINGERPRINT)) } .ok_or("d4-stall-inventory-token-missing")?; let inventory = device::accounting_inventory()?; let after = unsafe { super::d6_accounting::probe_ownership_finish(&mut *runtime,&inventory,before,None)? }; for (index,value) in after.words.into_iter().enumerate() { put(96+index,value); } unsafe { write_volatile(core::ptr::addr_of_mut!(STALL_FINGERPRINT),None); } put(86,1); put(89,clock()); } if get(91) == 0 && super::d5_smp::stall_probe_recovered()? { put(90,clock()); put(91,1); } } else if phase != 1 { return Err("d4-stall-probe-unknown-phase"); } Ok(()) } fn finalize_processes(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); let _binding = RuntimeBinding::bind(runtime,tables)?; 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 || get(57) == 0 || get(58) == 0 || get(25) != 1 || get(49) != 1 || get(52) != 1 { return Err("d4-service-finish-receipts"); } Ok(()) } pub(super) fn service_finish(runtime: *mut OsK660Runtime, tables: *const mmu::Tables, boot: *const BootData) -> Result<(), &'static str> { finalize_processes(runtime,tables,boot)?; unsafe { begin_shutdown(&mut *runtime,&*tables,&*boot)?; } put(21,clock()); Ok(()) } /// Full-mode duration sampling stops dispatch without closing either actual /// process or dropping the final queued response. D7 will resume one final /// SHELL/INIT round after every secondary service worker has really joined. pub(super) fn service_quiesce(_runtime: *mut OsK660Runtime, _tables: *const mmu::Tables, _boot: *const BootData) -> Result<(), &'static str> { guard()?; if get(3) != 2 || get(72) != 0 || get(63) != 0 || get(55) != 0 || owner::snapshot()?.current.is_some() || get(11) == 0 || get(11) != get(12) || get(11) != get(13) || get(70) != 0 { return Err("d4-quiesce-pending-work"); } let pending = channel::snapshot()?; if pending.request_depth != 0 || pending.response_depth == 0 || pending.responses_sent != get(13) || pending.responses_received != get(46) || pending.outstanding != pending.response_depth { return Err("d4-quiesce-channel-binding"); } put(72,1); put(73,clock()); device::snapshot() } pub(super) fn service_rounds() -> u64 { get(10) } pub(super) fn live_free() -> u64 { get(39) } /// Read only under the real dispatch lease, or on the boot CPU after every /// initialized D5 worker joined and service mode ended. Plain owner fields /// are never sampled concurrently by an unleased observer. pub(super) fn local_probes_complete() -> Result { guard()?; let cpus = super::d5_smp::initialized_cpu_count(); if !matches!(cpus,1|2|4) || (!super::d5_smp::service_mode_active() && !super::d5_smp::stopped()) { return Err("d4-probe-read-without-lease-or-join"); } let timeout = get(74) == 2 && get(75) != 0 && get(76) > get(75) && get(77) == 1 && get(83) != 0 && get(84) == 1 && get(70) == 0 && get(68) == 0 // Both actual roles must execute useful later work; completing the // delayed descriptor alone cannot satisfy this continuing-service gate. && get(13) > get(74) && get(46) > get(74); let peer = if cpus == 1 { // A sole physical CPU has no second CPU to withhold. Do not create a // peer receipt from a loop, fictitious slot or elapsed host sleep. get(85) == 0 && get(86) == 0 && get(91) == 0 } else { get(85) != 0 && get(86) == 1 && get(88) != 0 && get(89) > get(88) && get(90) >= get(89) && get(91) == 1 }; Ok(timeout && peer) } 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 mask15 workload never starts the D5 lifecycle. Its absence is // distinct from initialized workers which have not really joined. if super::d5_smp::lifecycle_initialized() && !super::d5_smp::stopped() { return Err("d4-shutdown-secondary-workers-live"); } if get(55) == 0 { if get(72) != 1 { return Err("d4-shutdown-not-quiesced"); } finalize_processes(runtime as *mut _,tables as *const _,boot as *const _)?; } // 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 || get(70) != 0 || unsafe { (&*core::ptr::addr_of!(HEAP_PAYLOAD)).is_some() } { 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); put(21,clock()); 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,2),(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(()) }