//! Worker-owned transaction engine. Main-lane callers exchange owned requests/results. use super::image::*; use prometeu_hal::memcard::MemcardStorage; use std::sync::atomic::{AtomicU8, Ordering}; /// Publication entry and pre-publication cancellation share a single linearization point. #[derive(Default)] pub struct PublicationControl(AtomicU8); impl PublicationControl { pub fn cancel(&self) { self.0.fetch_or(2, Ordering::SeqCst); } pub fn canceled(&self) -> bool { self.0.load(Ordering::SeqCst) & 2 != 0 } pub fn publication_attempted(&self) -> bool { self.0.load(Ordering::SeqCst) & 1 != 0 } // `try_update` requires Rust 1.95; keep older stable CI toolchains compatible. #[allow(deprecated)] fn enter(&self) -> Result<()> { self.0 .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |state| { if state & 2 == 0 { Some(state | 1) } else { None } }) .map(|_| ()) .map_err(|_| Error::Canceled) } fn check(&self) -> Result<()> { if self.canceled() { Err(Error::Canceled) } else { Ok(()) } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DurableResult { Success, Failure, Indeterminate, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CommitResult { pub durable: DurableResult, pub error: Option, pub sequence: u64, } pub struct Card { io: Box, pub maps: [Option; 2], pub active: usize, pub catalog: Catalog, scratch: Box<[u8; SLOT_BYTES]>, pub recovered: bool, pub degraded: bool, pub uncertain: bool, pub(super) attempted_publication: Option, pub write_blocked: bool, known_quarantine: [bool; BLOCK_COUNT], } impl Card { pub fn format(io: &mut dyn MemcardStorage, id: [u8; 16]) -> Result<()> { if io.len()? != IMAGE_BYTES { return Err(Error::InvalidRange); } let identity = identity_page(id); io.write_at(0, &identity)?; io.write_at(PAGE_BYTES as u64, &identity)?; let catalog = Catalog::default().encode(0)?; write_region(io, CATALOG_OFFSETS[0], &catalog)?; let mut map = Map::new(id); map.catalog_len = catalog.len() as u32; map.catalog_crc = crc32c(&catalog); let encoded = map.encode()?; io.write_at(MAP_OFFSETS[0], &encoded)?; io.write_at(MAP_OFFSETS[1], &encoded)?; io.sync()?; Ok(()) } pub fn mount(mut io: Box) -> Result { if io.len()? != IMAGE_BYTES { return Err(Error::Unsupported); } let mut page = [0; PAGE_BYTES]; let mut identities = [None; 2]; let mut recognized = false; for (i, item) in identities.iter_mut().enumerate() { io.read_at((i * PAGE_BYTES) as u64, &mut page)?; recognized |= &page[..8] == b"PMCARD1\0" && u32::from_le_bytes(page[8..12].try_into().unwrap()) == 1; *item = decode_identity(&page).ok(); } let id = identities[0].or(identities[1]).ok_or(if recognized { Error::Corrupt } else { Error::Unsupported })?; if identities.iter().flatten().any(|other| *other != id) { return Err(Error::Corrupt); } let mut maps: [Option; 2] = [None, None]; let mut unknown_metadata = false; for i in 0..2 { io.read_at(MAP_OFFSETS[i], &mut page)?; maps[i] = Map::decode(&page, id).ok(); // A zero page is a verified retirement. An undecodable nonzero page // may have lost quarantine information; do not silently reuse its pool. unknown_metadata |= maps[i].is_none() && page.iter().any(|&byte| byte != 0); } if let (Some(a), Some(b)) = (&maps[0], &maps[1]) && a.sequence == b.sequence && a != b { return Err(Error::Corrupt); } let highest = maps.iter().flatten().map(|m| m.sequence).max().unwrap_or(0); let mut known = [false; BLOCK_COUNT]; for m in maps.iter().flatten() { for (i, &bad) in m.quarantine.iter().enumerate() { known[i] |= bad; } } let mut scratch = Box::new([0; SLOT_BYTES]); let mut catalogs: [Option; 2] = [None, None]; let mut lost_map = false; for i in 0..2 { if let Some(m) = &maps[i] { match Self::validate_map(io.as_mut(), m, scratch.as_mut()) { Ok(c) => catalogs[i] = Some(c), Err(Error::Corrupt) => { maps[i] = None; lost_map = true } Err(e) => return Err(e), } } } let active = match (&maps[0], &maps[1]) { (Some(a), Some(b)) => usize::from(b.sequence > a.sequence), (Some(_), None) => 0, (None, Some(_)) => 1, _ => return Err(Error::Corrupt), }; let m = maps[active].as_ref().unwrap(); let recovered = m.sequence < highest || lost_map || unknown_metadata; let write_blocked = unknown_metadata || known.iter().zip(m.quarantine.iter()).any(|(&a, &b)| a && !b); let degraded = identities.iter().any(Option::is_none) || maps.iter().any(Option::is_none) || known.iter().any(|v| *v); Ok(Self { io, maps, active, catalog: catalogs[active].take().unwrap(), scratch, recovered, degraded, uncertain: false, attempted_publication: None, write_blocked, known_quarantine: known, }) } fn validate_map( io: &mut dyn MemcardStorage, m: &Map, scratch: &mut [u8; SLOT_BYTES], ) -> Result { let mut raw = vec![0; m.catalog_len as usize]; read_region(io, CATALOG_OFFSETS[m.public_copy], &mut raw)?; if crc32c(&raw) != m.catalog_crc { return Err(Error::Corrupt); } let catalog = Catalog::decode(&raw, m.icons_len as usize)?; let assigned = catalog.validate(m.icons_len as usize)?; for (s, &expected) in m.slots.iter().zip(&assigned) { if s.assigned != expected { return Err(Error::Corrupt); } if let Some(id) = s.block { io.read_at(block_offset(id)?, &mut scratch[..s.used as usize])?; if crc32c(&scratch[..s.used as usize]) != s.crc { return Err(Error::Corrupt); } } } let mut crc = !0; let mut at = 0usize; while at < m.icons_len as usize { let n = (m.icons_len as usize - at).min(SLOT_BYTES); io.read_at(ICON_OFFSETS[m.public_copy] + at as u64, &mut scratch[..n])?; crc = crc_extend(crc, &scratch[..n]); at += n; } if crc ^ !0 != m.icons_crc { return Err(Error::Corrupt); } for game in &catalog.games { let n = game.icon.length()?; io.read_at(ICON_OFFSETS[m.public_copy] + game.icon.offset as u64, &mut scratch[..n])?; if crc32c(&scratch[..n]) != game.icon.crc32c { return Err(Error::Corrupt); } } Ok(catalog) } pub fn current(&self) -> &Map { self.maps[self.active].as_ref().unwrap() } pub(super) fn known_exclusions(&self) -> [bool; BLOCK_COUNT] { self.known_quarantine } pub(super) fn remember_exclusions(&mut self, known: [bool; BLOCK_COUNT]) { for (i, bad) in known.into_iter().enumerate() { self.known_quarantine[i] |= bad; self.write_blocked |= bad && !self.current().quarantine[i]; } self.degraded |= self.known_quarantine.iter().any(|&bad| bad); } pub fn storage_read_only(&self) -> bool { self.io.read_only() } pub fn into_storage(self) -> Box { self.io } pub fn read_slot(&mut self, slot: usize, target: &mut [u8]) -> Result { let s = *self.current().slots.get(slot).ok_or(Error::InvalidRange)?; if !s.assigned || target.len() < s.used as usize { return Err(Error::InvalidRange); } if let Some(id) = s.block { self.io.read_at(block_offset(id)?, &mut target[..s.used as usize])?; if crc32c(&target[..s.used as usize]) != s.crc { return Err(Error::Corrupt); } } Ok(s.used as usize) } fn writable(&self) -> Result<()> { if self.uncertain { return Err(Error::Indeterminate); } if self.write_blocked || self.io.read_only() { return Err(Error::ReadOnly); } if self.current().sequence == u64::MAX { return Err(Error::CounterExhausted); } Ok(()) } fn retire_inactive(&mut self, control: &PublicationControl) -> Result<()> { control.check()?; let inactive = 1 - self.active; // Also invalidate torn/unknown pages before a previously referenced region is reused. self.io.write_at(MAP_OFFSETS[inactive], &[0; PAGE_BYTES])?; self.io.sync()?; self.io.read_at(MAP_OFFSETS[inactive], &mut self.scratch[..PAGE_BYTES])?; if self.scratch[..PAGE_BYTES].iter().any(|&v| v != 0) { self.write_blocked = true; return Err(Error::Corrupt); } self.maps[inactive] = None; control.check() } fn publish(&mut self, next: Map, control: &PublicationControl) -> Result<()> { let b = next.encode()?; control.enter()?; self.uncertain = true; self.attempted_publication = Some(next.clone()); let inactive = 1 - self.active; self.io.write_at(MAP_OFFSETS[inactive], &b)?; self.io.sync()?; self.io.read_at(MAP_OFFSETS[inactive], &mut self.scratch[..PAGE_BYTES])?; if self.scratch[..PAGE_BYTES] != b { return Err(Error::Corrupt); } self.maps[inactive] = Some(next); self.active = inactive; self.uncertain = false; Ok(()) } pub fn commit( &mut self, slot: usize, payload: &[u8], timestamp: u64, control: &PublicationControl, ) -> CommitResult { let outcome = self.commit_inner(slot, payload, timestamp, control); CommitResult { durable: if outcome.is_ok() { DurableResult::Success } else if self.uncertain { DurableResult::Indeterminate } else { DurableResult::Failure }, error: outcome.err(), sequence: self.current().sequence, } } fn commit_inner( &mut self, slot: usize, payload: &[u8], timestamp: u64, control: &PublicationControl, ) -> Result<()> { self.writable()?; self.attempted_publication = None; control.check()?; let old = *self.current().slots.get(slot).filter(|s| s.assigned).ok_or(Error::InvalidRange)?; if payload.len() > SLOT_BYTES { return Err(Error::InvalidRange); } let generation = old.generation.checked_add(1).ok_or(Error::CounterExhausted)?; self.retire_inactive(control)?; let mut next = self.current().clone(); next.sequence += 1; let block = if payload.is_empty() { None } else { let mut protected = self.known_quarantine; for m in self.maps.iter().flatten() { for s in &m.slots { if let Some(b) = s.block { protected[b as usize] = true; } } } let id = *next.order.iter().find(|&&id| !protected[id as usize]).ok_or(Error::NoSpace)?; control.check()?; self.io.write_at(block_offset(id)?, payload)?; self.io.sync()?; control.check()?; self.io.read_at(block_offset(id)?, &mut self.scratch[..payload.len()])?; if self.scratch[..payload.len()] != *payload { return Err(Error::Corrupt); } Some(id) }; if let Some(id) = block { move_last(&mut next.order, id) } if let Some(id) = old.block { move_last(&mut next.order, id) } next.slots[slot] = Slot { assigned: true, block, used: payload.len() as u32, generation, update_at: timestamp, crc: crc32c(payload), }; self.publish(next, control) } /// Runtime-authorized catalog mutation; userland cannot provide global ownership. /// Existing icon data streams between copies through the single scratch buffer. pub fn publish_catalog( &mut self, mut catalog: Catalog, slots: [Slot; SLOT_COUNT], new_icon: Option<(u32, &[u8])>, control: &PublicationControl, ) -> Result<()> { self.writable()?; self.attempted_publication = None; control.check()?; let mut next = self.current().clone(); next.sequence += 1; next.public_copy = 1 - next.public_copy; next.slots = slots; let mut offset = 0usize; for game in &mut catalog.games { let len = game.icon.length()?; game.icon.offset = offset as u32; offset = offset.checked_add(len).ok_or(Error::NoSpace)?; } catalog.validate(offset)?; let raw = catalog.encode(offset)?; let assigned = catalog.validate(offset)?; if slots.iter().zip(assigned).any(|(s, a)| s.assigned != a) { return Err(Error::Corrupt); } next.catalog_len = raw.len() as u32; next.catalog_crc = crc32c(&raw); next.icons_len = offset as u32; // Reject invalid descriptors before any administrative IO. next.encode()?; self.retire_inactive(control)?; let mut crc = !0; for game in &catalog.games { control.check()?; let len = game.icon.length()?; if let Some((id, bytes)) = new_icon.filter(|(id, _)| *id == game.app_id) { let _ = id; if bytes.len() != len || crc32c(bytes) != game.icon.crc32c { return Err(Error::Corrupt); } self.scratch[..len].copy_from_slice(bytes); } else { let old = self .catalog .games .iter() .find(|g| g.app_id == game.app_id) .ok_or(Error::InvalidRange)?; if old.icon.length()? != len || old.icon.crc32c != game.icon.crc32c { return Err(Error::Corrupt); } self.io.read_at( ICON_OFFSETS[self.current().public_copy] + old.icon.offset as u64, &mut self.scratch[..len], )?; if crc32c(&self.scratch[..len]) != old.icon.crc32c { return Err(Error::Corrupt); } } crc = crc_extend(crc, &self.scratch[..len]); self.io.write_at( ICON_OFFSETS[next.public_copy] + game.icon.offset as u64, &self.scratch[..len], )?; } next.icons_crc = crc ^ !0; write_region(self.io.as_mut(), CATALOG_OFFSETS[next.public_copy], &raw)?; self.io.sync()?; Self::validate_map(self.io.as_mut(), &next, self.scratch.as_mut())?; self.publish(next, control)?; self.catalog = catalog; Ok(()) } pub fn register( &mut self, mut game: Game, icon: &[u8], control: &PublicationControl, ) -> Result<()> { if self.catalog.games.iter().any(|g| g.app_id == game.app_id) { return Err(Error::InvalidRange); } let n = game.slots.len(); if !(1..=64).contains(&n) { return Err(Error::InvalidRange); } let mut slots = self.current().slots; let free: Vec = slots .iter() .enumerate() .filter(|(_, s)| !s.assigned) .map(|(i, _)| i as u8) .take(n) .collect(); if free.len() != n { return Err(Error::NoSpace); } game.slots = free; for &id in &game.slots { slots[id as usize] = Slot { assigned: true, ..Slot::default() }; } let app_id = game.app_id; let mut c = self.catalog.clone(); c.games.push(game); self.publish_catalog(c, slots, Some((app_id, icon)), control) } pub fn remove_game(&mut self, app_id: u32, control: &PublicationControl) -> Result<()> { let game = self.catalog.games.iter().find(|g| g.app_id == app_id).ok_or(Error::InvalidRange)?; let mut slots = self.current().slots; for &id in &game.slots { slots[id as usize] = Slot::default(); } let mut c = self.catalog.clone(); c.games.retain(|g| g.app_id != app_id); self.publish_catalog(c, slots, None, control) } pub fn grow(&mut self, app_id: u32, count: usize, control: &PublicationControl) -> Result<()> { if !(1..=64).contains(&count) { return Err(Error::InvalidRange); } let mut c = self.catalog.clone(); let g = c.games.iter_mut().find(|g| g.app_id == app_id).ok_or(Error::InvalidRange)?; if count <= g.slots.len() { return Ok(()); } let need = count - g.slots.len(); let mut slots = self.current().slots; let free: Vec = slots .iter() .enumerate() .filter(|(_, s)| !s.assigned) .map(|(i, _)| i as u8) .take(need) .collect(); if free.len() != need { return Err(Error::NoSpace); } for &id in &free { slots[id as usize] = Slot { assigned: true, ..Slot::default() }; } g.slots.extend(free); self.publish_catalog(c, slots, None, control) } /// Explicit host maintenance after coherent mount. Unknown exclusion history /// can only be cleared after every reusable, non-quarantined block is tested. pub fn revalidate(&mut self, control: &PublicationControl) -> Result<()> { if self.uncertain { return Err(Error::Indeterminate); } if self.io.read_only() { return Err(Error::ReadOnly); } if self.current().sequence == u64::MAX { return Err(Error::CounterExhausted); } self.write_blocked = true; self.retire_inactive(control)?; for block in 0..BLOCK_COUNT { if !self.known_quarantine[block] && !self.current().slots.iter().any(|s| s.block == Some(block as u8)) { self.test_free_block(block as u8, control)?; } } let mut next = self.current().clone(); next.sequence += 1; next.quarantine = self.known_quarantine; self.publish(next, control)?; self.write_blocked = false; self.degraded = self.known_quarantine.iter().any(|&bad| bad); Ok(()) } fn test_free_block(&mut self, block: u8, control: &PublicationControl) -> Result<()> { for pattern in [0x55, 0xaa] { control.check()?; self.scratch.fill(pattern); self.io.write_at(block_offset(block)?, self.scratch.as_ref())?; self.io.sync()?; control.check()?; self.io.read_at(block_offset(block)?, self.scratch.as_mut())?; if self.scratch.iter().any(|&byte| byte != pattern) { return Err(Error::Corrupt); } } Ok(()) } /// Reintegrating a known excluded block is a separate, explicit operation. pub fn reintegrate(&mut self, block: u8, control: &PublicationControl) -> Result<()> { self.writable()?; if block as usize >= BLOCK_COUNT || self.current().slots.iter().any(|s| s.block == Some(block)) { return Err(Error::InvalidRange); } self.retire_inactive(control)?; self.test_free_block(block, control)?; let mut next = self.current().clone(); next.sequence += 1; next.quarantine[block as usize] = false; self.publish(next, control)?; self.known_quarantine[block as usize] = false; self.degraded = self.known_quarantine.iter().any(|&bad| bad); Ok(()) } pub fn read_icon(&mut self, app_id: u32) -> Result> { let icon = &self .catalog .games .iter() .find(|g| g.app_id == app_id) .ok_or(Error::InvalidRange)? .icon; let mut bytes = vec![0; icon.length()?]; self.io .read_at(ICON_OFFSETS[self.current().public_copy] + icon.offset as u64, &mut bytes)?; if crc32c(&bytes) != icon.crc32c { return Err(Error::Corrupt); } Ok(bytes) } pub fn quarantine(&mut self, block: u8, control: &PublicationControl) -> Result<()> { if block as usize >= BLOCK_COUNT { return Err(Error::InvalidRange); } self.known_quarantine[block as usize] = true; self.degraded = true; let result = (|| { self.writable()?; if self.current().slots.iter().any(|s| s.block == Some(block)) { return Err(Error::Corrupt); } self.retire_inactive(control)?; let mut next = self.current().clone(); next.sequence += 1; next.quarantine = self.known_quarantine; self.publish(next, control) })(); if result.is_err() { self.write_blocked = true; } result } } fn move_last(order: &mut [u8; BLOCK_COUNT], id: u8) { let pos = order.iter().position(|&b| b == id).unwrap(); order[pos..].rotate_left(1); } #[cfg(test)] mod tests;