1010 lines
36 KiB
Rust
1010 lines
36 KiB
Rust
//! Per-game snapshots and one retained asynchronous request. No guest heap escapes a call.
|
|
use super::image::*;
|
|
use super::transaction::{Card, CommitResult, DurableResult, PublicationControl};
|
|
use crate::services::async_work::{AsyncWorkJobId, AsyncWorkLane};
|
|
use std::sync::{Arc, Mutex, RwLock, mpsc};
|
|
use std::time::{Duration, Instant};
|
|
|
|
pub const GUEST_BYTES: usize = 4096;
|
|
static NEXT_CONTEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
|
|
fn next_context() -> Result<u64> {
|
|
NEXT_CONTEXT
|
|
.fetch_update(
|
|
std::sync::atomic::Ordering::SeqCst,
|
|
std::sync::atomic::Ordering::SeqCst,
|
|
|n| n.checked_add(1).filter(|&next| next <= i64::MAX as u64),
|
|
)
|
|
.map_err(|_| Error::CounterExhausted)
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Mode {
|
|
Persistent,
|
|
MemoryOnly,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum RequestState {
|
|
Pending,
|
|
Success,
|
|
Failure,
|
|
Indeterminate,
|
|
MemoryOnly,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum RequestReason {
|
|
None,
|
|
Storage(Error),
|
|
Timeout,
|
|
RestartRequired,
|
|
}
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct RequestResult {
|
|
pub id: u64,
|
|
pub state: RequestState,
|
|
pub reason: RequestReason,
|
|
}
|
|
struct Snapshot {
|
|
bytes: Vec<u8>,
|
|
used: usize,
|
|
descriptor: Slot,
|
|
dirty: bool,
|
|
}
|
|
struct LocalSlot {
|
|
data: Arc<RwLock<Snapshot>>,
|
|
protected: bool,
|
|
}
|
|
struct Completion {
|
|
card: Card,
|
|
result: CommitResult,
|
|
}
|
|
struct Request {
|
|
id: u64,
|
|
session: u64,
|
|
epoch: u64,
|
|
local: usize,
|
|
source: Arc<RwLock<Snapshot>>,
|
|
control: Arc<PublicationControl>,
|
|
receiver: mpsc::Receiver<Completion>,
|
|
admitted: Instant,
|
|
result: RequestResult,
|
|
job: AsyncWorkJobId,
|
|
released: bool,
|
|
saves_payload: bool,
|
|
}
|
|
/// Main-lane control; the Card moves into the single worker while its source is protected.
|
|
#[derive(Default)]
|
|
pub struct Session {
|
|
card_id: Option<[u8; 16]>,
|
|
uncertain_target: Option<Map>,
|
|
health: (bool, bool, bool),
|
|
context: u64,
|
|
epoch: u64,
|
|
app_id: u32,
|
|
next_request: u64,
|
|
mode: Option<Mode>,
|
|
slots: Vec<LocalSlot>,
|
|
logical: Vec<u8>,
|
|
card: Option<Card>,
|
|
request: Option<Request>,
|
|
memory_result: Option<RequestResult>,
|
|
scratch: Option<Vec<u8>>,
|
|
faulted: bool,
|
|
reconcile_blocked: bool,
|
|
removal_pending: bool,
|
|
presentation: Option<Game>,
|
|
icon: Vec<u8>,
|
|
provisional: bool,
|
|
boot_active: bool,
|
|
boot_error: Option<Error>,
|
|
deferred: Option<(u64, usize, u64, Instant)>,
|
|
}
|
|
impl Session {
|
|
pub fn context(&self) -> u64 {
|
|
self.context
|
|
}
|
|
pub fn health(&self) -> (bool, bool, bool) {
|
|
let (recovered, degraded, blocked) = self.card.as_ref().map_or(self.health, |c| {
|
|
(c.recovered, c.degraded, c.write_blocked || c.storage_read_only() || c.uncertain)
|
|
});
|
|
(recovered, degraded, blocked || self.faulted || self.reconcile_blocked)
|
|
}
|
|
pub fn mode(&self) -> Option<Mode> {
|
|
self.mode
|
|
}
|
|
pub fn count(&self) -> usize {
|
|
self.slots.len()
|
|
}
|
|
pub fn notify_removal(&mut self) {
|
|
self.removal_pending = true;
|
|
self.reconcile_blocked = true;
|
|
if let Some(request) = &self.request {
|
|
request.control.cancel();
|
|
}
|
|
}
|
|
pub fn removal_pending(&self) -> bool {
|
|
self.removal_pending
|
|
}
|
|
pub fn host_faulted(&self) -> bool {
|
|
self.faulted
|
|
}
|
|
pub fn required_bytes(count: usize) -> Result<usize> {
|
|
if !(1..=64).contains(&count) {
|
|
return Err(Error::InvalidRange);
|
|
}
|
|
count
|
|
.checked_add(1)
|
|
.and_then(|n| n.checked_mul(SLOT_BYTES))
|
|
.and_then(|n| n.checked_add(512 * 1024))
|
|
.ok_or(Error::OutOfMemory)
|
|
}
|
|
fn allocate(
|
|
count: usize,
|
|
budget: usize,
|
|
reserve_scratch: bool,
|
|
) -> Result<(Vec<LocalSlot>, Vec<u8>)> {
|
|
if Self::required_bytes(count)? > budget {
|
|
return Err(Error::OutOfMemory);
|
|
}
|
|
let mut slots = Vec::new();
|
|
slots.try_reserve_exact(count).map_err(|_| Error::OutOfMemory)?;
|
|
for _ in 0..count {
|
|
let mut bytes = Vec::new();
|
|
bytes.try_reserve_exact(SLOT_BYTES).map_err(|_| Error::OutOfMemory)?;
|
|
bytes.resize(SLOT_BYTES, 0);
|
|
slots.push(LocalSlot {
|
|
data: Arc::new(RwLock::new(Snapshot {
|
|
bytes,
|
|
used: 0,
|
|
descriptor: Slot { assigned: true, ..Slot::default() },
|
|
dirty: false,
|
|
})),
|
|
protected: false,
|
|
});
|
|
}
|
|
let mut scratch = Vec::new();
|
|
if reserve_scratch {
|
|
scratch.try_reserve_exact(SLOT_BYTES).map_err(|_| Error::OutOfMemory)?;
|
|
scratch.resize(SLOT_BYTES, 0);
|
|
}
|
|
Ok((slots, scratch))
|
|
}
|
|
pub fn start_memory(&mut self, app_id: u32, count: usize, budget: usize) -> Result<u64> {
|
|
self.start_memory_with_card(app_id, count, budget, None)
|
|
}
|
|
pub fn start_memory_with_card(
|
|
&mut self,
|
|
app_id: u32,
|
|
count: usize,
|
|
budget: usize,
|
|
card: Option<Card>,
|
|
) -> Result<u64> {
|
|
if self.request.is_some() || self.deferred.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
self.card = card;
|
|
let (slots, scratch) = Self::allocate(count, budget, self.card.is_none())?;
|
|
self.context = next_context()?;
|
|
self.app_id = app_id;
|
|
self.presentation = None;
|
|
self.icon.clear();
|
|
self.provisional = true;
|
|
self.boot_active = false;
|
|
self.mode = Some(Mode::MemoryOnly);
|
|
self.slots = slots;
|
|
self.logical = (0..count as u8).collect();
|
|
self.scratch = if self.card.is_none() { Some(scratch) } else { None };
|
|
self.boot_error = None;
|
|
self.memory_result = None;
|
|
self.faulted = false;
|
|
self.reconcile_blocked = false;
|
|
self.removal_pending = false;
|
|
Ok(self.context)
|
|
}
|
|
/// Call during worker-side admission, before the guest starts. Existing records only;
|
|
/// provisional registration is coordinated by the bootstrap admission owner.
|
|
pub fn load_card(
|
|
&mut self,
|
|
card: Card,
|
|
app_id: u32,
|
|
count: usize,
|
|
budget: usize,
|
|
) -> Result<u64> {
|
|
self.load_card_mode(card, app_id, count, budget, false)
|
|
}
|
|
pub(super) fn load_card_memory(
|
|
&mut self,
|
|
card: Card,
|
|
app_id: u32,
|
|
count: usize,
|
|
budget: usize,
|
|
) -> Result<u64> {
|
|
self.load_card_mode(card, app_id, count, budget, true)
|
|
}
|
|
fn load_card_mode(
|
|
&mut self,
|
|
card: Card,
|
|
app_id: u32,
|
|
count: usize,
|
|
budget: usize,
|
|
memory_only: bool,
|
|
) -> Result<u64> {
|
|
if self.request.is_some() || self.deferred.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
self.health = (
|
|
card.recovered,
|
|
card.degraded,
|
|
card.write_blocked || card.storage_read_only() || card.uncertain,
|
|
);
|
|
self.card_id = Some(card.current().card_id);
|
|
self.card = Some(card);
|
|
let card = self.card.as_mut().unwrap();
|
|
let game =
|
|
card.catalog.games.iter().find(|g| g.app_id == app_id).ok_or(Error::InvalidState)?;
|
|
if !memory_only && count > game.slots.len() {
|
|
return Err(Error::NoSpace);
|
|
}
|
|
let mut logical = game.slots[..count.min(game.slots.len())].to_vec();
|
|
let presentation = game.clone();
|
|
let (slots, _scratch) = Self::allocate(count, budget, false)?;
|
|
for (local, &id) in slots.iter().zip(&logical) {
|
|
let mut snapshot = local.data.write().map_err(|_| Error::InvalidState)?;
|
|
snapshot.used = card.read_slot(id as usize, &mut snapshot.bytes)?;
|
|
snapshot.descriptor = card.current().slots[id as usize];
|
|
}
|
|
logical.resize(count, 255); // RAM-only extension has no persistent logical assignment.
|
|
self.context = next_context()?;
|
|
self.epoch = self.epoch.checked_add(1).ok_or(Error::CounterExhausted)?;
|
|
self.slots = slots;
|
|
self.logical = logical;
|
|
self.app_id = app_id;
|
|
self.mode = Some(if memory_only { Mode::MemoryOnly } else { Mode::Persistent });
|
|
if memory_only && self.logical.contains(&255) {
|
|
self.card_id = None;
|
|
}
|
|
self.presentation = Some(presentation);
|
|
self.provisional = false;
|
|
self.boot_active = false;
|
|
self.boot_error = None;
|
|
self.icon.clear();
|
|
self.scratch = None;
|
|
self.faulted = false;
|
|
self.reconcile_blocked = false;
|
|
self.removal_pending = false;
|
|
self.memory_result = None;
|
|
Ok(self.context)
|
|
}
|
|
pub fn app_id(&self) -> Option<u32> {
|
|
self.mode.map(|_| self.app_id)
|
|
}
|
|
pub fn is_new(&self) -> bool {
|
|
self.provisional
|
|
}
|
|
pub fn is_boot_active(&self) -> bool {
|
|
self.boot_active
|
|
}
|
|
pub fn publish_presentation(
|
|
&mut self,
|
|
context: u64,
|
|
lane: &AsyncWorkLane,
|
|
now: Instant,
|
|
) -> Result<u64> {
|
|
self.slot(context, 0)?;
|
|
if self.boot_active || self.provisional || self.mode != Some(Mode::Persistent) {
|
|
return Err(Error::InvalidState);
|
|
}
|
|
self.boot_active = true;
|
|
self.finish_boot(true, lane, now)?;
|
|
let r = self.request.as_mut().ok_or(Error::InvalidState)?;
|
|
r.released = false;
|
|
Ok(r.id)
|
|
}
|
|
pub fn begin_boot(&mut self) {
|
|
self.boot_active = true;
|
|
}
|
|
pub fn boot_pending(&self) -> bool {
|
|
self.boot_active
|
|
|| (self.provisional && self.request.is_some())
|
|
|| self.request.as_ref().is_some_and(|r| r.released)
|
|
}
|
|
pub fn boot_error(&self) -> Option<Error> {
|
|
self.boot_error
|
|
}
|
|
pub fn presentation(&self, context: u64) -> Result<Option<&Game>> {
|
|
self.slot(context, 0)?;
|
|
Ok(self.presentation.as_ref())
|
|
}
|
|
pub fn prepare_new_card(
|
|
&mut self,
|
|
card: Card,
|
|
app_id: u32,
|
|
count: usize,
|
|
created_at: u64,
|
|
budget: usize,
|
|
) -> Result<u64> {
|
|
if self.request.is_some() || self.deferred.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
if card.catalog.games.iter().any(|g| g.app_id == app_id) {
|
|
return self.load_card(card, app_id, count, budget);
|
|
}
|
|
self.health = (
|
|
card.recovered,
|
|
card.degraded,
|
|
card.write_blocked || card.storage_read_only() || card.uncertain,
|
|
);
|
|
self.card_id = Some(card.current().card_id);
|
|
self.card = Some(card);
|
|
let card = self.card.as_ref().unwrap();
|
|
let logical: Vec<u8> = card
|
|
.current()
|
|
.slots
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, s)| !s.assigned)
|
|
.map(|(i, _)| i as u8)
|
|
.take(count)
|
|
.collect();
|
|
if logical.len() != count {
|
|
return Err(Error::NoSpace);
|
|
}
|
|
let (slots, _) = Self::allocate(count, budget, false)?;
|
|
self.context = next_context()?;
|
|
self.epoch = self.epoch.checked_add(1).ok_or(Error::CounterExhausted)?;
|
|
self.presentation = Some(Game {
|
|
app_id,
|
|
title: String::new(),
|
|
data_format_version: 0,
|
|
created_at,
|
|
slots: logical.clone(),
|
|
icon: Icon { offset: 0, frames: 1, duration: 1, crc32c: 0 },
|
|
});
|
|
self.app_id = app_id;
|
|
self.logical = logical;
|
|
self.slots = slots;
|
|
self.mode = Some(Mode::Persistent);
|
|
self.scratch = None;
|
|
self.provisional = true;
|
|
self.boot_active = true;
|
|
self.memory_result = None;
|
|
self.icon.clear();
|
|
self.faulted = false;
|
|
self.boot_error = None;
|
|
Ok(self.context)
|
|
}
|
|
#[allow(clippy::too_many_arguments)] // Mirrors the bounded presentation ABI.
|
|
pub fn set_presentation(
|
|
&mut self,
|
|
context: u64,
|
|
title: &str,
|
|
version: u32,
|
|
frames: u8,
|
|
duration: u16,
|
|
bytes: &[u8],
|
|
created_at: u64,
|
|
) -> Result<()> {
|
|
self.slot(context, 0)?;
|
|
if self.request.is_some() || self.deferred.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
if title.trim().is_empty() || title.len() > 128 {
|
|
return Err(Error::InvalidRange);
|
|
}
|
|
let icon = Icon { offset: 0, frames, duration, crc32c: crc32c(bytes) };
|
|
if icon.length()? != bytes.len() {
|
|
return Err(Error::InvalidRange);
|
|
}
|
|
let old = self.presentation.as_ref();
|
|
self.presentation = Some(Game {
|
|
app_id: self.app_id,
|
|
title: title.into(),
|
|
data_format_version: version,
|
|
created_at: old.map_or(created_at, |g| g.created_at),
|
|
slots: old.map_or_else(|| self.logical.clone(), |g| g.slots.clone()),
|
|
icon,
|
|
});
|
|
self.icon.clear();
|
|
self.icon.extend_from_slice(bytes);
|
|
Ok(())
|
|
}
|
|
/// Completes the producer boundary. First-registration commits use one
|
|
/// composite worker request, so no guest wait can deadlock catalog publication.
|
|
pub fn finish_boot(&mut self, ready: bool, lane: &AsyncWorkLane, now: Instant) -> Result<()> {
|
|
if !self.boot_active {
|
|
return Err(Error::InvalidState);
|
|
}
|
|
self.boot_active = false;
|
|
if !ready {
|
|
if let Some((id, local, ..)) = self.deferred.take() {
|
|
self.slots[local].protected = false;
|
|
self.memory_result = Some(RequestResult {
|
|
id,
|
|
state: RequestState::Failure,
|
|
reason: RequestReason::Storage(Error::InvalidState),
|
|
});
|
|
}
|
|
return Err(Error::InvalidState);
|
|
}
|
|
if self.mode == Some(Mode::MemoryOnly) {
|
|
if self.presentation.is_none() {
|
|
return Err(Error::InvalidState);
|
|
}
|
|
return Ok(());
|
|
}
|
|
if !self.provisional && self.icon.is_empty() && self.deferred.is_none() {
|
|
return Ok(());
|
|
}
|
|
if self.request.is_some() || self.memory_result.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
let game = self.presentation.clone().ok_or(Error::InvalidState)?;
|
|
if game.title.trim().is_empty() || (self.provisional && self.icon.is_empty()) {
|
|
return Err(Error::InvalidState);
|
|
}
|
|
let deferred = self.deferred.take();
|
|
let saves_payload = deferred.is_some();
|
|
let (id, local, timestamp, admitted) = if let Some(request) = deferred {
|
|
request
|
|
} else {
|
|
self.next_request = self
|
|
.next_request
|
|
.checked_add(1)
|
|
.filter(|&n| n <= i64::MAX as u64)
|
|
.ok_or(Error::CounterExhausted)?;
|
|
(self.next_request, 0, 0, now)
|
|
};
|
|
let card = self.card.take().ok_or(Error::InvalidState)?;
|
|
let handoff = Arc::new(Mutex::new(Some(card)));
|
|
let worker_handoff = handoff.clone();
|
|
let source = self.slots[local].data.clone();
|
|
let worker_source = source.clone();
|
|
let control = Arc::new(PublicationControl::default());
|
|
let worker_control = control.clone();
|
|
let (sender, receiver) = mpsc::channel();
|
|
let icon = self.icon.clone();
|
|
let provisional = self.provisional;
|
|
let logical = self.logical[local] as usize;
|
|
let job = lane.submit_memcard_commit_write(move |_| {
|
|
let mut card = worker_handoff.lock().unwrap().take().unwrap();
|
|
let registration = if provisional {
|
|
card.register(game, &icon, &worker_control)
|
|
} else if icon.is_empty() {
|
|
Ok(())
|
|
} else {
|
|
let mut catalog = card.catalog.clone();
|
|
let id = game.app_id;
|
|
if let Some(entry) = catalog.games.iter_mut().find(|g| g.app_id == id) {
|
|
*entry = game;
|
|
}
|
|
card.publish_catalog(
|
|
catalog,
|
|
card.current().slots,
|
|
Some((id, &icon)),
|
|
&worker_control,
|
|
)
|
|
};
|
|
let result = match registration {
|
|
Ok(()) if saves_payload => {
|
|
let s = worker_source.read().unwrap();
|
|
card.commit(logical, &s.bytes[..s.used], timestamp, &worker_control)
|
|
}
|
|
Ok(()) => CommitResult {
|
|
durable: DurableResult::Success,
|
|
error: None,
|
|
sequence: card.current().sequence,
|
|
},
|
|
Err(error) => CommitResult {
|
|
durable: if card.uncertain {
|
|
DurableResult::Indeterminate
|
|
} else {
|
|
DurableResult::Failure
|
|
},
|
|
error: Some(error),
|
|
sequence: card.current().sequence,
|
|
},
|
|
};
|
|
let _ = sender.send(Completion { card, result });
|
|
crate::services::async_work::AsyncWorkJobOutcome::Completed
|
|
});
|
|
let job = match job {
|
|
Ok(job) => job,
|
|
Err(_) => {
|
|
self.card = handoff.lock().unwrap().take();
|
|
self.slots[local].protected = false;
|
|
return Err(Error::InvalidState);
|
|
}
|
|
};
|
|
self.slots[local].protected = true;
|
|
self.request = Some(Request {
|
|
id,
|
|
session: self.context,
|
|
epoch: self.epoch,
|
|
local,
|
|
source,
|
|
control,
|
|
receiver,
|
|
admitted,
|
|
result: RequestResult { id, state: RequestState::Pending, reason: RequestReason::None },
|
|
job,
|
|
released: !saves_payload,
|
|
saves_payload,
|
|
});
|
|
Ok(())
|
|
}
|
|
fn slot(&self, context: u64, local: usize) -> Result<&LocalSlot> {
|
|
if context != self.context || self.mode.is_none() {
|
|
return Err(Error::AccessDenied);
|
|
}
|
|
self.slots.get(local).ok_or(Error::InvalidRange)
|
|
}
|
|
pub fn read(&self, context: u64, local: usize, offset: usize, out: &mut [u8]) -> Result<usize> {
|
|
if out.len() > GUEST_BYTES
|
|
|| offset > SLOT_BYTES
|
|
|| offset.checked_add(out.len()).is_none_or(|v| v > SLOT_BYTES)
|
|
{
|
|
return Err(Error::InvalidRange);
|
|
}
|
|
let s = self.slot(context, local)?.data.read().map_err(|_| Error::InvalidState)?;
|
|
let n = out.len().min(s.used.saturating_sub(offset));
|
|
out[..n].copy_from_slice(&s.bytes[offset..offset + n]);
|
|
Ok(n)
|
|
}
|
|
pub fn write(&mut self, context: u64, local: usize, offset: usize, bytes: &[u8]) -> Result<()> {
|
|
let end = offset.checked_add(bytes.len()).ok_or(Error::InvalidRange)?;
|
|
if bytes.len() > GUEST_BYTES || end > SLOT_BYTES {
|
|
return Err(Error::InvalidRange);
|
|
}
|
|
let slot = self.slot(context, local)?;
|
|
if slot.protected {
|
|
return Err(Error::Busy);
|
|
}
|
|
let mut s = slot.data.try_write().map_err(|_| Error::Busy)?;
|
|
if offset > s.used {
|
|
let used = s.used;
|
|
s.bytes[used..offset].fill(0);
|
|
}
|
|
s.bytes[offset..end].copy_from_slice(bytes);
|
|
s.used = s.used.max(end);
|
|
s.dirty = true;
|
|
Ok(())
|
|
}
|
|
pub fn clear(&mut self, context: u64, local: usize) -> Result<()> {
|
|
let slot = self.slot(context, local)?;
|
|
if slot.protected {
|
|
return Err(Error::Busy);
|
|
}
|
|
let mut s = slot.data.try_write().map_err(|_| Error::Busy)?;
|
|
s.bytes.fill(0);
|
|
s.used = 0;
|
|
s.dirty = true;
|
|
Ok(())
|
|
}
|
|
pub fn descriptor(&self, context: u64, local: usize) -> Result<(Slot, usize, bool)> {
|
|
let s = self.slot(context, local)?.data.read().map_err(|_| Error::InvalidState)?;
|
|
Ok((s.descriptor, s.used, s.dirty))
|
|
}
|
|
pub fn unsaved(&self) -> bool {
|
|
self.slots.iter().any(|s| s.data.read().is_ok_and(|s| s.dirty))
|
|
}
|
|
pub fn commit(
|
|
&mut self,
|
|
context: u64,
|
|
local: usize,
|
|
timestamp: u64,
|
|
now: Instant,
|
|
lane: &AsyncWorkLane,
|
|
) -> Result<u64> {
|
|
self.slot(context, local)?;
|
|
if self.request.is_some() || self.memory_result.is_some() || self.deferred.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
if self.faulted || self.reconcile_blocked {
|
|
return Err(Error::ReadOnly);
|
|
}
|
|
let id = self
|
|
.next_request
|
|
.checked_add(1)
|
|
.filter(|&v| v <= i64::MAX as u64)
|
|
.ok_or(Error::CounterExhausted)?;
|
|
if self.mode == Some(Mode::MemoryOnly) {
|
|
self.next_request = id;
|
|
self.memory_result = Some(RequestResult {
|
|
id,
|
|
state: RequestState::MemoryOnly,
|
|
reason: RequestReason::None,
|
|
});
|
|
return Ok(id);
|
|
}
|
|
if self.boot_active {
|
|
self.next_request = id;
|
|
self.slots[local].protected = true;
|
|
self.deferred = Some((id, local, timestamp, now));
|
|
return Ok(id);
|
|
}
|
|
let card = self.card.take().ok_or(Error::InvalidState)?;
|
|
if card.uncertain || card.write_blocked || card.storage_read_only() {
|
|
self.card = Some(card);
|
|
return Err(Error::ReadOnly);
|
|
}
|
|
let handoff = Arc::new(Mutex::new(Some(card)));
|
|
let worker_handoff = handoff.clone();
|
|
let source = self.slots[local].data.clone();
|
|
let worker_source = source.clone();
|
|
let logical = self.logical[local] as usize;
|
|
let control = Arc::new(PublicationControl::default());
|
|
let worker_control = control.clone();
|
|
let (sender, receiver) = mpsc::channel();
|
|
let job = lane.submit_memcard_commit_write(move |_| {
|
|
let mut card = worker_handoff.lock().unwrap().take().unwrap();
|
|
let result = match worker_source.read() {
|
|
Ok(s) => card.commit(logical, &s.bytes[..s.used], timestamp, &worker_control),
|
|
Err(_) => CommitResult {
|
|
durable: DurableResult::Failure,
|
|
error: Some(Error::InvalidState),
|
|
sequence: card.current().sequence,
|
|
},
|
|
};
|
|
let _ = sender.send(Completion { card, result });
|
|
crate::services::async_work::AsyncWorkJobOutcome::Completed
|
|
});
|
|
let job = match job {
|
|
Ok(job) => job,
|
|
Err(_) => {
|
|
self.card = handoff.lock().unwrap().take();
|
|
return Err(Error::InvalidState);
|
|
}
|
|
};
|
|
self.slots[local].protected = true;
|
|
self.next_request = id;
|
|
self.request = Some(Request {
|
|
id,
|
|
session: self.context,
|
|
epoch: self.epoch,
|
|
local,
|
|
source,
|
|
control,
|
|
receiver,
|
|
admitted: now,
|
|
result: RequestResult { id, state: RequestState::Pending, reason: RequestReason::None },
|
|
job,
|
|
released: false,
|
|
saves_payload: true,
|
|
});
|
|
Ok(id)
|
|
}
|
|
pub fn poll(&mut self, now: Instant) {
|
|
if self.deferred.as_ref().is_some_and(|(_, _, _, admitted)| {
|
|
now.saturating_duration_since(*admitted) >= Duration::from_millis(500)
|
|
}) {
|
|
let (id, local, ..) = self.deferred.take().unwrap();
|
|
self.slots[local].protected = false;
|
|
self.memory_result = Some(RequestResult {
|
|
id,
|
|
state: RequestState::Failure,
|
|
reason: RequestReason::Timeout,
|
|
});
|
|
}
|
|
let Some(r) = &mut self.request else { return };
|
|
match r.receiver.try_recv() {
|
|
Ok(completion) => {
|
|
let current =
|
|
self.mode.is_some() && r.session == self.context && r.epoch == self.epoch;
|
|
if current {
|
|
self.slots[r.local].protected = false;
|
|
if r.result.reason == RequestReason::None {
|
|
r.result.state = match completion.result.durable {
|
|
DurableResult::Success => RequestState::Success,
|
|
DurableResult::Failure => RequestState::Failure,
|
|
DurableResult::Indeterminate => RequestState::Indeterminate,
|
|
};
|
|
r.result.reason = completion
|
|
.result
|
|
.error
|
|
.map_or(RequestReason::None, RequestReason::Storage);
|
|
if completion.result.durable == DurableResult::Success && r.saves_payload {
|
|
let mut s = r.source.write().unwrap();
|
|
s.descriptor =
|
|
completion.card.current().slots[self.logical[r.local] as usize];
|
|
s.dirty = false;
|
|
}
|
|
} // A timeout result is immutable; returned card requires explicit reconciliation.
|
|
if self.provisional && completion.result.durable != DurableResult::Success {
|
|
self.boot_error =
|
|
Some(completion.result.error.unwrap_or(Error::InvalidState));
|
|
}
|
|
if completion.result.durable == DurableResult::Success {
|
|
self.provisional = false;
|
|
self.presentation = completion
|
|
.card
|
|
.catalog
|
|
.games
|
|
.iter()
|
|
.find(|g| g.app_id == self.app_id)
|
|
.cloned();
|
|
}
|
|
}
|
|
if current
|
|
&& (completion.result.durable == DurableResult::Indeterminate
|
|
|| matches!(
|
|
completion.result.error,
|
|
Some(Error::Io(
|
|
prometeu_hal::memcard::MemcardIoError::Unavailable
|
|
| prometeu_hal::memcard::MemcardIoError::ReadOnly
|
|
))
|
|
))
|
|
{
|
|
self.removal_pending = true;
|
|
self.reconcile_blocked = true;
|
|
}
|
|
self.health = (
|
|
completion.card.recovered,
|
|
completion.card.degraded,
|
|
completion.card.write_blocked
|
|
|| completion.card.storage_read_only()
|
|
|| completion.card.uncertain,
|
|
);
|
|
self.card = Some(completion.card);
|
|
if r.released {
|
|
self.request = None;
|
|
}
|
|
return;
|
|
}
|
|
Err(mpsc::TryRecvError::Disconnected) => {}
|
|
Err(mpsc::TryRecvError::Empty) => {}
|
|
}
|
|
if r.result.state != RequestState::Pending {
|
|
return;
|
|
}
|
|
let elapsed = now.saturating_duration_since(r.admitted);
|
|
if elapsed >= Duration::from_millis(500) {
|
|
r.control.cancel();
|
|
}
|
|
if elapsed >= Duration::from_secs(1) {
|
|
r.result.state = if r.control.publication_attempted() {
|
|
RequestState::Indeterminate
|
|
} else {
|
|
RequestState::Failure
|
|
};
|
|
r.result.reason = RequestReason::RestartRequired;
|
|
self.faulted = true;
|
|
}
|
|
}
|
|
pub fn query(&self, context: u64, id: u64) -> Result<RequestResult> {
|
|
if context != self.context || self.mode.is_none() {
|
|
return Err(Error::AccessDenied);
|
|
}
|
|
if self.deferred.as_ref().is_some_and(|(pending, ..)| *pending == id) {
|
|
return Ok(RequestResult {
|
|
id,
|
|
state: RequestState::Pending,
|
|
reason: RequestReason::None,
|
|
});
|
|
}
|
|
if let Some(r) = self.memory_result.filter(|r| r.id == id) {
|
|
return Ok(r);
|
|
}
|
|
self.request
|
|
.as_ref()
|
|
.filter(|r| r.id == id && !r.released)
|
|
.map(|r| r.result)
|
|
.ok_or(Error::InvalidRange)
|
|
}
|
|
pub fn release_request(&mut self, context: u64, id: u64) -> Result<()> {
|
|
self.query(context, id)?;
|
|
if self.deferred.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
if self.memory_result.is_some() {
|
|
self.memory_result = None;
|
|
return Ok(());
|
|
}
|
|
let r = self.request.as_mut().unwrap();
|
|
if r.result.state == RequestState::Pending {
|
|
return Err(Error::Busy);
|
|
}
|
|
r.released = true;
|
|
if self.card.is_some() {
|
|
self.request = None;
|
|
}
|
|
Ok(())
|
|
}
|
|
pub fn has_in_flight(&self) -> bool {
|
|
self.request.is_some() || self.deferred.is_some()
|
|
}
|
|
/// Call only after the external unsaved-data decision. In-flight ownership stays native.
|
|
pub fn end_session(&mut self) {
|
|
if let Some(r) = &mut self.request {
|
|
r.control.cancel();
|
|
r.released = true;
|
|
}
|
|
if self.card.is_some() {
|
|
self.request = None;
|
|
}
|
|
self.removal_pending = false;
|
|
self.deferred = None;
|
|
self.memory_result = None;
|
|
self.mode = None;
|
|
self.slots.clear();
|
|
self.logical.clear();
|
|
self.presentation = None;
|
|
self.icon.clear();
|
|
self.scratch = None;
|
|
}
|
|
pub(super) fn retain_idle_card_opt(&mut self, card: Option<Card>) {
|
|
self.card = card;
|
|
}
|
|
pub(super) fn retain_idle_card(&mut self, card: Card) {
|
|
self.card = Some(card);
|
|
}
|
|
pub fn take_idle_card(&mut self) -> Result<Option<Card>> {
|
|
if self.mode.is_some() || self.request.is_some() {
|
|
return Err(Error::Busy);
|
|
}
|
|
Ok(self.card.take())
|
|
}
|
|
pub fn pending_job(&self) -> Option<AsyncWorkJobId> {
|
|
self.request.as_ref().map(|r| r.job)
|
|
}
|
|
/// Native worker operation after an explicit outside-game replacement choice.
|
|
/// Same-card reconciliation always retains RAM. No boot or lifecycle hook runs here.
|
|
pub(super) fn replace_storage(
|
|
&mut self,
|
|
storage: Box<dyn prometeu_hal::memcard::MemcardStorage>,
|
|
load_existing: bool,
|
|
control: &PublicationControl,
|
|
) -> Result<()> {
|
|
if self.has_in_flight() || self.boot_active || self.mode.is_none() {
|
|
return Err(Error::Busy);
|
|
}
|
|
if self.icon.is_empty()
|
|
&& let Some(card) = self.card.as_mut()
|
|
{
|
|
self.icon = card.read_icon(self.app_id)?;
|
|
}
|
|
if let Some(card) = &self.card
|
|
&& (card.uncertain || self.faulted)
|
|
{
|
|
self.uncertain_target = card.attempted_publication.clone();
|
|
}
|
|
let known = self.card.as_ref().map(|c| (c.current().card_id, c.known_exclusions()));
|
|
self.card.take(); // Release the old scratch before mounting another image.
|
|
self.scratch = None;
|
|
self.reconcile_blocked = true;
|
|
self.card = Some(Card::mount(storage)?);
|
|
let card = self.card.as_mut().unwrap();
|
|
let same = self.card_id == Some(card.current().card_id);
|
|
if let Some((id, known)) = known
|
|
&& id == card.current().card_id
|
|
{
|
|
card.remember_exclusions(known);
|
|
}
|
|
if card.write_blocked || card.storage_read_only() {
|
|
return Err(Error::ReadOnly);
|
|
}
|
|
if let Some(target) = &self.uncertain_target
|
|
&& target.card_id == card.current().card_id
|
|
{
|
|
// Verify the original map's sequence, logical slots, generations,
|
|
// lengths and CRCs after mount has checked the actual payload bytes.
|
|
if card.current().sequence >= target.sequence
|
|
&& self.logical.iter().any(|&id| {
|
|
id as usize >= SLOT_COUNT
|
|
|| card.current().slots[id as usize] != target.slots[id as usize]
|
|
})
|
|
{
|
|
return Err(Error::Indeterminate);
|
|
}
|
|
}
|
|
if same {
|
|
let game = card
|
|
.catalog
|
|
.games
|
|
.iter()
|
|
.find(|g| g.app_id == self.app_id)
|
|
.ok_or(Error::Corrupt)?;
|
|
if game.slots.get(..self.slots.len()) != Some(self.logical.as_slice()) {
|
|
return Err(Error::Corrupt);
|
|
}
|
|
} else {
|
|
if card.catalog.games.iter().any(|g| g.app_id == self.app_id) {
|
|
card.grow(self.app_id, self.slots.len(), control)?;
|
|
} else {
|
|
if load_existing {
|
|
return Err(Error::InvalidState);
|
|
}
|
|
let mut game = self.presentation.clone().ok_or(Error::InvalidState)?;
|
|
game.slots = vec![0; self.slots.len()];
|
|
card.register(game, &self.icon, control)?;
|
|
}
|
|
self.logical =
|
|
card.catalog.games.iter().find(|g| g.app_id == self.app_id).unwrap().slots
|
|
[..self.slots.len()]
|
|
.to_vec();
|
|
}
|
|
if !same && load_existing {
|
|
self.card_id = None;
|
|
}
|
|
for (slot, &logical) in self.slots.iter().zip(&self.logical) {
|
|
let mut data = slot.data.write().map_err(|_| Error::InvalidState)?;
|
|
if !same && load_existing {
|
|
data.bytes.fill(0);
|
|
data.used = card.read_slot(logical as usize, &mut data.bytes)?;
|
|
data.dirty = false;
|
|
} else {
|
|
let durable = card.current().slots[logical as usize];
|
|
data.dirty = data.used != durable.used as usize
|
|
|| crc32c(&data.bytes[..data.used]) != durable.crc;
|
|
}
|
|
data.descriptor = card.current().slots[logical as usize];
|
|
}
|
|
self.health = (
|
|
card.recovered,
|
|
card.degraded,
|
|
card.write_blocked || card.storage_read_only() || card.uncertain,
|
|
);
|
|
self.card_id = Some(card.current().card_id);
|
|
self.epoch = self.epoch.checked_add(1).ok_or(Error::CounterExhausted)?;
|
|
if !same && load_existing {
|
|
self.presentation =
|
|
card.catalog.games.iter().find(|g| g.app_id == self.app_id).cloned();
|
|
self.icon.clear();
|
|
}
|
|
self.mode = Some(Mode::Persistent);
|
|
self.removal_pending = false;
|
|
self.uncertain_target = None;
|
|
self.faulted = false;
|
|
self.reconcile_blocked = false;
|
|
Ok(())
|
|
}
|
|
pub fn detach(&mut self) -> Result<()> {
|
|
if self.deferred.is_some()
|
|
|| self
|
|
.request
|
|
.as_ref()
|
|
.is_some_and(|r| r.result.state == RequestState::Pending || self.card.is_none())
|
|
{
|
|
return Err(Error::Busy);
|
|
}
|
|
self.mode = Some(Mode::MemoryOnly);
|
|
self.removal_pending = false;
|
|
self.reconcile_blocked = false;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
#[test]
|
|
fn memory_snapshot_limits_isolation_and_no_fake_durability() {
|
|
let mut s = Session::default();
|
|
assert_eq!(s.start_memory(1, 64, 1024), Err(Error::OutOfMemory));
|
|
let c = s.start_memory(1, 2, Session::required_bytes(2).unwrap()).unwrap();
|
|
s.write(c, 0, 3, b"save").unwrap();
|
|
let mut b = [9; 16];
|
|
assert_eq!(s.read(c, 0, 0, &mut b), Ok(7));
|
|
assert_eq!(&b[..7], b"\0\0\0save");
|
|
assert_eq!(s.read(c + 1, 0, 0, &mut b), Err(Error::AccessDenied));
|
|
assert_eq!(s.clear(c, 2), Err(Error::InvalidRange));
|
|
let lane = AsyncWorkLane::default();
|
|
let id = s.commit(c, 0, 0, Instant::now(), &lane).unwrap();
|
|
assert_eq!(s.query(c, id).unwrap().state, RequestState::MemoryOnly);
|
|
assert_eq!(lane.pending_depth(), 0);
|
|
assert!(s.unsaved());
|
|
assert_eq!(s.commit(c, 0, 0, Instant::now(), &lane), Err(Error::Busy));
|
|
s.release_request(c, id).unwrap();
|
|
s.clear(c, 0).unwrap();
|
|
assert_eq!(s.read(c, 0, 0, &mut b), Ok(0));
|
|
}
|
|
#[test]
|
|
fn clear_and_sparse_writes_do_not_expose_previous_bytes() {
|
|
let mut s = Session::default();
|
|
let c = s.start_memory(1, 1, Session::required_bytes(1).unwrap()).unwrap();
|
|
s.write(c, 0, 0, b"secret").unwrap();
|
|
s.clear(c, 0).unwrap();
|
|
s.write(c, 0, 5, b"x").unwrap();
|
|
let mut b = [9; 6];
|
|
assert_eq!(s.read(c, 0, 0, &mut b), Ok(6));
|
|
assert_eq!(b, [0, 0, 0, 0, 0, b'x']);
|
|
}
|
|
}
|