sm64_binds/sm64/sync.rs
1//! [`SM64Game::sync_from`]: making a game a copy of a base again, cheaply
2//! when only a few pages changed since the last time.
3
4use anyhow::{Error, Result};
5
6use super::SM64Game;
7use super::dirty::DirtyTracker;
8
9/// Source of [`SM64Game`] ids, so a sync can tell which base it came from.
10static NEXT_GAME_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
11
12/// What [`SM64Game::sync_from`] keeps between calls.
13pub(super) struct SyncState {
14 /// Unique per game.
15 id: u64,
16 /// Bumped by anything that may change the game's memory ([`Self::touch`]),
17 /// so a sync knows when a base is unchanged.
18 generation: u64,
19 /// The base and its generation this game was last synced from.
20 synced_with: Option<(u64, u64)>,
21 tracker: Option<DirtyTracker>,
22 tracking_unavailable: bool,
23}
24
25impl SyncState {
26 pub(super) fn new() -> SyncState {
27 SyncState {
28 id: NEXT_GAME_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
29 generation: 0,
30 synced_with: None,
31 tracker: None,
32 tracking_unavailable: false,
33 }
34 }
35
36 /// Records that the game's memory may have changed. The only place the
37 /// generation moves: everything that can change memory goes through
38 /// [`SM64Game::parts_mut`] or [`SM64Game::mem_mut`], which call it.
39 pub(super) fn touch(&mut self) {
40 self.generation += 1;
41 }
42
43 fn version(&self) -> (u64, u64) {
44 (self.id, self.generation)
45 }
46}
47
48impl SM64Game {
49 /// Makes this game a copy of `base`, like [`SM64Game::copy_from`] does,
50 /// but cheaper when called repeatedly with the same base.
51 ///
52 /// The first call does a full copy and starts tracking which pages this
53 /// game writes. Later calls copy back only those pages, as long as `base`
54 /// has not changed since the previous sync (anything that could change
55 /// its memory, such as stepping it, counts as a change). Otherwise they
56 /// compare every page with `base` and copy the ones that differ. The result
57 /// is the same either way. Page tracking
58 /// needs Linux 6.7+ (see [`SM64Game::dirty_tracking_active`]); elsewhere
59 /// every call is a full copy.
60 ///
61 /// When `base` changes between calls (eg if it isn't a tree search),
62 /// [`SM64Game::copy_from`] is faster: comparing every page costs more than
63 /// copying them.
64 ///
65 /// With `SM64_VERIFY_SYNC=1` in the environment, every sync is checked
66 /// byte for byte against `base` and fails if they differ.
67 pub fn sync_from(&mut self, base: &SM64Game) -> Result<()> {
68 if base.build_id != self.build_id || base.layout != self.layout {
69 return Err(Error::msg(
70 "sync_from: the base game is a different build of the game",
71 ));
72 }
73 let (base_ptr, base_len) = base.mem();
74 let base_ptr = base_ptr as *const u8;
75 let (ptr, len) = self.mem_mut();
76 let tracked = self
77 .sync
78 .tracker
79 .as_ref()
80 .is_some_and(|t| t.covers(ptr, len));
81 let unchanged_base = self.sync.synced_with == Some(base.sync.version());
82
83 if tracked && unchanged_base && len == base_len {
84 let tracker = self.sync.tracker.as_mut().expect("checked above");
85 let written = tracker.take_written()?;
86 for &(start, end) in &written {
87 // SAFETY: both memories are `len` bytes long and `[start, end)`
88 // lies within the tracked region, which is exactly that long.
89 // They are distinct allocations, so the ranges cannot overlap.
90 unsafe {
91 std::ptr::copy_nonoverlapping(base_ptr.add(start), ptr.add(start), end - start)
92 };
93 }
94 // The copies above wrote those pages again; they match the base now.
95 for &(start, end) in &written {
96 tracker.protect(start, end)?;
97 }
98 } else if tracked && len == base_len {
99 // A different or changed base: copy only the pages that differ from
100 // it, and protect just those again, rather than copying everything
101 // and protecting all of memory (about ten times slower).
102 let tracker = self.sync.tracker.as_mut().expect("checked above");
103 tracker.take_written()?;
104 const PAGE: usize = 4096;
105 let mut copied: Vec<(usize, usize)> = Vec::new();
106 for (start, end) in self.layout.mutable_ranges() {
107 let end = end.min(len);
108 // Whole pages: the read-only bytes in the first page never
109 // change, so they compare equal and copying them is harmless.
110 let mut page = start - start % PAGE;
111 while page < end {
112 let next = (page + PAGE).min(end);
113 // SAFETY: both memories are `len` bytes long and distinct
114 // allocations; `[page, next)` lies within them.
115 let (dst, src) = unsafe {
116 (
117 std::slice::from_raw_parts_mut(ptr.add(page), next - page),
118 std::slice::from_raw_parts(base_ptr.add(page), next - page),
119 )
120 };
121 if dst != src {
122 dst.copy_from_slice(src);
123 match copied.last_mut() {
124 Some(last) if last.1 == page => last.1 = next,
125 _ => copied.push((page, next)),
126 }
127 }
128 page = next;
129 }
130 }
131 for &(start, end) in &copied {
132 tracker.protect(start, end.next_multiple_of(PAGE).min(len))?;
133 }
134 } else {
135 self.copy_from(base)?;
136 self.reset_tracking();
137 }
138 self.sync.synced_with = Some(base.sync.version());
139
140 if verify_syncs() {
141 let (ptr, len) = self.mem();
142 // SAFETY: both memories are valid for their sizes here.
143 let (a, b) = unsafe {
144 (
145 std::slice::from_raw_parts(ptr as *const u8, len),
146 std::slice::from_raw_parts(base_ptr, base_len),
147 )
148 };
149 if let Some(at) = a.iter().zip(b).position(|(x, y)| x != y) {
150 return Err(Error::msg(format!(
151 "sync_from left byte {at:#x} different from the base"
152 )));
153 }
154 }
155 Ok(())
156 }
157
158 /// Whether [`SM64Game::sync_from`] is tracking written pages, rather
159 /// than doing full copies.
160 pub fn dirty_tracking_active(&self) -> bool {
161 self.sync.tracker.is_some()
162 }
163
164 /// Marks every page clean, starting a tracker if needed. Called right
165 /// after a full copy, when this game matches its base.
166 fn reset_tracking(&mut self) {
167 let (ptr, len) = self.mem();
168 let sync = &mut self.sync;
169 if let Some(tracker) = &mut sync.tracker
170 && tracker.covers(ptr, len)
171 && tracker.protect(0, len).is_ok()
172 {
173 return;
174 }
175 // Memory moved or grew, or there is no tracker yet. Dropping the old
176 // tracker closes its userfaultfd, which unregisters the old range.
177 sync.tracker = None;
178 if !sync.tracking_unavailable {
179 sync.tracker = DirtyTracker::new(ptr, len);
180 sync.tracking_unavailable = sync.tracker.is_none();
181 }
182 }
183}
184
185/// Whether `SM64_VERIFY_SYNC` asks for every sync to be checked.
186fn verify_syncs() -> bool {
187 static VERIFY: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
188 *VERIFY.get_or_init(|| std::env::var_os("SM64_VERIFY_SYNC").is_some_and(|v| v != "0"))
189}