//! Retained, allocation-free IPC for the native INIT/SHELL execution owners. //! //! Endpoints are real ProcessIds, never fabricated Scheduler TaskIds. The D3 //! dispatcher remains responsible for entering the independent EL0 address //! spaces and validating their userspace buffers before copying bytes here. //! Each operation checks both endpoint lifetimes and the actual Running caller. //! Replies require a request which the service actually dequeued. Four pending //! slots bound the entire request/reply lifetime, including queued responses. use super::process_owner::{self, Id, State}; use core::sync::atomic::{Ordering, compiler_fence}; pub(super) const CAPACITY: usize = 4; pub(super) const MAX_PAYLOAD: usize = 128; const EMPTY_ID: Id = Id { slot: u8::MAX, generation: 0, }; pub(super) const ABI_VERSION: u64 = 1; /// ABI word 0 is valid only after the real endpoints have been bound. All /// counters describe performed operations or refusals, never expected totals. /// /// Words 0..31: valid, ABI, boot, state, service(slot,generation), client /// (slot,generation), capacity, payload bound, next sequence, request depth, /// response depth, outstanding, request sent/received, response sent/received, /// request/response byte totals, request/response high-water marks, refusal /// counts (full, stale, foreign, closing, buffer, sequence, empty, drain), /// successful close calls, successful queue-drain calls. /// Words 32..95: eight physical ring slots, request four then response four, /// with present, sequence, source(slot,generation), destination(slot,generation), /// length, and FNV-1a-64 of exactly that payload's length (eight words each). /// Words 96..119: four pending records: sequence, state (vacant/queued/ /// delivered/responded/completed = 0/1/2/3/4), request length, response length, /// request hash, response hash. Words 120..127: request/response heads, /// not-running/dead-endpoint refusals, service/client raw capability handles, /// actual capability acquisitions, actual capability retirements. #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D4_CHANNEL: [u64; 128] = [u64::MAX; 128]; /// Four request and four response ring slots, each MAX_PAYLOAD bytes. Consumed /// bytes remain as evidence; metadata's present flag distinguishes live data. #[unsafe(no_mangle)] pub static mut OS_PRODUCT_D4_CHANNEL_BUFFERS: [u8; 1024] = [0; 1024]; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Receipt { pub sequence: u64, pub source: Id, pub destination: Id, pub length: usize, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct Snapshot { pub boot_id: u64, pub service: Id, pub client: Id, /// 1: accepting; 2: closing/completing; 3: drained; 4: retiring handles. pub state: u64, pub next_sequence: u64, pub request_depth: u64, pub response_depth: u64, pub outstanding: u64, pub requests_sent: u64, pub requests_received: u64, pub responses_sent: u64, pub responses_received: u64, pub request_bytes: u64, pub response_bytes: u64, pub full_rejections: u64, pub stale_rejections: u64, pub foreign_rejections: u64, pub closing_rejections: u64, pub buffer_rejections: u64, pub sequence_rejections: u64, pub empty_rejections: u64, pub drain_rejections: u64, pub not_running_rejections: u64, pub dead_endpoint_rejections: u64, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Error { Uninitialized, Boot, Endpoints, Stale, Foreign, Destination, NotRunning, DeadEndpoint, Full, Closing, Buffer, Sequence, Empty, NotDrained, } impl Error { const fn tag(self) -> &'static str { match self { Self::Uninitialized => "d4-channel-uninitialized", Self::Boot => "d4-channel-boot-mismatch", Self::Endpoints => "d4-channel-endpoint-mismatch", Self::Stale => "d4-channel-stale-generation", Self::Foreign => "d4-channel-foreign-endpoint", Self::Destination => "d4-channel-destination", Self::NotRunning => "d4-channel-caller-not-running", Self::DeadEndpoint => "d4-channel-endpoint-not-live", Self::Full => "d4-channel-full", Self::Closing => "d4-channel-closed", Self::Buffer => "d4-channel-invalid-buffer", Self::Sequence => "d4-channel-sequence", Self::Empty => "d4-channel-empty", Self::NotDrained => "d4-channel-not-drained", } } } #[derive(Clone, Copy)] struct Message { present: bool, receipt: Receipt, bytes: [u8; MAX_PAYLOAD], } impl Message { const EMPTY: Self = Self { present: false, receipt: Receipt { sequence: 0, source: EMPTY_ID, destination: EMPTY_ID, length: 0, }, bytes: [0; MAX_PAYLOAD], }; fn new(source: Id, destination: Id, sequence: u64, payload: &[u8]) -> Self { let mut bytes = [0; MAX_PAYLOAD]; bytes[..payload.len()].copy_from_slice(payload); Self { present: true, receipt: Receipt { sequence, source, destination, length: payload.len(), }, bytes, } } } struct Queue { slots: [Message; CAPACITY], head: usize, count: usize, high_water: usize, } impl Queue { const fn new() -> Self { Self { slots: [Message::EMPTY; CAPACITY], head: 0, count: 0, high_water: 0, } } fn push(&mut self, message: Message) -> Result<(), Error> { if self.count == CAPACITY { return Err(Error::Full); } let tail = (self.head + self.count) % CAPACITY; self.slots[tail] = message; self.count += 1; self.high_water = self.high_water.max(self.count); Ok(()) } fn front(&self) -> Result { if self.count == 0 { Err(Error::Empty) } else { Ok(self.slots[self.head]) } } fn pop(&mut self) { // Retain the actual payload/receipt for raw evidence, but never deliver // this consumed slot again unless a later push explicitly replaces it. self.slots[self.head].present = false; self.head = (self.head + 1) % CAPACITY; self.count -= 1; } } #[derive(Clone, Copy, PartialEq, Eq)] enum PendingState { Vacant, Queued, Delivered, Responded, Completed, } #[derive(Clone, Copy)] struct Pending { sequence: u64, state: PendingState, request_length: usize, response_length: usize, request_hash: u64, response_hash: u64, } impl Pending { const EMPTY: Self = Self { sequence: 0, state: PendingState::Vacant, request_length: 0, response_length: 0, request_hash: 0, response_hash: 0, }; fn active(&self) -> bool { !matches!(self.state, PendingState::Vacant | PendingState::Completed) } } #[derive(Clone, Copy)] struct Counters { requests_sent: u64, requests_received: u64, responses_sent: u64, responses_received: u64, request_bytes: u64, response_bytes: u64, full: u64, stale: u64, foreign: u64, closing: u64, buffer: u64, sequence: u64, empty: u64, not_drained: u64, close_calls: u64, drain_calls: u64, not_running: u64, dead_endpoint: u64, } impl Counters { const ZERO: Self = Self { requests_sent: 0, requests_received: 0, responses_sent: 0, responses_received: 0, request_bytes: 0, response_bytes: 0, full: 0, stale: 0, foreign: 0, closing: 0, buffer: 0, sequence: 0, empty: 0, not_drained: 0, close_calls: 0, drain_calls: 0, not_running: 0, dead_endpoint: 0, }; } struct Channel { boot_id: u64, service: Id, client: Id, state: u64, next_sequence: u64, requests: Queue, responses: Queue, pending: [Pending; CAPACITY], counters: Counters, service_handle: u64, client_handle: u64, handles_opened: u64, handles_closed: u64, } impl Channel { const fn new() -> Self { Self { boot_id: 0, service: EMPTY_ID, client: EMPTY_ID, state: 0, next_sequence: 1, requests: Queue::new(), responses: Queue::new(), pending: [Pending::EMPTY; CAPACITY], counters: Counters::ZERO, service_handle: 0, client_handle: 0, handles_opened: 0, handles_closed: 0, } } fn open( &mut self, boot: u64, service: Id, client: Id, state: &mut impl FnMut(Id) -> Result, ) -> Result<(), Error> { if boot == 0 { return Err(Error::Boot); } if service == client || service.slot == client.slot || service.generation == 0 || client.generation == 0 { return Err(Error::Endpoints); } for id in [service, client] { if matches!(state(id)?, State::Exited(_)) { return Err(Error::DeadEndpoint); } } if self.state != 0 { if self.boot_id != boot { return Err(Error::Boot); } if self.service != service || self.client != client { return Err(Error::Endpoints); } // Idempotent attachment never resets counters, queues, or closing. return Ok(()); } self.boot_id = boot; self.service = service; self.client = client; self.state = 1; Ok(()) } fn endpoints_live( &self, state: &mut impl FnMut(Id) -> Result, ) -> Result<(), Error> { if self.state == 0 { return Err(Error::Uninitialized); } for id in [self.service, self.client] { if matches!(state(id)?, State::Exited(_)) { return Err(Error::DeadEndpoint); } } Ok(()) } fn caller( &self, caller: Id, state: &mut impl FnMut(Id) -> Result, ) -> Result { if self.state == 0 { return Err(Error::Uninitialized); } // The full Id is checked before using any index. Matching a slot alone // never authorizes an endpoint, even after the process table recycles it. if caller != self.client && caller != self.service { return Err( if caller.slot == self.client.slot || caller.slot == self.service.slot { Error::Stale } else { // Reject an unbound endpoint before consulting process_owner. // A fabricated lookup must not perturb D3's actual retained // process-table stale-rejection evidence. Error::Foreign }, ); } self.endpoints_live(state)?; if state(caller)? != State::Running { return Err(Error::NotRunning); } Ok(caller == self.client) } fn note(&mut self, result: &Result<(), Error>) { let counter = match result { Err(Error::Full) => &mut self.counters.full, Err(Error::Stale) => &mut self.counters.stale, Err(Error::Foreign) => &mut self.counters.foreign, Err(Error::Closing) => &mut self.counters.closing, Err(Error::Buffer) => &mut self.counters.buffer, Err(Error::Sequence) => &mut self.counters.sequence, Err(Error::Empty) => &mut self.counters.empty, Err(Error::NotDrained) => &mut self.counters.not_drained, Err(Error::NotRunning) => &mut self.counters.not_running, Err(Error::DeadEndpoint) => &mut self.counters.dead_endpoint, _ => return, }; *counter = counter.saturating_add(1); } fn send( &mut self, caller: Id, destination: Id, sequence: u64, payload: &[u8], state: &mut impl FnMut(Id) -> Result, ) -> Result<(), Error> { let result = self.send_inner(caller, destination, sequence, payload, state); self.note(&result); result } fn send_inner( &mut self, caller: Id, destination: Id, sequence: u64, payload: &[u8], state: &mut impl FnMut(Id) -> Result, ) -> Result<(), Error> { let from_client = self.caller(caller, state)?; let expected = if from_client { self.service } else { self.client }; if destination != expected { return Err(if destination.slot == expected.slot { Error::Stale } else { Error::Foreign }); } if payload.is_empty() || payload.len() > MAX_PAYLOAD { return Err(Error::Buffer); } if self.state >= 3 || (from_client && self.state != 1) { return Err(Error::Closing); } let message = Message::new(caller, destination, sequence, payload); if from_client { if sequence == 0 || sequence != self.next_sequence || sequence == u64::MAX { return Err(Error::Sequence); } let index = self .pending .iter() .position(|p| !p.active()) .ok_or(Error::Full)?; self.requests.push(message)?; self.pending[index] = Pending { sequence, state: PendingState::Queued, request_length: payload.len(), response_length: 0, request_hash: hash(payload), response_hash: 0, }; self.next_sequence += 1; self.counters.requests_sent = self.counters.requests_sent.saturating_add(1); self.counters.request_bytes = self .counters .request_bytes .saturating_add(payload.len() as u64); } else { let index = self .pending .iter() .position(|p| p.sequence == sequence && p.state == PendingState::Delivered) .ok_or(Error::Sequence)?; self.responses.push(message)?; self.pending[index].state = PendingState::Responded; self.pending[index].response_length = payload.len(); self.pending[index].response_hash = hash(payload); self.counters.responses_sent = self.counters.responses_sent.saturating_add(1); self.counters.response_bytes = self .counters .response_bytes .saturating_add(payload.len() as u64); } Ok(()) } fn receive( &mut self, caller: Id, out: &mut [u8], state: &mut impl FnMut(Id) -> Result, ) -> Result { let result = self.receive_inner(caller, out, state); self.note(&result.as_ref().map(|_| ()).map_err(|e| *e)); result } fn receive_inner( &mut self, caller: Id, out: &mut [u8], state: &mut impl FnMut(Id) -> Result, ) -> Result { let to_client = self.caller(caller, state)?; if self.state >= 3 { return Err(Error::Closing); } let message = if to_client { self.responses.front()? } else { self.requests.front()? }; if message.receipt.destination != caller { return Err(Error::Endpoints); } if out.len() < message.receipt.length { return Err(Error::Buffer); } let wanted = if to_client { PendingState::Responded } else { PendingState::Queued }; let index = self .pending .iter() .position(|p| p.sequence == message.receipt.sequence && p.state == wanted) .ok_or(Error::Sequence)?; // No message is consumed on validation/short-buffer failure. out[..message.receipt.length].copy_from_slice(&message.bytes[..message.receipt.length]); if to_client { self.responses.pop(); self.pending[index].state = PendingState::Completed; self.counters.responses_received = self.counters.responses_received.saturating_add(1); } else { self.requests.pop(); self.pending[index].state = PendingState::Delivered; self.counters.requests_received = self.counters.requests_received.saturating_add(1); } Ok(message.receipt) } fn close_client( &mut self, caller: Id, state: &mut impl FnMut(Id) -> Result, ) -> Result<(), Error> { let result = (|| { if !self.caller(caller, state)? { return Err(Error::Foreign); } if self.state >= 3 { return Err(Error::Closing); } self.state = 2; self.counters.close_calls = self.counters.close_calls.saturating_add(1); Ok(()) })(); self.note(&result); result } fn drain(&mut self, state: &mut impl FnMut(Id) -> Result) -> Result<(), Error> { let result = (|| { self.endpoints_live(state)?; if self.state == 1 || self.requests.count != 0 || self.responses.count != 0 || self.pending.iter().any(Pending::active) { return Err(Error::NotDrained); } self.state = 3; self.counters.drain_calls = self.counters.drain_calls.saturating_add(1); Ok(()) })(); self.note(&result); result } fn snapshot(&self) -> Result { if self.state == 0 { return Err(Error::Uninitialized); } let c = self.counters; Ok(Snapshot { boot_id: self.boot_id, service: self.service, client: self.client, state: self.state, next_sequence: self.next_sequence, request_depth: self.requests.count as u64, response_depth: self.responses.count as u64, outstanding: self.pending.iter().filter(|p| p.active()).count() as u64, requests_sent: c.requests_sent, requests_received: c.requests_received, responses_sent: c.responses_sent, responses_received: c.responses_received, request_bytes: c.request_bytes, response_bytes: c.response_bytes, full_rejections: c.full, stale_rejections: c.stale, foreign_rejections: c.foreign, closing_rejections: c.closing, buffer_rejections: c.buffer, sequence_rejections: c.sequence, empty_rejections: c.empty, drain_rejections: c.not_drained, not_running_rejections: c.not_running, dead_endpoint_rejections: c.dead_endpoint, }) } fn persisted_drained(&self) -> bool { // This is a read-only historical receipt, not permission to operate an // endpoint after D7 retires its process metadata. Both real capability // close calls completed before state 3 could be published. self.state == 3 && self.handles_opened == 2 && self.handles_closed == 2 && self.service_handle != 0 && self.client_handle != 0 && self.service_handle != self.client_handle && self.requests.count == 0 && self.responses.count == 0 && self.requests.slots.iter().all(|m| !m.present) && self.responses.slots.iter().all(|m| !m.present) && self.pending.iter().all(|p| !p.active()) && self.counters.requests_sent == self.counters.requests_received && self.counters.requests_sent == self.counters.responses_sent && self.counters.requests_sent == self.counters.responses_received } fn evidence(&self) -> Result<([u64; 128], [u8; 1024]), Error> { let s = self.snapshot()?; let mut words = [0; 128]; words[..32].copy_from_slice(&[ 1, ABI_VERSION, s.boot_id, s.state, u64::from(s.service.slot), s.service.generation, u64::from(s.client.slot), s.client.generation, CAPACITY as u64, MAX_PAYLOAD as u64, s.next_sequence, s.request_depth, s.response_depth, s.outstanding, s.requests_sent, s.requests_received, s.responses_sent, s.responses_received, s.request_bytes, s.response_bytes, self.requests.high_water as u64, self.responses.high_water as u64, s.full_rejections, s.stale_rejections, s.foreign_rejections, s.closing_rejections, s.buffer_rejections, s.sequence_rejections, s.empty_rejections, s.drain_rejections, self.counters.close_calls, self.counters.drain_calls, ]); let mut bytes = [0; 1024]; for (queue, base) in [(&self.requests, 0), (&self.responses, CAPACITY)] { for (i, message) in queue.slots.iter().enumerate() { let n = base + i; let w = 32 + n * 8; let r = message.receipt; words[w..w + 8].copy_from_slice(&[ u64::from(message.present), r.sequence, u64::from(r.source.slot), r.source.generation, u64::from(r.destination.slot), r.destination.generation, r.length as u64, hash(&message.bytes[..r.length]), ]); bytes[n * MAX_PAYLOAD..(n + 1) * MAX_PAYLOAD].copy_from_slice(&message.bytes); } } for (index, pending) in self.pending.iter().enumerate() { let base = 96 + index * 6; words[base..base + 6].copy_from_slice(&[ pending.sequence, match pending.state { PendingState::Vacant => 0, PendingState::Queued => 1, PendingState::Delivered => 2, PendingState::Responded => 3, PendingState::Completed => 4, }, pending.request_length as u64, pending.response_length as u64, pending.request_hash, pending.response_hash, ]); } words[120] = self.requests.head as u64; words[121] = self.responses.head as u64; words[122] = self.counters.not_running; words[123] = self.counters.dead_endpoint; words[124] = self.service_handle; words[125] = self.client_handle; words[126] = self.handles_opened; words[127] = self.handles_closed; Ok((words, bytes)) } } fn hash(bytes: &[u8]) -> u64 { bytes.iter().fold(0xcbf2_9ce4_8422_2325, |value, byte| { (value ^ u64::from(*byte)).wrapping_mul(0x0000_0100_0000_01b3) }) } static mut BUSY: bool = false; static mut OWNER: Channel = Channel::new(); struct Access; impl Drop for Access { fn drop(&mut self) { compiler_fence(Ordering::SeqCst); unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(BUSY), false); } } } fn require_boot_cpu() -> Result<(), &'static str> { #[cfg(target_arch = "aarch64")] { let cpu: u64; let el: u64; let daif: u64; unsafe { core::arch::asm!( "mrs {cpu}, MPIDR_EL1", "mrs {el}, CurrentEL", "mrs {daif}, DAIF", cpu = out(reg) cpu, el = out(reg) el, daif = out(reg) daif, options(nomem, nostack, preserves_flags) ); } if cpu & 0x0000_00ff_00ff_ffff != 0 || el != 4 || daif & 0x3c0 != 0x3c0 { return Err("d4-channel-masked-boot-cpu-required"); } Ok(()) } #[cfg(not(target_arch = "aarch64"))] Err("d4-channel-native-el1-required") } fn actual_state(id: Id) -> Result { process_owner::state(id).map_err(|error| match error { "process-owner-stale-id" => Error::Stale, _ => Error::DeadEndpoint, }) } fn access(f: impl FnOnce(&mut Channel) -> Result) -> Result { require_boot_cpu()?; unsafe { if core::ptr::read_volatile(core::ptr::addr_of!(BUSY)) { return Err("d4-channel-reentrant-access"); } core::ptr::write_volatile(core::ptr::addr_of_mut!(BUSY), true); } compiler_fence(Ordering::SeqCst); let _access = Access; // As in process_owner, this is only a fully masked boot-CPU reentry guard, // never an SMP lock. No mutable reference may escape across ERET/unmasking. let owner = unsafe { &mut *core::ptr::addr_of_mut!(OWNER) }; #[cfg(not(test))] if owner.state == 1 || owner.state == 2 { if owner.handles_opened != 2 || owner.handles_closed != 0 || super::d6_accounting::channel_validate(owner.service, owner.service_handle)? != owner.boot_id || super::d6_accounting::channel_validate(owner.client, owner.client_handle)? != owner.boot_id { return Err("d4-channel-capability-binding"); } } let result = f(owner); if let Ok((words, bytes)) = owner.evidence() { unsafe { core::ptr::write_volatile(core::ptr::addr_of_mut!(OS_PRODUCT_D4_CHANNEL), words); core::ptr::write_volatile( core::ptr::addr_of_mut!(OS_PRODUCT_D4_CHANNEL_BUFFERS), bytes, ); } } result.map_err(Error::tag) } /// Attach the actual retained INIT and its retained SHELL child. A second call /// cannot replace endpoints or reset any existing progress/closing state. pub(super) fn open(boot: u64, init: Id, shell: Id) -> Result<(), &'static str> { access(|owner| { let processes = process_owner::snapshot().map_err(|_| Error::DeadEndpoint)?; if processes.boot_id != boot || processes.init != init { return Err(Error::Boot); } if process_owner::parent(shell).map_err(|_| Error::Stale)? != Some(init) { return Err(Error::Endpoints); } #[cfg(not(test))] if owner.state == 0 { if owner.handles_opened != 0 { return Err(Error::Endpoints); } // Acquire actual owner-scoped kernel capabilities. A failed second // acquisition retires the first; no partially open channel escapes. let service_handle = super::d6_accounting::channel_open(init, boot).map_err(|_| Error::Endpoints)?; let client_handle = match super::d6_accounting::channel_open(shell, boot) { Ok(handle) => handle, Err(_) => { // If retirement itself fails, retain the token rather than // falsely reporting that its resource was released. if super::d6_accounting::channel_close(init, service_handle).is_err() { owner.service_handle = service_handle; owner.handles_opened = 1; } return Err(Error::Endpoints); } }; owner.service_handle = service_handle; owner.client_handle = client_handle; owner.handles_opened = 2; } owner.open(boot, init, shell, &mut actual_state) }) } pub(super) fn send( caller: Id, destination: Id, sequence: u64, payload: &[u8], ) -> Result<(), &'static str> { access(|owner| { let bad_destination = (caller == owner.client && destination != owner.service) || (caller == owner.service && destination != owner.client); owner .send(caller, destination, sequence, payload, &mut actual_state) .map_err(|error| { if bad_destination && matches!(error, Error::Stale | Error::Foreign) { Error::Destination } else { error } }) }) } pub(super) fn receive(caller: Id, out: &mut [u8]) -> Result { access(|owner| owner.receive(caller, out, &mut actual_state)) } pub(super) fn request(sender: Id, payload: &[u8]) -> Result { access(|owner| { if sender != owner.client { let result = owner .caller(sender, &mut actual_state) .and(Err(Error::Foreign)); owner.note(&result); return result.map(|_| 0); } let sequence = owner.next_sequence; owner.send(sender, owner.service, sequence, payload, &mut actual_state)?; Ok(sequence) }) } pub(super) fn respond(sender: Id, sequence: u64, payload: &[u8]) -> Result<(), &'static str> { access(|owner| { if sender != owner.service { let result = owner .caller(sender, &mut actual_state) .and(Err(Error::Foreign)); owner.note(&result); return result; } owner.send(sender, owner.client, sequence, payload, &mut actual_state) }) } pub(super) fn response(receiver: Id, out: &mut [u8]) -> Result { access(|owner| { if receiver != owner.client { let result = owner .caller(receiver, &mut actual_state) .and(Err(Error::Foreign)); owner.note(&result); return result.map(|_| unreachable!()); } owner.receive(receiver, out, &mut actual_state) }) } pub(super) fn close_client(sender: Id) -> Result<(), &'static str> { access(|owner| owner.close_client(sender, &mut actual_state)) } /// Only a client close followed by actual request/reply completion can yield a /// drain receipt. A timeout, live queue, or exited endpoint cannot become clean. pub(super) fn drain() -> Result<(), &'static str> { access(|owner| { owner.drain(&mut actual_state)?; #[cfg(not(test))] { owner.state = 4; } #[cfg(not(test))] if owner.handles_closed == 0 { super::d6_accounting::channel_close(owner.service, owner.service_handle) .map_err(|_| Error::NotDrained)?; owner.handles_closed = 1; } #[cfg(not(test))] if owner.handles_closed == 1 { super::d6_accounting::channel_close(owner.client, owner.client_handle) .map_err(|_| Error::NotDrained)?; owner.handles_closed = 2; } owner.state = 3; Ok(()) }) } pub(super) fn snapshot() -> Result { access(|owner| { if !owner.persisted_drained() { owner.endpoints_live(&mut actual_state)?; } owner.snapshot() }) } pub(super) fn identities() -> Result<(Id, Id), &'static str> { snapshot().map(|s| (s.service, s.client)) } pub(super) fn is_drained() -> Result { access(|owner| { if owner.persisted_drained() { return Ok(true); } if owner.state == 3 { return Err(Error::NotDrained); } owner.endpoints_live(&mut actual_state)?; Ok(false) }) } #[cfg(test)] mod tests { use super::*; use turkos_kernel::process::ProcessTable; struct Fixture { table: ProcessTable, service: Id, client: Id, channel: Channel, } fn state(table: &ProcessTable, id: Id) -> Result { table.state(id).map_err(|_| Error::Stale) } impl Fixture { fn new() -> Self { let mut table = ProcessTable::new(); let service = table.create().unwrap(); let client = table.create().unwrap(); let mut channel = Channel::new(); channel .open(99, service, client, &mut |id| state(&table, id)) .unwrap(); Self { table, service, client, channel, } } fn run(&mut self, id: Id) { for other in [self.service, self.client] { if self.table.state(other) == Ok(State::Running) { self.table.yield_ready(other).unwrap(); } } self.table.run(id).unwrap(); } fn send(&mut self, caller: Id, dest: Id, sequence: u64, bytes: &[u8]) -> Result<(), Error> { self.channel.send(caller, dest, sequence, bytes, &mut |id| { state(&self.table, id) }) } fn receive(&mut self, caller: Id, out: &mut [u8]) -> Result { self.channel .receive(caller, out, &mut |id| state(&self.table, id)) } } #[test] fn round_trip_copies_actual_bytes_and_full_endpoint_identities() { let mut f = Fixture::new(); f.run(f.client); f.send(f.client, f.service, 1, b"shell:udp:nonce=461") .unwrap(); assert_eq!(f.channel.snapshot().unwrap().outstanding, 1); f.run(f.service); let mut bytes = [0; MAX_PAYLOAD]; let req = f.receive(f.service, &mut bytes).unwrap(); assert_eq!( req, Receipt { sequence: 1, source: f.client, destination: f.service, length: 19 } ); assert_eq!(&bytes[..req.length], b"shell:udp:nonce=461"); f.send(f.service, f.client, req.sequence, b"net:udp:nonce=461") .unwrap(); f.run(f.client); let response = f.receive(f.client, &mut bytes).unwrap(); assert_eq!(response.source, f.service); assert_eq!(response.destination, f.client); assert_eq!(response.sequence, req.sequence); assert_eq!(&bytes[..response.length], b"net:udp:nonce=461"); let s = f.channel.snapshot().unwrap(); assert_eq!( ( s.requests_sent, s.requests_received, s.responses_sent, s.responses_received ), (1, 1, 1, 1) ); assert_eq!( (s.request_depth, s.response_depth, s.outstanding), (0, 0, 0) ); let (words, buffers) = f.channel.evidence().unwrap(); assert_eq!(words[32], 0); // consumed request is not live assert_eq!(words[33], 1); assert_eq!(&buffers[..19], b"shell:udp:nonce=461"); assert_eq!(&buffers[512..529], b"net:udp:nonce=461"); assert_eq!(words[97], 4); // completed pending transaction } #[test] fn four_outstanding_bound_capacity_even_after_server_dequeues_requests() { let mut f = Fixture::new(); f.run(f.client); for sequence in 1..=4 { f.send(f.client, f.service, sequence, &[sequence as u8]) .unwrap(); } assert_eq!( f.send(f.client, f.service, 5, b"overflow"), Err(Error::Full) ); assert_eq!(f.channel.next_sequence, 5); f.run(f.service); let mut bytes = [0; MAX_PAYLOAD]; for sequence in 1..=4 { let request = f.receive(f.service, &mut bytes).unwrap(); assert_eq!(request.sequence, sequence); f.send(f.service, f.client, sequence, &[sequence as u8, 9]) .unwrap(); } f.run(f.client); assert_eq!( f.send(f.client, f.service, 5, b"still-pending"), Err(Error::Full) ); assert_eq!(f.receive(f.client, &mut bytes).unwrap().sequence, 1); f.send(f.client, f.service, 5, b"credit-returned").unwrap(); assert_eq!(f.channel.snapshot().unwrap().full_rejections, 2); assert_eq!(f.channel.snapshot().unwrap().outstanding, 4); } #[test] fn short_or_oversize_buffers_do_not_consume_or_publish_messages() { let mut f = Fixture::new(); f.run(f.client); assert_eq!(f.send(f.client, f.service, 1, b""), Err(Error::Buffer)); assert_eq!( f.send(f.client, f.service, 1, &[7; MAX_PAYLOAD + 1]), Err(Error::Buffer) ); assert_eq!(f.channel.next_sequence, 1); f.send(f.client, f.service, 1, b"actual").unwrap(); f.run(f.service); let mut short = [99; 5]; assert_eq!(f.receive(f.service, &mut short), Err(Error::Buffer)); assert_eq!(short, [99; 5]); assert_eq!(f.channel.requests.count, 1); let mut full = [0; 6]; assert_eq!(f.receive(f.service, &mut full).unwrap().length, 6); assert_eq!(&full, b"actual"); assert_eq!(f.channel.snapshot().unwrap().buffer_rejections, 3); } #[test] fn forged_generation_foreign_endpoint_and_nonrunning_caller_are_rejected() { let mut f = Fixture::new(); f.run(f.client); let forged = Id { generation: f.client.generation + 100, ..f.client }; assert_eq!(f.send(forged, f.service, 1, b"x"), Err(Error::Stale)); let wrong_destination = Id { generation: f.service.generation + 100, ..f.service }; assert_eq!( f.send(f.client, wrong_destination, 1, b"x"), Err(Error::Stale) ); let foreign = f.table.create().unwrap(); assert_eq!(f.send(foreign, f.service, 1, b"x"), Err(Error::Foreign)); assert_eq!(f.send(f.client, foreign, 1, b"x"), Err(Error::Foreign)); assert_eq!(f.send(f.service, f.client, 1, b"x"), Err(Error::NotRunning)); let s = f.channel.snapshot().unwrap(); assert_eq!( ( s.stale_rejections, s.foreign_rejections, s.not_running_rejections ), (2, 2, 1) ); assert_eq!((s.requests_sent, s.next_sequence), (0, 1)); } #[test] fn exit_reap_and_slot_reuse_never_rebind_retained_endpoint() { let mut f = Fixture::new(); f.table.exit(f.client, -11).unwrap(); f.run(f.service); assert_eq!( f.send(f.service, f.client, 1, b"x"), Err(Error::DeadEndpoint) ); f.table.reap(f.client).unwrap(); let replacement = f.table.create().unwrap(); assert_eq!(replacement.slot, f.client.slot); assert_ne!(replacement.generation, f.client.generation); assert_eq!(f.send(replacement, f.service, 1, b"x"), Err(Error::Stale)); assert_eq!(f.send(f.service, f.client, 1, b"x"), Err(Error::Stale)); assert_eq!( f.channel .open(99, f.service, replacement, &mut |id| state(&f.table, id)), Err(Error::Endpoints) ); assert_eq!(f.channel.client, f.client); } #[test] fn reply_requires_dequeued_request_and_rejects_duplicate_response() { let mut f = Fixture::new(); f.run(f.service); assert_eq!( f.send(f.service, f.client, 1, b"fabricated"), Err(Error::Sequence) ); f.run(f.client); f.send(f.client, f.service, 1, b"request").unwrap(); f.run(f.service); assert_eq!( f.send(f.service, f.client, 1, b"premature"), Err(Error::Sequence) ); let mut bytes = [0; MAX_PAYLOAD]; f.receive(f.service, &mut bytes).unwrap(); assert_eq!( f.send(f.service, f.client, 2, b"wrong-sequence"), Err(Error::Sequence) ); f.send(f.service, f.client, 1, b"real-response").unwrap(); assert_eq!( f.send(f.service, f.client, 1, b"duplicate"), Err(Error::Sequence) ); assert_eq!(f.channel.responses.count, 1); assert_eq!(f.channel.snapshot().unwrap().sequence_rejections, 4); } #[test] fn close_refuses_new_requests_but_completes_retained_exchange_before_drain() { let mut f = Fixture::new(); f.run(f.client); f.send(f.client, f.service, 1, b"pending").unwrap(); assert_eq!( f.channel.drain(&mut |id| state(&f.table, id)), Err(Error::NotDrained) ); f.channel .close_client(f.client, &mut |id| state(&f.table, id)) .unwrap(); assert_eq!( f.send(f.client, f.service, 2, b"closing"), Err(Error::Closing) ); assert_eq!( f.channel.drain(&mut |id| state(&f.table, id)), Err(Error::NotDrained) ); f.run(f.service); let mut bytes = [0; MAX_PAYLOAD]; f.receive(f.service, &mut bytes).unwrap(); f.send(f.service, f.client, 1, b"completion").unwrap(); assert_eq!( f.channel.drain(&mut |id| state(&f.table, id)), Err(Error::NotDrained) ); f.run(f.client); f.receive(f.client, &mut bytes).unwrap(); f.channel.drain(&mut |id| state(&f.table, id)).unwrap(); assert_eq!(f.channel.snapshot().unwrap().state, 3); assert_eq!(f.receive(f.client, &mut bytes), Err(Error::Closing)); let s = f.channel.snapshot().unwrap(); assert_eq!(s.drain_rejections, 3); assert_eq!(s.outstanding, 0); assert_eq!(s.closing_rejections, 2); } #[test] fn idempotent_open_preserves_progress_and_cannot_change_boot() { let mut f = Fixture::new(); f.run(f.client); f.send(f.client, f.service, 1, b"persist").unwrap(); let before = f.channel.snapshot().unwrap(); assert_eq!( f.channel .open(99, f.service, f.client, &mut |id| state(&f.table, id)), Ok(()) ); assert_eq!(f.channel.snapshot().unwrap(), before); assert_eq!( f.channel .open(100, f.service, f.client, &mut |id| state(&f.table, id)), Err(Error::Boot) ); assert_eq!(f.channel.snapshot().unwrap(), before); } #[test] fn fifo_wraparound_preserves_monotonic_request_sequence_and_payloads() { let mut f = Fixture::new(); let mut bytes = [0; MAX_PAYLOAD]; for sequence in 1u64..=21 { f.run(f.client); f.send(f.client, f.service, sequence, &sequence.to_le_bytes()) .unwrap(); f.run(f.service); assert_eq!(f.receive(f.service, &mut bytes).unwrap().sequence, sequence); assert_eq!(&bytes[..8], &sequence.to_le_bytes()); let response = (sequence ^ 0x55).to_le_bytes(); f.send(f.service, f.client, sequence, &response).unwrap(); f.run(f.client); assert_eq!(f.receive(f.client, &mut bytes).unwrap().sequence, sequence); assert_eq!(&bytes[..8], &response); } let s = f.channel.snapshot().unwrap(); assert_eq!(s.next_sequence, 22); assert_eq!(s.responses_received, 21); assert_eq!(s.outstanding, 0); } #[test] fn empty_and_sequence_exhaustion_refusals_preserve_live_queue() { let mut f = Fixture::new(); f.run(f.client); let mut bytes = [0; MAX_PAYLOAD]; assert_eq!(f.receive(f.client, &mut bytes), Err(Error::Empty)); assert_eq!( f.send(f.client, f.service, 2, b"skip"), Err(Error::Sequence) ); f.channel.next_sequence = u64::MAX; assert_eq!( f.send(f.client, f.service, u64::MAX, b"wrap"), Err(Error::Sequence) ); let s = f.channel.snapshot().unwrap(); assert_eq!(s.next_sequence, u64::MAX); assert_eq!((s.request_depth, s.outstanding), (0, 0)); assert_eq!((s.empty_rejections, s.sequence_rejections), (1, 2)); } }