dstorage.rs 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555
  1. //! The console's DirectStorage (`XCRDAPI.dll`): a factory that opens files
  2. //! and creates request queues and status arrays the title polls. Its
  3. //! interfaces have grown since 2020 (new interface ids, new slots); the
  4. //! slots here are the ones the title calls, read from its call
  5. //! sites. Slots nobody has needed yet log their offset.
  6. //!
  7. //! A request starts once it is submitted, not before: the title maps the
  8. //! pages a batch is read into, and fills in their page lists, in its own
  9. //! submit (`submit`).
  10. //!
  11. //! Submitted requests of every queue run on one pool of workers, as the
  12. //! console's hardware runs them: in parallel, started in queue order,
  13. //! queues served by weighted round robin over their priorities (about 10x
  14. //! per level, counted in bytes), with at most the staging buffer's worth of
  15. //! compressed source in flight. Each request reads its source (a file or
  16. //! memory), inflates zlib data and/or unpacks BCPack data, and writes the
  17. //! destination (an address, or physical pages). Completion is what stays
  18. //! in order: a status entry is written once every request enqueued before
  19. //! it on its queue has finished, with the first failure (in queue order)
  20. //! since the previous status entry, or success.
  21. #![allow(non_snake_case)]
  22. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  23. use std::borrow::Cow;
  24. use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
  25. use std::ffi::{CStr, c_char, c_void};
  26. use std::os::windows::fs::FileExt;
  27. use std::os::windows::io::FromRawHandle;
  28. use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering};
  29. use std::sync::{Condvar, Mutex, MutexGuard, OnceLock};
  30. use victory_formats::bcpack::{self, Tables};
  31. use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING};
  32. use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put};
  33. use crate::{HleModule, hle_export};
  34. /// The factory interface the title asks for.
  35. const FACTORY: Guid = Guid::new(
  36. 0x6295_9d11,
  37. 0xd45f,
  38. 0x4884,
  39. [0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae],
  40. );
  41. const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
  42. const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
  43. /// `HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)`: the source ends early.
  44. const END_OF_FILE: HRESULT = 0x8007_0026_u32 as i32;
  45. /// `HRESULT_FROM_WIN32(ERROR_INVALID_DATA)`: a bad compressed stream.
  46. const INVALID_DATA: HRESULT = 0x8007_000D_u32 as i32;
  47. type Out = *mut *mut c_void;
  48. static FACTORY_OBJECT: Object = Object::new("dstorage factory", &FACTORY_VTABLE);
  49. pub extern "system" fn DStorageGetFactory(iid: *const Guid, out: Out) -> HRESULT {
  50. // SAFETY: the title passes a GUID (null tolerated).
  51. match unsafe { iid.as_ref() } {
  52. Some(&iid) if iid == FACTORY => {
  53. put(out, std::ptr::from_ref(&FACTORY_OBJECT).cast_mut().cast())
  54. }
  55. iid => {
  56. tracing::warn!(iid = ?iid.map(Guid::to_string), "DStorageGetFactory: unknown interface");
  57. E_NOINTERFACE
  58. }
  59. }
  60. }
  61. /// One of our objects with state: the runtime's object header (method
  62. /// table first), a reference count, then `T`.
  63. #[repr(C)]
  64. struct Instance<T> {
  65. base: Object,
  66. refs: AtomicU32,
  67. state: T,
  68. }
  69. impl<T> Instance<T> {
  70. fn create(base: Object, state: T) -> *mut c_void {
  71. Box::into_raw(Box::new(Instance {
  72. base,
  73. refs: AtomicU32::new(1),
  74. state,
  75. }))
  76. .cast()
  77. }
  78. }
  79. extern "system" fn add_ref_instance<T>(this: *const Instance<T>) -> u32 {
  80. // SAFETY: an instance we created and the title still holds.
  81. unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1
  82. }
  83. extern "system" fn release<T>(this: *mut Instance<T>) -> u32 {
  84. // SAFETY: as above.
  85. let left = unsafe { &*this }.refs.fetch_sub(1, Ordering::AcqRel) - 1;
  86. if left == 0 {
  87. // SAFETY: the last reference; created by `Instance::create`.
  88. drop(unsafe { Box::from_raw(this) });
  89. }
  90. left
  91. }
  92. fn iid_text(iid: *const Guid) -> String {
  93. // SAFETY: the title passes a GUID (null tolerated).
  94. unsafe { iid.as_ref() }.map_or_else(|| "null".into(), Guid::to_string)
  95. }
  96. /// `HRESULT_FROM_WIN32` of a host error.
  97. fn from_win32(error: &std::io::Error) -> HRESULT {
  98. error
  99. .raw_os_error()
  100. .map_or(E_INVALIDARG, |e| (0x8007_0000 | (e as u32 & 0xffff)) as i32)
  101. }
  102. // The factory.
  103. type Factory = *const Object;
  104. /// Opens `path` for reading; the file object owns the handle.
  105. extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out: Out) -> HRESULT {
  106. const GENERIC_READ: u32 = 0x8000_0000;
  107. const FILE_SHARE_READ: u32 = 1;
  108. const OPEN_EXISTING: u32 = 3;
  109. if path.is_null() {
  110. return E_INVALIDARG;
  111. }
  112. // Goes through `files`, so paths on our virtual drives work too.
  113. let handle = super::files::CreateFileW(
  114. path,
  115. GENERIC_READ,
  116. FILE_SHARE_READ,
  117. std::ptr::null(),
  118. OPEN_EXISTING,
  119. 0,
  120. std::ptr::null_mut(),
  121. );
  122. // SAFETY: the title passes a NUL-terminated path.
  123. let name = unsafe {
  124. let len = (0..).take_while(|&i| *path.add(i) != 0).count();
  125. String::from_utf16_lossy(std::slice::from_raw_parts(path, len))
  126. };
  127. if handle as isize == -1 {
  128. let error = std::io::Error::last_os_error();
  129. tracing::warn!(path = name, %error, "dstorage: opening a file failed");
  130. return from_win32(&error);
  131. }
  132. let kept = name.clone();
  133. tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened");
  134. // SAFETY: a handle we just opened and nobody else owns.
  135. let file = unsafe { std::fs::File::from_raw_handle(handle) };
  136. let files = Files::new(file, Io::chosen());
  137. let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { files });
  138. if stream_log::on() {
  139. stream_log::line(format_args!("F\t{:x}\t{kept}", file as usize));
  140. }
  141. WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner()).push((file as usize, kept));
  142. put(out, file)
  143. }
  144. /// `(capacity, name, iid, out)`.
  145. extern "system" fn create_status_array(
  146. _: Factory,
  147. capacity: u32,
  148. name: *const c_char,
  149. iid: *const Guid,
  150. out: Out,
  151. ) -> HRESULT {
  152. tracing::info!(
  153. capacity,
  154. name = text(name),
  155. iid = iid_text(iid),
  156. "dstorage: status array"
  157. );
  158. let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect();
  159. let written = (0..capacity).map(|_| AtomicU64::new(0)).collect();
  160. let array = Instance::create(
  161. Object::new("dstorage status array", &STATUS_VTABLE),
  162. StatusArray { entries, written },
  163. );
  164. put(out, array)
  165. }
  166. /// The queue's description: as in 2020 (source type, capacity, priority,
  167. /// name), plus a field the title sets to 1.
  168. #[repr(C)]
  169. struct QueueDesc {
  170. source_type: u64,
  171. capacity: u16,
  172. priority: i8,
  173. name: *const c_char,
  174. unknown: u64,
  175. }
  176. extern "system" fn create_queue(
  177. _: Factory,
  178. desc: *const QueueDesc,
  179. iid: *const Guid,
  180. out: Out,
  181. ) -> HRESULT {
  182. // SAFETY: the title passes its description (null tolerated).
  183. let Some(desc) = (unsafe { desc.as_ref() }) else {
  184. return E_INVALIDARG;
  185. };
  186. let name = text(desc.name);
  187. tracing::info!(
  188. source = desc.source_type,
  189. capacity = desc.capacity,
  190. priority = desc.priority,
  191. name,
  192. unknown = desc.unknown,
  193. iid = iid_text(iid),
  194. "dstorage: queue"
  195. );
  196. let Some(scheduler) = scheduler() else {
  197. return E_OUTOFMEMORY;
  198. };
  199. let mut lanes = scheduler.lock();
  200. let id = lanes.next_id;
  201. lanes.next_id += 1;
  202. let lane = Lane::new(desc.priority, desc.capacity);
  203. lanes.lanes.insert(id, lane);
  204. drop(lanes);
  205. put(
  206. out,
  207. Instance::create(Object::new("dstorage queue", &QUEUE_VTABLE), Queue { id }),
  208. )
  209. }
  210. /// The title asks for 32 MiB and stops if this fails. Give PC worker threads
  211. /// enough staging headroom (default 256 MiB) so multi-MB RPF chunks don't
  212. /// starve the remaining cores.
  213. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT {
  214. static FLOOR_MB: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
  215. let floor = *FLOOR_MB.get_or_init(|| {
  216. std::env::var("VICTORY_DSTORAGE_STAGING_MB")
  217. .ok()
  218. .and_then(|v| v.trim().parse::<u64>().ok())
  219. .unwrap_or(256)
  220. }) << 20;
  221. tracing::info!(size, floor, "dstorage: staging buffer size");
  222. if let Some(scheduler) = scheduler() {
  223. scheduler.lock().staging = u64::from(size).max(floor);
  224. }
  225. S_OK
  226. }
  227. fn text(name: *const c_char) -> String {
  228. if name.is_null() {
  229. return String::new();
  230. }
  231. // SAFETY: a NUL-terminated name from the title.
  232. unsafe { CStr::from_ptr(name) }
  233. .to_string_lossy()
  234. .into_owned()
  235. }
  236. static FACTORY_VTABLE: Methods<16> = Methods([
  237. missing::<0> as *const (),
  238. add_ref as *const (),
  239. add_ref as *const (),
  240. missing::<3> as *const (), // 0x18 (2020: queue creation)
  241. open_file as *const (), // 0x20
  242. create_status_array as *const (), // 0x28
  243. missing::<6> as *const (), // 0x30 (2020: CPU affinity)
  244. missing::<7> as *const (), // 0x38 (2020: debug flags)
  245. set_staging_buffer_size as *const (), // 0x40
  246. missing::<9> as *const (),
  247. create_queue as *const (), // 0x50
  248. missing::<11> as *const (),
  249. missing::<12> as *const (),
  250. missing::<13> as *const (),
  251. missing::<14> as *const (),
  252. missing::<15> as *const (),
  253. ]);
  254. // Files.
  255. struct File {
  256. files: Files,
  257. }
  258. /// How files are read (`VICTORY_DSTORAGE_IO`).
  259. #[derive(Clone, Copy, Debug, PartialEq, Eq)]
  260. enum Io {
  261. /// `one`: all workers through the one handle, as before. The host does
  262. /// the reads of a handle one after the other.
  263. One,
  264. /// `handles`: a handle for each worker.
  265. Handles,
  266. /// `overlapped`: one handle, whose reads the host does side by side.
  267. Overlapped,
  268. /// `direct`: a handle for each worker, past the host's file cache.
  269. Direct,
  270. }
  271. impl Io {
  272. fn chosen() -> Io {
  273. static CHOSEN: OnceLock<Io> = OnceLock::new();
  274. *CHOSEN.get_or_init(|| {
  275. let io = match std::env::var("VICTORY_DSTORAGE_IO").as_deref().map(str::trim) {
  276. Ok("one") => Io::One,
  277. Ok("handles") => Io::Handles,
  278. Ok("overlapped") => Io::Overlapped,
  279. Ok("direct") => Io::Direct,
  280. _ => Io::DEFAULT,
  281. };
  282. tracing::info!(?io, "dstorage: how files are read (VICTORY_DSTORAGE_IO)");
  283. io
  284. })
  285. }
  286. const DEFAULT: Io = Io::Handles;
  287. }
  288. /// A file as the workers read it: the handle the title opened, and those
  289. /// made from it when a worker first reads.
  290. struct Files {
  291. first: std::fs::File,
  292. others: Box<[OnceLock<Option<std::fs::File>>]>,
  293. io: Io,
  294. }
  295. impl Files {
  296. fn new(first: std::fs::File, io: Io) -> Files {
  297. let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
  298. let others = match io {
  299. Io::One => 0,
  300. Io::Overlapped => 1,
  301. Io::Handles | Io::Direct => workers,
  302. };
  303. Files { first, others: (0..others).map(|_| OnceLock::new()).collect(), io }
  304. }
  305. #[cfg(test)]
  306. fn open_for_test(path: &str, io: Io) -> Files {
  307. Files::new(std::fs::File::open(path).unwrap(), io)
  308. }
  309. /// Reads at `offset`; as [`FileExt::seek_read`].
  310. fn read_at(&self, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
  311. use windows_sys::Win32::Storage::FileSystem::{FILE_FLAG_NO_BUFFERING, FILE_FLAG_OVERLAPPED};
  312. let flags = match self.io {
  313. Io::One | Io::Handles => 0,
  314. Io::Overlapped => FILE_FLAG_OVERLAPPED,
  315. Io::Direct => FILE_FLAG_OVERLAPPED | FILE_FLAG_NO_BUFFERING,
  316. };
  317. let other = match self.others.len() {
  318. 0 => None,
  319. n => self.others[this_thread() % n].get_or_init(|| reopen(&self.first, flags)).as_ref(),
  320. };
  321. match (other, self.io) {
  322. (Some(file), Io::Overlapped) => read_overlapped(file, out, offset),
  323. (Some(file), Io::Direct) => read_direct(file, out, offset),
  324. (file, _) => file.unwrap_or(&self.first).seek_read(out, offset),
  325. }
  326. }
  327. }
  328. /// A number for this thread: 0 for the first that asks, and so on.
  329. fn this_thread() -> usize {
  330. static NEXT: AtomicU32 = AtomicU32::new(0);
  331. thread_local! {
  332. static NUMBER: usize = NEXT.fetch_add(1, Ordering::Relaxed) as usize;
  333. }
  334. NUMBER.with(|n| *n)
  335. }
  336. /// Another handle to `file`, for reading; `None` if the host gives none
  337. /// (then the first one is used).
  338. fn reopen(file: &std::fs::File, flags: u32) -> Option<std::fs::File> {
  339. use std::os::windows::io::AsRawHandle;
  340. use windows_sys::Win32::Foundation::{GENERIC_READ, INVALID_HANDLE_VALUE};
  341. use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_READ, ReOpenFile};
  342. // SAFETY: a file we hold open.
  343. let handle = unsafe { ReOpenFile(file.as_raw_handle(), GENERIC_READ, FILE_SHARE_READ, flags) };
  344. if handle == INVALID_HANDLE_VALUE {
  345. tracing::warn!(error = %std::io::Error::last_os_error(), flags, "dstorage: a file could not be opened again");
  346. return None;
  347. }
  348. // SAFETY: a handle just opened, ours alone.
  349. Some(unsafe { std::fs::File::from_raw_handle(handle) })
  350. }
  351. /// A read through a handle opened for overlapped reads, waited for.
  352. fn read_overlapped(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
  353. use std::os::windows::io::AsRawHandle;
  354. use windows_sys::Win32::Foundation::{CloseHandle, ERROR_HANDLE_EOF, ERROR_IO_PENDING, HANDLE};
  355. use windows_sys::Win32::Storage::FileSystem::ReadFile;
  356. use windows_sys::Win32::System::IO::{GetOverlappedResult, OVERLAPPED};
  357. use windows_sys::Win32::System::Threading::CreateEventW;
  358. /// Set when this thread's read is done.
  359. struct Event(HANDLE);
  360. impl Drop for Event {
  361. fn drop(&mut self) {
  362. // SAFETY: our own event.
  363. unsafe { CloseHandle(self.0) };
  364. }
  365. }
  366. thread_local! {
  367. static DONE: Event =
  368. // SAFETY: a plain manual-reset event.
  369. Event(unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) });
  370. }
  371. DONE.with(|done| {
  372. if done.0.is_null() {
  373. return Err(std::io::Error::last_os_error());
  374. }
  375. let mut overlapped = OVERLAPPED { hEvent: done.0, ..Default::default() };
  376. overlapped.Anonymous.Anonymous.Offset = offset as u32;
  377. overlapped.Anonymous.Anonymous.OffsetHigh = (offset >> 32) as u32;
  378. let len = out.len().min(1 << 30) as u32;
  379. let mut n = 0;
  380. // SAFETY: `out` and `overlapped` stay until the read is done, which
  381. // is waited for.
  382. let mut read = unsafe {
  383. ReadFile(file.as_raw_handle(), out.as_mut_ptr(), len, std::ptr::null_mut(), &mut overlapped)
  384. } != 0;
  385. let mut error = std::io::Error::last_os_error();
  386. if read || error.raw_os_error() == Some(ERROR_IO_PENDING as i32) {
  387. // SAFETY: as above.
  388. read = unsafe { GetOverlappedResult(file.as_raw_handle(), &overlapped, &mut n, 1) } != 0;
  389. error = std::io::Error::last_os_error();
  390. }
  391. match error.raw_os_error() {
  392. _ if read => Ok(n as usize),
  393. Some(code) if code == ERROR_HANDLE_EOF as i32 => Ok(0),
  394. _ => Err(error),
  395. }
  396. })
  397. }
  398. /// A read past the file cache: of the whole sectors around the bytes, into
  399. /// a buffer of this thread's, unless `out` takes them as they are.
  400. fn read_direct(file: &std::fs::File, out: &mut [u8], offset: u64) -> std::io::Result<usize> {
  401. /// Every disk's sectors are at most this; offsets, sizes and addresses
  402. /// are multiples of it.
  403. const SECTOR: usize = 4096;
  404. /// Read at a time.
  405. const MOST: usize = 1 << 20;
  406. let sector = SECTOR as u64;
  407. if offset % sector == 0 && out.len() % SECTOR == 0 && out.as_ptr() as usize % SECTOR == 0 {
  408. return read_overlapped(file, out, offset);
  409. }
  410. thread_local! {
  411. static BUFFER: std::cell::RefCell<Vec<u8>> = std::cell::RefCell::new(vec![0; MOST + SECTOR]);
  412. }
  413. BUFFER.with_borrow_mut(|buffer| {
  414. let skip = buffer.as_ptr().align_offset(SECTOR);
  415. let before = (offset % sector) as usize;
  416. let len = (before + out.len()).next_multiple_of(SECTOR).min(MOST);
  417. let aligned = &mut buffer[skip..skip + len];
  418. let read = read_overlapped(file, aligned, offset - before as u64)?;
  419. let n = read.saturating_sub(before).min(out.len());
  420. out[..n].copy_from_slice(&aligned[before..before + n]);
  421. Ok(n)
  422. })
  423. }
  424. static FILE_VTABLE: Methods<8> = Methods([
  425. missing::<0> as *const (),
  426. add_ref_instance::<File> as *const (),
  427. release::<File> as *const (),
  428. missing::<3> as *const (),
  429. missing::<4> as *const (),
  430. missing::<5> as *const (),
  431. missing::<6> as *const (),
  432. missing::<7> as *const (),
  433. ]);
  434. // Status arrays.
  435. struct StatusArray {
  436. entries: Box<[AtomicI32]>,
  437. /// For the log: when each entry was written ([`stream_log::now`]); 0
  438. /// once the title has seen it.
  439. written: Box<[AtomicU64]>,
  440. }
  441. type Array = *mut Instance<StatusArray>;
  442. /// The result of the requests before entry `index`: pending, the first
  443. /// failure, or success.
  444. extern "system" fn status_result(this: Array, index: u32) -> HRESULT {
  445. // SAFETY: an array we created and the title still holds.
  446. let entries = &unsafe { &*this }.state.entries;
  447. entries
  448. .get(index as usize)
  449. .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire))
  450. }
  451. /// The title polls this (entry 0, a `Sleep(1)` loop) and never
  452. /// reads the result itself.
  453. extern "system" fn is_complete(this: Array, index: u32) -> bool {
  454. let done = status_result(this, index) != E_PENDING;
  455. if done && stream_log::on() {
  456. // SAFETY: as above.
  457. let written = &unsafe { &*this }.state.written;
  458. if let Some(at) = written.get(index as usize).map(|w| w.swap(0, Ordering::Relaxed)).filter(|&at| at != 0) {
  459. stream_log::line(format_args!("P\t{:x}\t{at}\t{}", this as usize, stream_log::now()));
  460. }
  461. }
  462. done
  463. }
  464. static STATUS_VTABLE: Methods<5> = Methods([
  465. missing::<0> as *const (),
  466. add_ref_instance::<StatusArray> as *const (),
  467. release::<StatusArray> as *const (),
  468. is_complete as *const (), // 0x18
  469. status_result as *const (), // 0x20
  470. ]);
  471. // Queues.
  472. /// A queue object: its lane in the scheduler.
  473. struct Queue {
  474. id: u64,
  475. }
  476. impl Drop for Queue {
  477. fn drop(&mut self) {
  478. close_lane(self.id);
  479. }
  480. }
  481. type QueueRef = *const Instance<Queue>;
  482. /// Every queue's requests, run by a pool of workers.
  483. struct Scheduler {
  484. lanes: Mutex<Lanes>,
  485. /// Requests to start, or staging space freed.
  486. work: Condvar,
  487. /// A request finished (for full queues and `close`).
  488. finished: Condvar,
  489. }
  490. /// Priority weights per class (low, normal, high and real-time), as the
  491. /// console's: about 10x per level, counted against request sizes.
  492. const COST: [u64; 3] = [100, 10, 1];
  493. /// The console's default staging buffer.
  494. const STAGING: u64 = 32 << 20;
  495. struct Lanes {
  496. lanes: HashMap<u64, Lane>,
  497. next_id: u64,
  498. /// Submission order over all queues.
  499. next_seq: u64,
  500. /// Bytes of staging held by running requests, and the limit.
  501. staged: u64,
  502. staging: u64,
  503. /// A start waited for staging space since the last finish.
  504. starved: bool,
  505. /// Weighted round robin: each class's virtual time (bytes × cost), and
  506. /// the time of the last start; within a class, the lane clock of the
  507. /// last start.
  508. clock: [u64; 3],
  509. now: u64,
  510. lane_now: [u64; 3],
  511. /// Since the last debug summary: requests, bytes written, time spent
  512. /// running them.
  513. done: (u64, u64, std::time::Duration),
  514. refused: u64,
  515. /// BCPack bytes written and time spent on them.
  516. bcpack: (u64, std::time::Duration),
  517. since: Option<std::time::Instant>,
  518. }
  519. /// A queue's requests in the scheduler.
  520. struct Lane {
  521. class: usize,
  522. capacity: usize,
  523. /// Bytes started, for round robin among the lanes of a class.
  524. clock: u64,
  525. /// Enqueued, not yet submitted.
  526. unsubmitted: Vec<Command>,
  527. /// Submitted, by sequence number: reads not started, status entries
  528. /// not written, reads running, and failures not yet reported.
  529. reads: VecDeque<(u64, Read)>,
  530. statuses: VecDeque<(u64, Status)>,
  531. running: BTreeSet<u64>,
  532. failures: BTreeMap<u64, HRESULT>,
  533. closed: bool,
  534. }
  535. // SAFETY: requests point into title memory and our own objects, which stay
  536. // valid until the title has seen them complete; status arrays count their
  537. // references atomically.
  538. unsafe impl Send for Lane {}
  539. /// A read a worker runs.
  540. struct Job {
  541. lane: u64,
  542. seq: u64,
  543. request: Request,
  544. note: Note,
  545. staging: u64,
  546. }
  547. // SAFETY: as for `Lane`.
  548. unsafe impl Send for Job {}
  549. /// The scheduler, with its workers started on first use; `None` if not
  550. /// even one worker could start.
  551. fn scheduler() -> Option<&'static Scheduler> {
  552. static SCHEDULER: OnceLock<Option<Scheduler>> = OnceLock::new();
  553. static STARTED: std::sync::Once = std::sync::Once::new();
  554. let scheduler = SCHEDULER
  555. .get_or_init(|| {
  556. Some(Scheduler {
  557. lanes: Mutex::new(Lanes {
  558. lanes: HashMap::new(),
  559. next_id: 0,
  560. next_seq: 0,
  561. staged: 0,
  562. staging: STAGING,
  563. starved: false,
  564. clock: [0; 3],
  565. now: 0,
  566. lane_now: [0; 3],
  567. done: Default::default(),
  568. refused: 0,
  569. bcpack: Default::default(),
  570. since: None,
  571. }),
  572. work: Condvar::new(),
  573. finished: Condvar::new(),
  574. })
  575. })
  576. .as_ref()?;
  577. STARTED.call_once(|| {
  578. let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
  579. let started = (0..workers)
  580. .filter(|i| {
  581. std::thread::Builder::new()
  582. .name(format!("dstorage {i}"))
  583. .spawn(|| work(scheduler))
  584. .is_ok()
  585. })
  586. .count();
  587. tracing::info!(workers = started, "dstorage: workers");
  588. });
  589. Some(scheduler)
  590. }
  591. impl Scheduler {
  592. fn lock(&self) -> MutexGuard<'_, Lanes> {
  593. self.lanes.lock().unwrap_or_else(|e| e.into_inner())
  594. }
  595. }
  596. /// The walls trace (`VICTORY_WALLS_TRACE`): 0 or unset: off; 1: a line for
  597. /// every read request that fails, with its file; 2: for every request (the
  598. /// list of a launch's reads, by file and offset, is what a launch with the
  599. /// first room's walls and one without are compared by).
  600. fn walls_trace() -> u8 {
  601. static ON: OnceLock<u8> = OnceLock::new();
  602. *ON.get_or_init(|| {
  603. std::env::var("VICTORY_WALLS_TRACE").ok().and_then(|v| v.trim().parse::<u8>().ok()).unwrap_or(0)
  604. })
  605. }
  606. /// The files opened, by the address of our file object, with their paths
  607. /// (for the walls trace: a request names its file by that address).
  608. static WALLS_FILES: Mutex<Vec<(usize, String)>> = Mutex::new(Vec::new());
  609. /// The walls trace's line for a request that is done.
  610. fn walls_request(request: &Request, result: &Result<(), HRESULT>, started: std::time::Instant) {
  611. let level = walls_trace();
  612. if level == 0 || (level == 1 && result.is_ok()) {
  613. return;
  614. }
  615. let file = if request.options & MEMORY_SOURCE != 0 {
  616. "memory".to_string()
  617. } else {
  618. let files = WALLS_FILES.lock().unwrap_or_else(|e| e.into_inner());
  619. let source = request.source as usize;
  620. files.iter().find(|f| f.0 == source).map_or_else(|| "?".to_string(), |f| f.1.clone())
  621. };
  622. let hr = match result {
  623. Ok(()) => 0,
  624. Err(hr) => *hr as u32,
  625. };
  626. tracing::info!(
  627. file,
  628. offset = request.offset,
  629. source_size = request.source_size,
  630. destination_size = request.destination_size,
  631. to_pages = request.options & PAGE_DESTINATION != 0,
  632. options = format_args!("{:#x}", request.options),
  633. ms = started.elapsed().as_millis() as u64,
  634. ok = result.is_ok(),
  635. hr = format_args!("{hr:#010x}"),
  636. "walls trace: a read request is done"
  637. );
  638. }
  639. /// The streaming log (`VICTORY_DSTORAGE_LOG=<file>`): a line for every
  640. /// request (`R`: queue, number, file, offset, source bytes, destination
  641. /// bytes, options, when enqueued, submitted, started, done, result), every
  642. /// status entry written (`S`: array, number, when enqueued, when written),
  643. /// the title's first look at it after (`P`: array, when written, when
  644. /// seen), every file opened (`F`), and each second what the title's mapping
  645. /// calls cost (`M`, `xmem::map_costs`). Times are milliseconds since the
  646. /// Unix epoch.
  647. pub(crate) mod stream_log {
  648. use super::*;
  649. use std::io::Write;
  650. type Log = Mutex<std::io::BufWriter<std::fs::File>>;
  651. fn log() -> Option<&'static Log> {
  652. static LOG: OnceLock<Option<Log>> = OnceLock::new();
  653. LOG.get_or_init(|| {
  654. let path = std::env::var_os("VICTORY_DSTORAGE_LOG")?;
  655. let file = std::fs::File::create(&path).ok()?;
  656. std::thread::spawn(|| {
  657. loop {
  658. std::thread::sleep(std::time::Duration::from_secs(1));
  659. if let Some(costs) = super::super::xmem::map_costs() {
  660. line(format_args!("M\t{}\t{costs}", now()));
  661. }
  662. if let Some(log) = log() {
  663. let _ = log.lock().unwrap_or_else(|e| e.into_inner()).flush();
  664. }
  665. }
  666. });
  667. Some(Mutex::new(std::io::BufWriter::with_capacity(1 << 20, file)))
  668. })
  669. .as_ref()
  670. }
  671. pub(crate) fn on() -> bool {
  672. static ON: OnceLock<bool> = OnceLock::new();
  673. *ON.get_or_init(|| std::env::var_os("VICTORY_DSTORAGE_LOG").is_some())
  674. }
  675. /// Milliseconds since the Unix epoch.
  676. pub(super) fn now() -> u64 {
  677. std::time::SystemTime::now()
  678. .duration_since(std::time::UNIX_EPOCH)
  679. .map_or(0, |t| t.as_millis() as u64)
  680. }
  681. pub(super) fn line(text: std::fmt::Arguments) {
  682. if let Some(log) = log() {
  683. let _ = writeln!(log.lock().unwrap_or_else(|e| e.into_inner()), "{text}");
  684. }
  685. }
  686. pub(super) fn request(job: &Job, started: std::time::Instant, result: &Result<(), HRESULT>) {
  687. if !on() {
  688. return;
  689. }
  690. let now = now();
  691. let ago = |t: Option<std::time::Instant>| now - t.map_or(0, |t| t.elapsed().as_millis() as u64);
  692. let r = &job.request;
  693. line(format_args!(
  694. "R\t{}\t{}\t{:x}\t{}\t{}\t{}\t{:x}\t{}\t{}\t{}\t{now}\t{:x}",
  695. job.lane,
  696. job.seq,
  697. r.source as usize,
  698. r.offset,
  699. r.source_size,
  700. r.destination_size,
  701. r.options,
  702. ago(job.note.enqueued),
  703. ago(job.note.submitted),
  704. ago(Some(started)),
  705. result.err().unwrap_or(0)
  706. ));
  707. }
  708. }
  709. /// A worker: runs the next read of the most deserving queue.
  710. fn work(scheduler: &'static Scheduler) {
  711. let mut lanes = scheduler.lock();
  712. loop {
  713. let Some(job) = lanes.start() else {
  714. lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner());
  715. continue;
  716. };
  717. drop(lanes);
  718. let started = std::time::Instant::now();
  719. let traced = Traced::start(&job);
  720. let reading = victory_gpu::timeline::span("streaming: a request");
  721. let result = execute(&job.request);
  722. reading.end();
  723. walls_request(&job.request, &result, started);
  724. stream_log::request(&job, started, &result);
  725. if let Some(traced) = traced {
  726. traced.end(&job, &result);
  727. }
  728. lanes = scheduler.lock();
  729. lanes.finish(&job, result);
  730. lanes.count(&job, started);
  731. if std::mem::take(&mut lanes.starved) {
  732. scheduler.work.notify_all();
  733. }
  734. scheduler.finished.notify_all();
  735. }
  736. }
  737. impl Lanes {
  738. /// Counts a finished request; every 5 s a debug line sums them up.
  739. fn count(&mut self, job: &Job, started: std::time::Instant) {
  740. let (requests, bytes, busy) = &mut self.done;
  741. *requests += 1;
  742. *bytes += u64::from(job.request.destination_size);
  743. *busy += started.elapsed();
  744. if job.request.options & BCPACK != 0 {
  745. self.bcpack.0 += u64::from(job.request.destination_size);
  746. self.bcpack.1 += started.elapsed();
  747. }
  748. let since = *self.since.get_or_insert(started);
  749. let elapsed = since.elapsed();
  750. if elapsed.as_secs() >= 5 {
  751. let waiting: usize = self.lanes.values().map(|l| l.reads.len()).sum();
  752. let reading = READING.swap(0, Ordering::Relaxed) as f64 / 1e9;
  753. tracing::debug!(
  754. requests = *requests,
  755. mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6),
  756. busy_workers = format_args!("{:.2}", busy.as_secs_f64() / elapsed.as_secs_f64()),
  757. reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()),
  758. staging_waits = std::mem::take(&mut self.refused),
  759. bcpack_mb = self.bcpack.0 / 1_000_000,
  760. bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()),
  761. waiting,
  762. "dstorage: last {:.1} s",
  763. elapsed.as_secs_f64()
  764. );
  765. self.done = Default::default();
  766. self.bcpack = Default::default();
  767. self.since = None;
  768. }
  769. }
  770. /// Starts the next read of the class with the least virtual time, from
  771. /// its lane that has started the fewest bytes, if the staging buffer
  772. /// has room for it (or nothing else holds any).
  773. fn start(&mut self) -> Option<Job> {
  774. let busy = || self.lanes.iter().filter(|(_, l)| !l.reads.is_empty());
  775. let (_, class) = busy().map(|(_, l)| (self.clock[l.class], l.class)).min()?;
  776. let (_, _, id) = busy()
  777. .filter(|(_, l)| l.class == class)
  778. .filter_map(|(&id, l)| Some((l.clock, l.reads.front()?.0, id)))
  779. .min()?;
  780. let lane = self.lanes.get_mut(&id)?;
  781. let &(seq, Read { request, note }) = lane.reads.front()?;
  782. let staging = staging_bytes(&request);
  783. if self.staged > 0 && self.staged + staging > self.staging {
  784. self.starved = true;
  785. self.refused += 1;
  786. return None;
  787. }
  788. lane.reads.pop_front();
  789. lane.running.insert(seq);
  790. self.staged += staging;
  791. let size = u64::from(request.destination_size.max(request.source_size)).max(1);
  792. self.now = self.clock[class];
  793. self.clock[class] += size * COST[class];
  794. self.lane_now[class] = lane.clock;
  795. lane.clock += size;
  796. Some(Job {
  797. lane: id,
  798. seq,
  799. request,
  800. note,
  801. staging,
  802. })
  803. }
  804. fn finish(&mut self, job: &Job, result: Result<(), HRESULT>) {
  805. self.staged -= job.staging;
  806. if let Some(lane) = self.lanes.get_mut(&job.lane) {
  807. lane.running.remove(&job.seq);
  808. if let Err(hr) = result {
  809. lane.failures.insert(job.seq, hr);
  810. }
  811. lane.flush();
  812. }
  813. }
  814. /// Moves a queue's enqueued commands to the workers; `early` when the
  815. /// title has not asked for it ([`queue`]).
  816. fn submit(&mut self, id: u64, early: bool) {
  817. let Some(class) = self.lanes.get(&id).map(|l| l.class) else {
  818. return;
  819. };
  820. // A class that had nothing waiting starts from now, not from the
  821. // credit it left behind.
  822. if !self
  823. .lanes
  824. .values()
  825. .any(|l| l.class == class && !l.reads.is_empty())
  826. {
  827. self.clock[class] = self.clock[class].max(self.now);
  828. }
  829. let Some(lane) = self.lanes.get_mut(&id) else {
  830. return;
  831. };
  832. if lane.reads.is_empty() {
  833. lane.clock = lane.clock.max(self.lane_now[class]);
  834. }
  835. trace_batch(id, &lane.unsubmitted, early);
  836. for command in std::mem::take(&mut lane.unsubmitted) {
  837. let seq = self.next_seq;
  838. self.next_seq += 1;
  839. match command {
  840. Command::Read(mut read) => {
  841. read.note.submitted(&read.request, early);
  842. lane.reads.push_back((seq, read));
  843. }
  844. Command::Status(status) => lane.statuses.push_back((seq, status)),
  845. }
  846. }
  847. lane.flush();
  848. }
  849. }
  850. impl Lane {
  851. fn new(priority: i8, capacity: u16) -> Lane {
  852. Lane {
  853. class: priority.clamp(-1, 1).wrapping_add(1) as usize,
  854. capacity: usize::from(capacity),
  855. clock: 0,
  856. unsubmitted: Vec::new(),
  857. reads: VecDeque::new(),
  858. statuses: VecDeque::new(),
  859. running: BTreeSet::new(),
  860. failures: BTreeMap::new(),
  861. closed: false,
  862. }
  863. }
  864. /// Requests and status entries held, submitted or not.
  865. fn entries(&self) -> usize {
  866. self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len()
  867. }
  868. /// Writes the status entries whose earlier reads have all finished.
  869. fn flush(&mut self) {
  870. while let Some(&(seq, _)) = self.statuses.front() {
  871. let waiting = self.reads.front().map(|r| r.0);
  872. if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) {
  873. return;
  874. }
  875. let Some((_, status)) = self.statuses.pop_front() else {
  876. return;
  877. };
  878. let later = self.failures.split_off(&seq);
  879. let first = std::mem::replace(&mut self.failures, later)
  880. .into_values()
  881. .next();
  882. if stream_log::on() {
  883. let at = stream_log::now();
  884. stream_log::line(format_args!("S\t{:x}\t{seq}\t{}\t{at}", status.array as usize, status.enqueued));
  885. status.written().store(at, Ordering::Relaxed);
  886. }
  887. status
  888. .entry()
  889. .store(first.unwrap_or(S_OK), Ordering::Release);
  890. }
  891. }
  892. }
  893. /// Staging bytes a request holds while it runs: what it buffers between
  894. /// the file and the destination. Raw reads go straight to their
  895. /// destination, memory sources need none (as on the console).
  896. fn staging_bytes(request: &Request) -> u64 {
  897. let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0;
  898. if buffered && request.options & MEMORY_SOURCE == 0 {
  899. u64::from(request.source_size)
  900. } else {
  901. 0
  902. }
  903. }
  904. /// Ends a queue: what was not started is dropped, and this waits for the
  905. /// reads already running (they write title memory).
  906. fn close_lane(id: u64) {
  907. let Some(scheduler) = scheduler() else {
  908. return;
  909. };
  910. let mut lanes = scheduler.lock();
  911. let Some(lane) = lanes.lanes.get_mut(&id) else {
  912. return;
  913. };
  914. lane.closed = true;
  915. lane.unsubmitted.clear();
  916. lane.reads.clear();
  917. lane.statuses.clear(); // releases their arrays
  918. while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) {
  919. lanes = scheduler
  920. .finished
  921. .wait(lanes)
  922. .unwrap_or_else(|e| e.into_inner());
  923. }
  924. lanes.lanes.remove(&id);
  925. scheduler.finished.notify_all();
  926. }
  927. /// A read request as the title builds it, 0x48 bytes.
  928. #[repr(C)]
  929. #[derive(Clone, Copy)]
  930. struct Request {
  931. options: u64,
  932. /// An address, or with `PAGE_DESTINATION` an array of 64 KiB page
  933. /// numbers.
  934. destination: *mut c_void,
  935. /// With `PAGE_DESTINATION`, the low 16 bits are where in the first page
  936. /// the destination starts.
  937. page_offset: u64,
  938. destination_size: u32,
  939. /// Our file object, or with `MEMORY_SOURCE` an address.
  940. source: *const c_void,
  941. offset: u64,
  942. source_size: u32,
  943. /// Compressed size between two decompression stages; unused here.
  944. intermediate_size: u32,
  945. /// Matched by cancellation; the title leaves it 0.
  946. tag: u64,
  947. name: *const c_char,
  948. }
  949. // Request options.
  950. /// Inflate zlib (RFC 1950) data.
  951. const ZLIB: u64 = 1;
  952. /// Bits 1-4: decode BCPack data of this BC format number (0: none).
  953. const BCPACK: u64 = 0xf << 1;
  954. const PAGE_DESTINATION: u64 = 1 << 21;
  955. const MEMORY_SOURCE: u64 = 1 << 22;
  956. // Bits 5-20 select a further transform, bit 23 a source in physical pages;
  957. // The title's packages need neither, so requests with them fail.
  958. const PAGE: usize = 64 * 1024;
  959. enum Command {
  960. Read(Read),
  961. Status(Status),
  962. }
  963. /// An enqueued request, and what the trace knows of it.
  964. #[derive(Clone, Copy)]
  965. struct Read {
  966. request: Request,
  967. note: Note,
  968. }
  969. /// The streaming trace (`VICTORY_DSTORAGE_TRACE`): 0 or unset: off; 1: a
  970. /// line for every batch, and for every request whose page list, or whose
  971. /// pages' mapping, changed when it should not have, or whose bytes another
  972. /// running request writes too; 2: a line for every request.
  973. fn trace() -> u8 {
  974. static ON: OnceLock<u8> = OnceLock::new();
  975. *ON.get_or_init(|| {
  976. std::env::var("VICTORY_DSTORAGE_TRACE").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(0)
  977. })
  978. }
  979. /// When a request was enqueued and submitted, and what its page list held
  980. /// then (a hash; 0 without a list). Only filled in for the trace, but for
  981. /// `early`.
  982. #[derive(Clone, Copy, Default)]
  983. struct Note {
  984. enqueued: Option<std::time::Instant>,
  985. at_enqueue: u64,
  986. submitted: Option<std::time::Instant>,
  987. at_submit: u64,
  988. /// Started before the title's submit.
  989. early: bool,
  990. }
  991. impl Note {
  992. fn enqueued(request: &Request) -> Note {
  993. match trace() {
  994. 0 if stream_log::on() => Note { enqueued: Some(std::time::Instant::now()), ..Note::default() },
  995. 0 => Note::default(),
  996. _ => Note {
  997. enqueued: Some(std::time::Instant::now()),
  998. at_enqueue: list_hash(request),
  999. ..Note::default()
  1000. },
  1001. }
  1002. }
  1003. fn submitted(&mut self, request: &Request, early: bool) {
  1004. self.early = early;
  1005. if trace() > 0 || stream_log::on() {
  1006. self.submitted = Some(std::time::Instant::now());
  1007. }
  1008. if trace() > 0 {
  1009. self.at_submit = list_hash(request);
  1010. }
  1011. }
  1012. }
  1013. /// A hash of the page numbers a request's list holds now; 0 without one.
  1014. fn list_hash(request: &Request) -> u64 {
  1015. list_of(request).map_or(0, |pages| {
  1016. // FNV-1a; never 0.
  1017. pages.iter().fold(0xcbf2_9ce4_8422_2325_u64, |h, &p| (h ^ p as u64).wrapping_mul(0x100_0000_01b3)) | 1
  1018. })
  1019. }
  1020. /// The page numbers a request's list holds now.
  1021. fn list_of(request: &Request) -> Option<Vec<usize>> {
  1022. (request.options & PAGE_DESTINATION != 0 && !request.destination.is_null()).then(|| {
  1023. let (offset, len) = Traced::bytes(request);
  1024. read_list(request.destination.cast(), offset, len)
  1025. })
  1026. }
  1027. /// The trace's line for a batch: how much of it goes to pages, and how many
  1028. /// of those lists the title filled in since it enqueued them (its protocol:
  1029. /// most of them; a batch started `early` runs on what they held before).
  1030. fn trace_batch(queue: u64, commands: &[Command], early: bool) {
  1031. if trace() == 0 {
  1032. return;
  1033. }
  1034. let reads = || {
  1035. commands.iter().filter_map(|c| match c {
  1036. Command::Read(read) => Some(read),
  1037. Command::Status(_) => None,
  1038. })
  1039. };
  1040. let (mut to_pages, mut filled, mut empty) = (0, 0, 0);
  1041. for read in reads().filter(|r| r.request.options & PAGE_DESTINATION != 0) {
  1042. to_pages += 1;
  1043. filled += usize::from(list_hash(&read.request) != read.note.at_enqueue);
  1044. empty += usize::from(list_of(&read.request).is_some_and(|l| l.contains(&0)));
  1045. }
  1046. tracing::info!(
  1047. queue,
  1048. early,
  1049. commands = commands.len(),
  1050. to_pages,
  1051. lists_filled_since_enqueued = filled,
  1052. lists_not_filled = empty,
  1053. oldest_ms = reads().next().and_then(|r| r.note.enqueued).map_or(0, |t| t.elapsed().as_millis() as u64),
  1054. "dstorage trace: a batch"
  1055. );
  1056. }
  1057. /// The bytes of pages that running requests write, for the trace: by page
  1058. /// number, the request and its bytes in the page.
  1059. type Writers = HashMap<usize, Vec<(u64, usize, usize)>>;
  1060. static WRITERS: Mutex<Option<Writers>> = Mutex::new(None);
  1061. /// A running request in the trace.
  1062. struct Traced {
  1063. pages: Vec<usize>,
  1064. at_start: u64,
  1065. shown: Vec<(usize, usize)>,
  1066. }
  1067. impl Traced {
  1068. fn start(job: &Job) -> Option<Traced> {
  1069. if trace() == 0 {
  1070. return None;
  1071. }
  1072. let at_start = list_hash(&job.request);
  1073. let pages = list_of(&job.request).unwrap_or_default();
  1074. let (offset, len) = Traced::bytes(&job.request);
  1075. {
  1076. let mut writers = WRITERS.lock().unwrap_or_else(|e| e.into_inner());
  1077. let writers = writers.get_or_insert_with(Writers::new);
  1078. for (i, &page) in pages.iter().enumerate().filter(|(_, p)| **p != 0) {
  1079. let from = offset.max(i * PAGE) - i * PAGE;
  1080. let to = (offset + len).min((i + 1) * PAGE) - i * PAGE;
  1081. let others = writers.entry(page).or_default();
  1082. for &(other, a, b) in others.iter().filter(|&&(_, a, b)| a < to && from < b) {
  1083. tracing::warn!(
  1084. page,
  1085. from,
  1086. to,
  1087. seq = job.seq,
  1088. other,
  1089. other_from = a,
  1090. other_to = b,
  1091. "dstorage trace: two running requests write the same bytes of a page"
  1092. );
  1093. }
  1094. others.push((job.seq, from, to));
  1095. }
  1096. }
  1097. let shown = super::xmem::pages_shown(&pages, offset, len);
  1098. Some(Traced { pages, at_start, shown })
  1099. }
  1100. /// Where in its first page a request's destination starts, and its size.
  1101. fn bytes(request: &Request) -> (usize, usize) {
  1102. ((request.page_offset & 0xffff) as usize, request.destination_size as usize)
  1103. }
  1104. fn end(self, job: &Job, result: &Result<(), HRESULT>) {
  1105. let (offset, len) = Traced::bytes(&job.request);
  1106. let at_end = list_hash(&job.request);
  1107. let moved = super::xmem::pages_shown(&self.pages, offset, len) != self.shown;
  1108. {
  1109. let mut writers = WRITERS.lock().unwrap_or_else(|e| e.into_inner());
  1110. let writers = writers.get_or_insert_with(Writers::new);
  1111. for page in &self.pages {
  1112. if let Some(others) = writers.get_mut(page) {
  1113. others.retain(|w| w.0 != job.seq);
  1114. if others.is_empty() {
  1115. writers.remove(page);
  1116. }
  1117. }
  1118. }
  1119. }
  1120. let note = &job.note;
  1121. // A request of the title's submit: its list is filled in by then,
  1122. // and stays.
  1123. let late = note.at_submit != self.at_start || self.at_start != at_end;
  1124. if trace() < 2 && !late && !moved && !note.early && result.is_ok() {
  1125. return;
  1126. }
  1127. let since = |t: Option<std::time::Instant>| t.map_or(0, |t| t.elapsed().as_millis() as u64);
  1128. tracing::info!(
  1129. seq = job.seq,
  1130. queue = job.lane,
  1131. early = note.early,
  1132. list = format_args!("{:p}", job.request.destination),
  1133. page_offset = job.request.page_offset,
  1134. size = len,
  1135. enqueued_ms_ago = since(note.enqueued),
  1136. submitted_ms_ago = since(note.submitted),
  1137. at_enqueue = format_args!("{:016x}", note.at_enqueue),
  1138. at_submit = format_args!("{:016x}", note.at_submit),
  1139. at_start = format_args!("{:016x}", self.at_start),
  1140. at_end = format_args!("{at_end:016x}"),
  1141. list_changed_late = late,
  1142. mapping_changed = moved,
  1143. first_page = self.pages.first().copied().unwrap_or(0),
  1144. ok = result.is_ok(),
  1145. "dstorage trace: a request"
  1146. );
  1147. }
  1148. }
  1149. /// A status entry to write, holding a reference on its array.
  1150. struct Status {
  1151. array: Array,
  1152. index: u32,
  1153. /// For the log.
  1154. enqueued: u64,
  1155. }
  1156. impl Drop for Status {
  1157. fn drop(&mut self) {
  1158. release(self.array);
  1159. }
  1160. }
  1161. impl Status {
  1162. fn entry(&self) -> &AtomicI32 {
  1163. // SAFETY: we hold a reference; the index was checked when enqueued.
  1164. &unsafe { &*self.array }.state.entries[self.index as usize]
  1165. }
  1166. fn written(&self) -> &AtomicU64 {
  1167. // SAFETY: as above.
  1168. &unsafe { &*self.array }.state.written[self.index as usize]
  1169. }
  1170. }
  1171. extern "system" fn enqueue_request(this: QueueRef, request: *const Request) {
  1172. // SAFETY: the title passes its request (null tolerated).
  1173. let Some(&request) = (unsafe { request.as_ref() }) else {
  1174. return;
  1175. };
  1176. let note = Note::enqueued(&request);
  1177. queue(this, Command::Read(Read { request, note }));
  1178. }
  1179. extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) {
  1180. // SAFETY: the title passes an array we created (null tolerated).
  1181. let Some(entries) = (unsafe { array.as_ref() }).map(|a| &a.state.entries) else {
  1182. return;
  1183. };
  1184. let Some(entry) = entries.get(index as usize) else {
  1185. tracing::warn!(index, "dstorage: status entry out of range");
  1186. return;
  1187. };
  1188. entry.store(E_PENDING, Ordering::Release);
  1189. add_ref_instance(array);
  1190. let enqueued = stream_log::now();
  1191. queue(this, Command::Status(Status { array, index, enqueued }));
  1192. }
  1193. /// Whether a queue submits itself once half of it is enqueued
  1194. /// (`VICTORY_DSTORAGE_HALF=1`), as DirectStorage for the PC does and as ours
  1195. /// did. The title's batches (up to 4,095 requests, in queues of 4,159) hold
  1196. /// more than half now and then, and it maps the pages they go to and fills
  1197. /// in their page lists in its own submit, after it has enqueued them all
  1198. /// (image +0xe88f0: the batch's mapping list first, at +0xf2c470, which
  1199. /// writes the page lists at +0x55aa6a0; then the status entry; then our
  1200. /// submit). So 2,079 requests, three or four times a load, ran on lists of
  1201. /// page 0, or, worse, of the pages the addresses had shown before: their
  1202. /// data went into whatever those pages belonged to by then, and the pages it
  1203. /// was for stayed as they were.
  1204. fn half_submits() -> bool {
  1205. static ON: OnceLock<bool> = OnceLock::new();
  1206. *ON.get_or_init(|| std::env::var_os("VICTORY_DSTORAGE_HALF").is_some_and(|v| v == "1"))
  1207. }
  1208. /// Adds a command to the queue; blocks while the queue is full. A queue
  1209. /// that is full of commands nobody submitted submits itself, since nothing
  1210. /// else could make room.
  1211. fn queue(this: QueueRef, command: Command) {
  1212. // SAFETY: a queue we created and the title still holds.
  1213. let id = unsafe { &*this }.state.id;
  1214. let Some(scheduler) = scheduler() else {
  1215. return;
  1216. };
  1217. let mut lanes = scheduler.lock();
  1218. loop {
  1219. let Some(lane) = lanes.lanes.get(&id).filter(|l| !l.closed) else {
  1220. return; // closed: dropped (a status releases its array)
  1221. };
  1222. // One slot stays free, as the console's count of empty slots says.
  1223. if lane.entries() + 1 < lane.capacity.max(2) {
  1224. break;
  1225. }
  1226. if !lane.unsubmitted.is_empty() && lane.reads.is_empty() && lane.running.is_empty() {
  1227. tracing::warn!(
  1228. queue = id,
  1229. commands = lane.unsubmitted.len(),
  1230. "dstorage: a queue full of commands that are not submitted submits itself"
  1231. );
  1232. lanes.submit(id, true);
  1233. scheduler.work.notify_all();
  1234. continue;
  1235. }
  1236. lanes = scheduler
  1237. .finished
  1238. .wait(lanes)
  1239. .unwrap_or_else(|e| e.into_inner());
  1240. }
  1241. let Some(lane) = lanes.lanes.get_mut(&id) else {
  1242. return;
  1243. };
  1244. lane.unsubmitted.push(command);
  1245. if half_submits() && lane.unsubmitted.len() >= (lane.capacity / 2).max(1) {
  1246. lanes.submit(id, true);
  1247. scheduler.work.notify_all();
  1248. }
  1249. }
  1250. /// The title's submit, where its page lists become valid ([`half_submits`]):
  1251. /// the pages are mapped just before, also those under addresses without a
  1252. /// list (memory only the CPU sees).
  1253. extern "system" fn submit(this: QueueRef) {
  1254. let _called = victory_gpu::timeline::span("the title's DirectStorage Submit");
  1255. // SAFETY: as above.
  1256. let id = unsafe { &*this }.state.id;
  1257. let Some(scheduler) = scheduler() else {
  1258. return;
  1259. };
  1260. let mut lanes = scheduler.lock();
  1261. let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len());
  1262. tracing::debug!(commands = pending, "dstorage: submit");
  1263. lanes.submit(id, false);
  1264. scheduler.work.notify_all();
  1265. }
  1266. /// Ends the queue whatever its reference count: what was not started never
  1267. /// completes, and this returns once the reads already running have
  1268. /// finished. The title calls this, not `Release`.
  1269. extern "system" fn close(this: QueueRef) {
  1270. // SAFETY: as above.
  1271. close_lane(unsafe { &*this }.state.id);
  1272. }
  1273. /// Reads, inflates and/or unpacks, and writes one request.
  1274. fn execute(request: &Request) -> Result<(), HRESULT> {
  1275. let options = request.options;
  1276. let fail = |hr: HRESULT, why: &str| {
  1277. tracing::warn!(
  1278. options = format_args!("{options:#x}"),
  1279. offset = request.offset,
  1280. source_size = request.source_size,
  1281. destination_size = request.destination_size,
  1282. intermediate_size = request.intermediate_size,
  1283. tag = request.tag,
  1284. name = text(request.name),
  1285. hr = format_args!("{:#010x}", hr as u32),
  1286. "dstorage: request failed: {why}"
  1287. );
  1288. hr
  1289. };
  1290. if options & !(ZLIB | BCPACK | PAGE_DESTINATION | MEMORY_SOURCE) != 0 {
  1291. return Err(fail(E_NOTIMPL, "unsupported options"));
  1292. }
  1293. if request.source.is_null() || request.destination.is_null() {
  1294. return Err(fail(E_INVALIDARG, "no source or destination"));
  1295. }
  1296. let bc = ((options & BCPACK) >> 1) as u8;
  1297. let size = request.destination_size as usize;
  1298. if options & (ZLIB | BCPACK) == 0 {
  1299. if request.source_size > request.destination_size {
  1300. return Err(fail(E_INVALIDARG, "source larger than destination"));
  1301. }
  1302. let size = request.source_size as usize;
  1303. return into_destination(request, size, |out| read_into(request, out).map(|()| size))
  1304. .map_err(|hr| fail(hr, "copying"));
  1305. }
  1306. let tables = if bc != 0 { Some(bcpack_tables()?) } else { None };
  1307. let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?;
  1308. // The console's order: zlib first, then BCPack.
  1309. let source = if bc != 0 && options & ZLIB != 0 {
  1310. let mut packed = vec![0; request.intermediate_size as usize];
  1311. let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?;
  1312. packed.truncate(n);
  1313. Cow::Owned(packed)
  1314. } else {
  1315. source
  1316. };
  1317. into_destination(request, size, |out| match tables {
  1318. Some(tables) => bcpack::decode(bc, &source, out, tables)
  1319. .map(|()| out.len())
  1320. .map_err(|e| fail(INVALID_DATA, &e.to_string())),
  1321. None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")),
  1322. })?;
  1323. tracing::trace!(
  1324. options = format_args!("{options:#x}"),
  1325. offset = request.offset,
  1326. size,
  1327. "dstorage: request done"
  1328. );
  1329. Ok(())
  1330. }
  1331. /// Inflates a zlib stream into `out`, returning the bytes written. A stream
  1332. /// that ends short of `out` passes: the title's chunks fill it exactly, and
  1333. /// nothing says that is required.
  1334. fn inflate(source: &[u8], out: &mut [u8]) -> Result<usize, HRESULT> {
  1335. thread_local! {
  1336. static INFLATE: std::cell::RefCell<zlib_rs::Inflate> =
  1337. std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15));
  1338. }
  1339. INFLATE.with_borrow_mut(|state| {
  1340. state.reset(true);
  1341. // `Inflate::decompress` cannot distinguish a valid empty stream from
  1342. // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch
  1343. // destination and verify `written <= out_len` afterward.
  1344. let out_len = out.len();
  1345. let mut scratch = [0u8; 1];
  1346. let dest = if out_len == 0 { &mut scratch[..] } else { out };
  1347. let (mut in_pos, mut out_pos) = (0usize, 0usize);
  1348. let status = loop {
  1349. match state.decompress(
  1350. &source[in_pos..],
  1351. &mut dest[out_pos..],
  1352. zlib_rs::InflateFlush::NoFlush,
  1353. ) {
  1354. Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd),
  1355. Ok(zlib_rs::Status::Ok) => {
  1356. let next_in = state.total_in() as usize;
  1357. let next_out = state.total_out() as usize;
  1358. if next_in == in_pos && next_out == out_pos {
  1359. break Ok(zlib_rs::Status::BufError);
  1360. }
  1361. in_pos = next_in;
  1362. out_pos = next_out;
  1363. }
  1364. other => break other,
  1365. }
  1366. };
  1367. let written = state.total_out() as usize;
  1368. match status {
  1369. Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written),
  1370. other => {
  1371. tracing::debug!(?other, "dstorage: zlib stream");
  1372. Err(INVALID_DATA)
  1373. }
  1374. }
  1375. })
  1376. }
  1377. /// The BCPack format's constant tables, parsed once for the process. If
  1378. /// they do not parse every BCPack request fails: one warning, then debug.
  1379. fn bcpack_tables() -> Result<&'static Tables, HRESULT> {
  1380. static TABLES: OnceLock<Result<Tables, String>> = OnceLock::new();
  1381. static WARNED: AtomicBool = AtomicBool::new(false);
  1382. match TABLES.get_or_init(load_bcpack_tables) {
  1383. Ok(tables) => Ok(tables),
  1384. Err(why) if !WARNED.swap(true, Ordering::Relaxed) => {
  1385. tracing::warn!("dstorage: BCPack requests fail: {why} (more at debug)");
  1386. Err(E_NOTIMPL)
  1387. }
  1388. Err(_) => {
  1389. tracing::debug!("dstorage: BCPack request failed: no tables");
  1390. Err(E_NOTIMPL)
  1391. }
  1392. }
  1393. }
  1394. /// The tables VIctory ships with.
  1395. #[cfg(not(test))]
  1396. fn load_bcpack_tables() -> Result<Tables, String> {
  1397. Tables::builtin().map_err(|e| format!("the built-in BCPack tables: {e}"))
  1398. }
  1399. /// Tests decode streams made against tables of their own, from this folder.
  1400. #[cfg(test)]
  1401. static BCPACK_DIR: OnceLock<std::path::PathBuf> = OnceLock::new();
  1402. #[cfg(test)]
  1403. fn use_bcpack_tables(dir: std::path::PathBuf) {
  1404. let _ = BCPACK_DIR.set(dir);
  1405. }
  1406. #[cfg(test)]
  1407. fn load_bcpack_tables() -> Result<Tables, String> {
  1408. let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?;
  1409. let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?;
  1410. Tables::parse(&bytes).map_err(|e| e.to_string())
  1411. }
  1412. /// A compressed request's source: borrowed from memory, or read from the
  1413. /// file.
  1414. fn read_source(request: &Request) -> Result<Cow<'static, [u8]>, HRESULT> {
  1415. let size = request.source_size as usize;
  1416. if request.options & MEMORY_SOURCE != 0 {
  1417. // SAFETY: the title's source holds `size` bytes until completion.
  1418. let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) };
  1419. return Ok(Cow::Borrowed(bytes));
  1420. }
  1421. let mut bytes = vec![0; size];
  1422. read_into(request, &mut bytes)?;
  1423. Ok(Cow::Owned(bytes))
  1424. }
  1425. /// Nanoseconds workers spent reading files, for the debug summary.
  1426. static READING: AtomicU64 = AtomicU64::new(0);
  1427. /// How often a read the host refuses is tried again (about 0.25 s in all).
  1428. const READ_RETRIES: u32 = 8;
  1429. /// Fills `out` (the source size) from the request's file or memory.
  1430. fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> {
  1431. if request.options & MEMORY_SOURCE != 0 {
  1432. // SAFETY: the title's source holds `out.len()` bytes until completion.
  1433. out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) });
  1434. return Ok(());
  1435. }
  1436. // SAFETY: a file object we created; the title keeps it open.
  1437. let files = &unsafe { &*request.source.cast::<Instance<File>>() }
  1438. .state
  1439. .files;
  1440. let started = std::time::Instant::now();
  1441. let (mut done, mut tries) = (0, 0);
  1442. let result = loop {
  1443. if done == out.len() {
  1444. break Ok(());
  1445. }
  1446. let error = match files.read_at(&mut out[done..], request.offset + done as u64) {
  1447. Ok(0) => break Err(END_OF_FILE),
  1448. Ok(n) => {
  1449. done += n;
  1450. continue;
  1451. }
  1452. Err(error) => error,
  1453. };
  1454. // Title memory the GPU side guards again in the moment between our
  1455. // opening it and the kernel's write fails the read (and a busy host
  1456. // can refuse one): opened again and tried again, since the title
  1457. // never learns of a failed read.
  1458. tracing::warn!(
  1459. %error,
  1460. offset = request.offset,
  1461. size = out.len(),
  1462. done,
  1463. tries,
  1464. "dstorage: a read of the file failed"
  1465. );
  1466. if tries == READ_RETRIES {
  1467. break Err(from_win32(&error));
  1468. }
  1469. std::thread::sleep(std::time::Duration::from_millis(1 << tries));
  1470. tries += 1;
  1471. victory_gpu::kernel_will_write(out.as_ptr() as usize + done, out.len() - done);
  1472. };
  1473. READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
  1474. result
  1475. }
  1476. /// Runs `fill` on the destination's first `len` bytes; `fill` returns how
  1477. /// many it produced. GPU-visible destinations are host memory like the
  1478. /// rest (GPU address = CPU address), so an address is written in place;
  1479. /// physical pages are too when they are consecutive pages of one
  1480. /// allocation, and otherwise go through a buffer.
  1481. fn into_destination(
  1482. request: &Request,
  1483. len: usize,
  1484. mut fill: impl FnMut(&mut [u8]) -> Result<usize, HRESULT>,
  1485. ) -> Result<(), HRESULT> {
  1486. if request.options & PAGE_DESTINATION == 0 {
  1487. // Raw reads land through the kernel, which does not fault into the
  1488. // GPU side's guard on title buffers; open them first, and until the
  1489. // bytes are there.
  1490. let writing = victory_gpu::kernel_writing(request.destination as usize, len);
  1491. // SAFETY: the title's destination holds `destination_size` bytes, at
  1492. // least `len`, and nothing else writes it until completion.
  1493. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) };
  1494. let filled = fill(out).map(drop);
  1495. drop(writing);
  1496. // Again now that the bytes are there: a texture looked at in between
  1497. // was uploaded without them (`xmem::pages_written`).
  1498. if super::xmem::stream_notice() {
  1499. victory_gpu::kernel_will_write(request.destination as usize, len);
  1500. } else {
  1501. victory_gpu::title_memory_written(request.destination as usize, len, false);
  1502. }
  1503. return filled;
  1504. }
  1505. let offset = (request.page_offset & 0xffff) as usize;
  1506. let list = request.destination.cast();
  1507. let mut pages = page_list(list, offset, len);
  1508. // The title sees its destination through the pages its list names: if
  1509. // it names others by the time the data is written, they get it as well.
  1510. // (Said aloud: by the title's protocol a submitted request's list stays
  1511. // as it is.)
  1512. for _ in 0..3 {
  1513. into_pages(&pages, offset, len, &mut fill)?;
  1514. let now = read_list(list, offset, len);
  1515. if now == pages || !super::xmem::pages_known(&now, offset, len) {
  1516. break;
  1517. }
  1518. tracing::warn!(
  1519. list = format_args!("{list:p}"),
  1520. offset,
  1521. len,
  1522. first = pages.first(),
  1523. first_now = now.first(),
  1524. "dstorage: a destination's page list changed during the write; written to its new pages too"
  1525. );
  1526. pages = now;
  1527. }
  1528. Ok(())
  1529. }
  1530. /// Runs `fill` on `len` bytes of `pages`, from `offset` into the first.
  1531. fn into_pages(
  1532. pages: &[usize],
  1533. offset: usize,
  1534. len: usize,
  1535. mut fill: impl FnMut(&mut [u8]) -> Result<usize, HRESULT>,
  1536. ) -> Result<(), HRESULT> {
  1537. // Consecutive pages of one allocation (the usual case): written in
  1538. // place through one view.
  1539. if let Some(mut window) = super::xmem::page_window(pages, offset, len) {
  1540. let filled = fill(window.bytes()).map(drop);
  1541. super::xmem::pages_written(pages, offset, len);
  1542. return filled;
  1543. }
  1544. let mut data = vec![0; len];
  1545. let n = fill(&mut data)?;
  1546. // A page the title has just made, or a view the host refuses for a moment (commit
  1547. // or address space short while a load maps many at once), can come right a little
  1548. // later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12,
  1549. // about 1.5 s in all).
  1550. static RETRIES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  1551. let retries = *RETRIES.get_or_init(|| {
  1552. std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12)
  1553. });
  1554. let mut written = super::xmem::write_physical(pages, offset, &data[..n]);
  1555. let mut tries = 0;
  1556. while !written && tries < retries {
  1557. std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128)));
  1558. tries += 1;
  1559. written = super::xmem::write_physical(pages, offset, &data[..n]);
  1560. }
  1561. if written {
  1562. super::xmem::pages_written(pages, offset, n);
  1563. if tries > 0 {
  1564. tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry");
  1565. }
  1566. Ok(())
  1567. } else {
  1568. let known = super::xmem::pages_known(pages, offset, len);
  1569. tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up");
  1570. // Said aloud: the title never reads a request's result
  1571. // (it only polls for completion), so a destination left unwritten
  1572. // is a model or texture that silently holds whatever its pages
  1573. // held before.
  1574. tracing::warn!(
  1575. offset,
  1576. len,
  1577. pages = pages.len(),
  1578. "dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails"
  1579. );
  1580. Err(E_INVALIDARG)
  1581. }
  1582. }
  1583. /// The page numbers `list` holds now, one per 64 KiB of destination.
  1584. fn read_list(list: *const usize, offset: usize, len: usize) -> Vec<usize> {
  1585. (0..(offset + len).div_ceil(PAGE))
  1586. // SAFETY: the title passes a page number per 64 KiB of
  1587. // destination, which holds at least `len` bytes from `offset`;
  1588. // it may be writing them.
  1589. .map(|i| unsafe { list.add(i).read_volatile() })
  1590. .collect()
  1591. }
  1592. /// The request's page numbers. A list is the part of the title's own page
  1593. /// table (one number per 64 KiB of its address range) that describes the
  1594. /// destination, filled in when the title submits the batch, so it is valid
  1595. /// here. It is only ever overwritten: an address the title unmapped keeps
  1596. /// the number of the page it had, which the title maps elsewhere soon after,
  1597. /// so a number the title owns says nothing about whether it is the right
  1598. /// one ([`half_submits`]). Page 0 does (an address never mapped yet): a list
  1599. /// with a page the title does not own is read again for a while, up to
  1600. /// 1.5 s; what it holds then is used as it is.
  1601. fn page_list(list: *const usize, offset: usize, len: usize) -> Vec<usize> {
  1602. let mut pages = read_list(list, offset, len);
  1603. if super::xmem::pages_known(&pages, offset, len) {
  1604. return pages;
  1605. }
  1606. // Timed from here: what took long before was the lock on the page table
  1607. // (which the title's mapping calls hold), not the list.
  1608. let started = std::time::Instant::now();
  1609. let mut known = false;
  1610. while !known && started.elapsed().as_millis() < 1500 {
  1611. std::thread::sleep(std::time::Duration::from_millis(1));
  1612. pages = read_list(list, offset, len);
  1613. known = super::xmem::pages_known(&pages, offset, len);
  1614. }
  1615. tracing::warn!(
  1616. ms = started.elapsed().as_millis() as u64,
  1617. known,
  1618. "dstorage: a destination's page list was not filled in yet"
  1619. );
  1620. pages
  1621. }
  1622. /// Slots by the 2020 order, which the argument shapes at
  1623. /// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called).
  1624. static QUEUE_VTABLE: Methods<12> = Methods([
  1625. missing::<0> as *const (),
  1626. add_ref_instance::<Queue> as *const (),
  1627. release::<Queue> as *const (),
  1628. enqueue_request as *const (), // 0x18
  1629. enqueue_status as *const (), // 0x20
  1630. missing::<5> as *const (), // 0x28 (2020: fence signal)
  1631. submit as *const (), // 0x30
  1632. missing::<7> as *const (), // 0x38 (2020: cancel by tag)
  1633. close as *const (), // 0x40
  1634. missing::<9> as *const (), // 0x48 (2020: error event)
  1635. missing::<10> as *const (), // 0x50 (2020: error record)
  1636. missing::<11> as *const (), // 0x58 (2020: queue info)
  1637. ]);
  1638. pub(crate) fn module() -> HleModule {
  1639. HleModule {
  1640. name: "dstorage",
  1641. dlls: &["xcrdapi.dll"],
  1642. exports: vec![hle_export!(DStorageGetFactory)],
  1643. }
  1644. }
  1645. #[cfg(test)]
  1646. mod tests {
  1647. use std::os::windows::ffi::OsStrExt;
  1648. use std::time::{Duration, Instant};
  1649. use super::*;
  1650. use crate::modules::xgameruntime::method;
  1651. fn call<F: Copy>(object: *mut c_void, slot: usize) -> F {
  1652. // SAFETY: every object here starts with the runtime header.
  1653. method(unsafe { &*object.cast::<Object>() }, slot)
  1654. }
  1655. fn factory() -> *mut c_void {
  1656. let mut factory = std::ptr::null_mut();
  1657. assert_eq!(DStorageGetFactory(&FACTORY, &mut factory), S_OK);
  1658. factory
  1659. }
  1660. fn open(path: &std::path::Path) -> *mut c_void {
  1661. let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
  1662. let open: extern "system" fn(*mut c_void, *const u16, *const Guid, Out) -> HRESULT =
  1663. call(factory(), 0x20);
  1664. let mut file = std::ptr::null_mut();
  1665. assert_eq!(
  1666. open(factory(), wide.as_ptr(), std::ptr::null(), &mut file),
  1667. S_OK
  1668. );
  1669. file
  1670. }
  1671. fn status_array(capacity: u32) -> *mut c_void {
  1672. let create: extern "system" fn(
  1673. *mut c_void,
  1674. u32,
  1675. *const c_char,
  1676. *const Guid,
  1677. Out,
  1678. ) -> HRESULT = call(factory(), 0x28);
  1679. let mut array = std::ptr::null_mut();
  1680. let name = c"test".as_ptr();
  1681. assert_eq!(
  1682. create(factory(), capacity, name, std::ptr::null(), &mut array),
  1683. S_OK
  1684. );
  1685. array
  1686. }
  1687. fn new_queue(source_type: u64) -> *mut c_void {
  1688. let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT =
  1689. call(factory(), 0x50);
  1690. let desc = QueueDesc {
  1691. source_type,
  1692. capacity: 0x80,
  1693. priority: 0,
  1694. name: c"test".as_ptr(),
  1695. unknown: 1,
  1696. };
  1697. let mut queue = std::ptr::null_mut();
  1698. assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK);
  1699. queue
  1700. }
  1701. fn request(
  1702. options: u64,
  1703. destination: *mut c_void,
  1704. destination_size: usize,
  1705. source: *const c_void,
  1706. offset: u64,
  1707. source_size: usize,
  1708. ) -> Request {
  1709. Request {
  1710. options,
  1711. destination,
  1712. page_offset: 0,
  1713. destination_size: destination_size as u32,
  1714. source,
  1715. offset,
  1716. source_size: source_size as u32,
  1717. intermediate_size: 0,
  1718. tag: 0,
  1719. name: std::ptr::null(),
  1720. }
  1721. }
  1722. fn enqueue(queue: *mut c_void, request: &Request) {
  1723. let f: extern "system" fn(*mut c_void, *const Request) = call(queue, 0x18);
  1724. f(queue, request);
  1725. }
  1726. fn enqueue_status(queue: *mut c_void, array: *mut c_void, index: u32) {
  1727. let f: extern "system" fn(*mut c_void, *mut c_void, u32) = call(queue, 0x20);
  1728. f(queue, array, index);
  1729. }
  1730. fn void(object: *mut c_void, slot: usize) {
  1731. let f: extern "system" fn(*mut c_void) = call(object, slot);
  1732. f(object);
  1733. }
  1734. fn result(array: *mut c_void, index: u32) -> HRESULT {
  1735. let f: extern "system" fn(*mut c_void, u32) -> HRESULT = call(array, 0x20);
  1736. f(array, index)
  1737. }
  1738. /// Polls as the title does, then returns the entry's result.
  1739. fn wait(array: *mut c_void, index: u32) -> HRESULT {
  1740. let done: extern "system" fn(*mut c_void, u32) -> bool = call(array, 0x18);
  1741. let start = Instant::now();
  1742. while !done(array, index) {
  1743. assert!(start.elapsed() < Duration::from_secs(10), "never completed");
  1744. std::thread::sleep(Duration::from_millis(1));
  1745. }
  1746. result(array, index)
  1747. }
  1748. fn file_with(bytes: &[u8]) -> (tempfile::TempDir, *mut c_void) {
  1749. let dir = tempfile::tempdir().unwrap();
  1750. let path = dir.path().join("data.bin");
  1751. std::fs::write(&path, bytes).unwrap();
  1752. let file = open(&path);
  1753. (dir, file)
  1754. }
  1755. fn pattern(n: usize) -> Vec<u8> {
  1756. (0..n).map(|i| (i * 7 + i / 251) as u8).collect()
  1757. }
  1758. #[test]
  1759. fn request_layout_is_the_titles() {
  1760. assert_eq!(size_of::<Request>(), 0x48);
  1761. assert_eq!(std::mem::offset_of!(Request, destination_size), 0x18);
  1762. assert_eq!(std::mem::offset_of!(Request, source), 0x20);
  1763. assert_eq!(std::mem::offset_of!(Request, source_size), 0x30);
  1764. assert_eq!(std::mem::offset_of!(Request, name), 0x40);
  1765. assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18);
  1766. }
  1767. fn compress_zlib(plain: &[u8]) -> Vec<u8> {
  1768. let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())];
  1769. let (packed, rc) =
  1770. zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6));
  1771. assert_eq!(rc, zlib_rs::ReturnCode::Ok);
  1772. packed.to_vec()
  1773. }
  1774. #[test]
  1775. fn raw_and_zlib_reads_from_a_file() {
  1776. let plain = pattern(300_000);
  1777. let packed = compress_zlib(&plain);
  1778. let mut contents = plain.clone();
  1779. contents.extend_from_slice(&packed);
  1780. let (_dir, file) = file_with(&contents);
  1781. let (queue, array) = (new_queue(0), status_array(1));
  1782. let mut raw = vec![0u8; 1000];
  1783. let mut inflated = vec![0u8; plain.len()];
  1784. let at = |b: &mut Vec<u8>| b.as_mut_ptr().cast();
  1785. enqueue(queue, &request(0, at(&mut raw), 1000, file, 5000, 1000));
  1786. let offset = plain.len() as u64;
  1787. let zlib = request(
  1788. ZLIB,
  1789. at(&mut inflated),
  1790. plain.len(),
  1791. file,
  1792. offset,
  1793. packed.len(),
  1794. );
  1795. enqueue(queue, &zlib);
  1796. enqueue_status(queue, array, 0);
  1797. assert_eq!(result(array, 0), E_PENDING, "pending until done");
  1798. void(queue, 0x30);
  1799. assert_eq!(wait(array, 0), S_OK);
  1800. assert_eq!(raw, plain[5000..6000]);
  1801. assert_eq!(inflated, plain);
  1802. void(queue, 0x40);
  1803. }
  1804. #[test]
  1805. fn memory_sources_inflate_too() {
  1806. let plain = pattern(70_000);
  1807. let packed = compress_zlib(&plain);
  1808. let (queue, array) = (new_queue(1), status_array(1));
  1809. let mut out = vec![0u8; plain.len()];
  1810. let options = ZLIB | MEMORY_SOURCE;
  1811. let r = request(
  1812. options,
  1813. out.as_mut_ptr().cast(),
  1814. out.len(),
  1815. packed.as_ptr().cast(),
  1816. 0,
  1817. packed.len(),
  1818. );
  1819. enqueue(queue, &r);
  1820. enqueue_status(queue, array, 0);
  1821. void(queue, 0x30);
  1822. assert_eq!(wait(array, 0), S_OK);
  1823. assert_eq!(out, plain);
  1824. }
  1825. #[test]
  1826. fn statuses_complete_in_order_with_the_first_failure() {
  1827. let contents = pattern(4096);
  1828. let (_dir, file) = file_with(&contents);
  1829. let (queue, array) = (new_queue(0), status_array(3));
  1830. // Requests in flight together run in any order, so none of them
  1831. // shares a destination (failed ones leave theirs undefined).
  1832. let mut buffers = [[0u8; 16]; 5];
  1833. let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast());
  1834. // Segment 0: a read past the end, then a bad stream; the first wins.
  1835. enqueue(queue, &request(0, failed, 16, file, 4090, 16));
  1836. enqueue(queue, &request(ZLIB, failed_too, 16, file, 0, 16));
  1837. enqueue_status(queue, array, 0);
  1838. // Segment 1: two reads.
  1839. enqueue(queue, &request(0, other, 16, file, 0, 16));
  1840. enqueue(queue, &request(0, out, 16, file, 100, 16));
  1841. enqueue_status(queue, array, 1);
  1842. void(queue, 0x30);
  1843. // Segment 2: a BCPack request (BC7) whose stream is empty fails.
  1844. with_test_tables();
  1845. enqueue(queue, &request(7 << 1, bcpack, 16, file, 0, 0));
  1846. enqueue_status(queue, array, 2);
  1847. void(queue, 0x30);
  1848. assert_eq!(wait(array, 2), INVALID_DATA);
  1849. assert_eq!(result(array, 0), END_OF_FILE);
  1850. assert_eq!(result(array, 1), S_OK);
  1851. assert_eq!(buffers[2], contents[100..116]);
  1852. assert_eq!(buffers[3], contents[..16]);
  1853. }
  1854. #[test]
  1855. fn half_a_queue_waits_for_the_submit() {
  1856. use crate::modules::xmem;
  1857. // Two pages the title owns: the one its list still names from
  1858. // earlier, and the one it maps for this batch when it submits.
  1859. let mut pages = [0usize; 2];
  1860. let mut n = 2;
  1861. assert_eq!(xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
  1862. let [stale, right] = pages;
  1863. let plain = pattern(64);
  1864. let mut list = [stale];
  1865. let (queue, array) = (new_queue(1), status_array(1));
  1866. // More than half of the queue's 128.
  1867. for i in 0..100 {
  1868. let mut r = request(
  1869. PAGE_DESTINATION | MEMORY_SOURCE,
  1870. list.as_mut_ptr().cast(),
  1871. plain.len(),
  1872. plain.as_ptr().cast(),
  1873. 0,
  1874. plain.len(),
  1875. );
  1876. r.page_offset = i * 64;
  1877. enqueue(queue, &r);
  1878. }
  1879. std::thread::sleep(Duration::from_millis(50));
  1880. // SAFETY: our own list, which a worker may be reading.
  1881. unsafe { std::ptr::write_volatile(list.as_mut_ptr(), right) };
  1882. enqueue_status(queue, array, 0);
  1883. void(queue, 0x30);
  1884. assert_eq!(wait(array, 0), S_OK);
  1885. let bytes = |page: usize| -> Vec<u8> {
  1886. xmem::page_window(&[page], 0, 6400).unwrap().bytes().to_vec()
  1887. };
  1888. assert!(bytes(stale) == [0; 6400], "written to the page the list named before");
  1889. assert!(bytes(right) == plain.repeat(100), "not written to the page the list names");
  1890. }
  1891. #[test]
  1892. fn a_full_queue_submits_itself() {
  1893. let (_dir, file) = file_with(&pattern(64));
  1894. let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT =
  1895. call(factory(), 0x50);
  1896. let desc = QueueDesc {
  1897. source_type: 0,
  1898. capacity: 4,
  1899. priority: 1,
  1900. name: c"small".as_ptr(),
  1901. unknown: 1,
  1902. };
  1903. let mut queue = std::ptr::null_mut();
  1904. assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK);
  1905. let array = status_array(1);
  1906. let mut outs = [[0u8; 16]; 4];
  1907. for out in &mut outs[..2] {
  1908. enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16));
  1909. }
  1910. enqueue_status(queue, array, 0);
  1911. std::thread::sleep(Duration::from_millis(20));
  1912. assert_eq!(result(array, 0), E_PENDING, "three of four: not submitted");
  1913. // One more than fits: would wait for good.
  1914. for out in &mut outs[2..] {
  1915. enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16));
  1916. }
  1917. assert_eq!(wait(array, 0), S_OK);
  1918. void(queue, 0x40);
  1919. assert!(outs[..2].iter().all(|out| out[..] == pattern(64)[8..24]));
  1920. }
  1921. #[test]
  1922. fn a_list_that_changes_during_the_write_has_its_new_pages_written() {
  1923. use crate::modules::xmem;
  1924. let mut pages = [0usize; 4];
  1925. let mut n = 4;
  1926. assert_eq!(xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()), 1);
  1927. // In place (consecutive pages) and through a buffer.
  1928. for old in [[pages[0], pages[1]], [pages[1], pages[0]]] {
  1929. let new = [pages[3], pages[2]];
  1930. let mut list = old;
  1931. let at = list.as_mut_ptr();
  1932. let len = PAGE + 100;
  1933. let r = request(PAGE_DESTINATION, at.cast(), len, std::ptr::null(), 0, len);
  1934. let mut runs = 0;
  1935. let written = into_destination(&r, len, |out| {
  1936. runs += 1;
  1937. out.fill(0xa5);
  1938. // SAFETY: our own list.
  1939. unsafe { at.cast::<[usize; 2]>().write_volatile(new) };
  1940. Ok(out.len())
  1941. });
  1942. assert_eq!((written, runs), (Ok(()), 2));
  1943. assert!(xmem::page_window(&new[..1], 0, PAGE).unwrap().bytes().iter().all(|&b| b == 0xa5));
  1944. assert!(xmem::page_window(&new[1..], 0, 100).unwrap().bytes().iter().all(|&b| b == 0xa5));
  1945. for page in new {
  1946. xmem::page_window(&[page], 0, PAGE).unwrap().bytes().fill(0);
  1947. }
  1948. }
  1949. }
  1950. #[test]
  1951. fn a_read_into_memory_guarded_for_a_moment_is_tried_again() {
  1952. use windows_sys::Win32::System::Memory::{
  1953. MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE, PAGE_READONLY, VirtualAlloc, VirtualProtect,
  1954. };
  1955. let plain = pattern(3 * 4096);
  1956. let (_dir, file) = file_with(&plain);
  1957. // SAFETY: a fresh allocation; its middle page is read-only until the
  1958. // thread opens it, as a guard of the GPU side's would be.
  1959. let at = unsafe {
  1960. VirtualAlloc(std::ptr::null(), plain.len(), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)
  1961. } as usize;
  1962. assert_ne!(at, 0);
  1963. let protect = move |to| {
  1964. let mut old = 0;
  1965. // SAFETY: as above.
  1966. unsafe { VirtualProtect((at + 4096) as *const _, 4096, to, &mut old) }
  1967. };
  1968. assert_ne!(protect(PAGE_READONLY), 0);
  1969. let opener = std::thread::spawn(move || {
  1970. std::thread::sleep(Duration::from_millis(20));
  1971. protect(PAGE_READWRITE)
  1972. });
  1973. let r = request(0, at as *mut c_void, plain.len(), file, 0, plain.len());
  1974. assert_eq!(execute(&r), Ok(()));
  1975. assert_ne!(opener.join().unwrap(), 0);
  1976. // SAFETY: as above, all of it readable.
  1977. assert_eq!(unsafe { std::slice::from_raw_parts(at as *const u8, plain.len()) }, plain);
  1978. }
  1979. /// What ways of reading a file give, at `VICTORY_BENCH_FILE` (a file of
  1980. /// the title's, only read): 24 threads, requests of 48 KiB at random,
  1981. /// first from places nobody read lately, then the same once more.
  1982. /// `VICTORY_BENCH_FILE=... cargo test --release -p victory-hle --lib
  1983. /// read_bench -- --ignored --nocapture`
  1984. #[test]
  1985. #[ignore = "a benchmark"]
  1986. fn read_bench() {
  1987. const THREADS: usize = 24;
  1988. const SIZE: usize = 48 << 10;
  1989. const READS: usize = 12_000;
  1990. let path = std::env::var("VICTORY_BENCH_FILE").expect("VICTORY_BENCH_FILE");
  1991. let len = std::fs::metadata(&path).unwrap().len();
  1992. let mut seed = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos() as u64 | 1;
  1993. let mut random = move || {
  1994. seed ^= seed << 13;
  1995. seed ^= seed >> 7;
  1996. seed ^= seed << 17;
  1997. seed
  1998. };
  1999. for round in 0..2 {
  2000. for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] {
  2001. let file = Files::open_for_test(&path, mode);
  2002. let at: Vec<u64> = (0..READS).map(|_| random() % (len - SIZE as u64) & !15).collect();
  2003. for pass in ["cold", "again"] {
  2004. let next = std::sync::atomic::AtomicUsize::new(0);
  2005. let busy = AtomicU64::new(0);
  2006. let start = Instant::now();
  2007. std::thread::scope(|s| {
  2008. for _ in 0..THREADS {
  2009. s.spawn(|| {
  2010. let mut out = vec![0u8; SIZE];
  2011. while let Some(&at) = at.get(next.fetch_add(1, Ordering::Relaxed)) {
  2012. let began = Instant::now();
  2013. let mut done = 0;
  2014. while done < SIZE {
  2015. done += file.read_at(&mut out[done..], at + done as u64).unwrap();
  2016. }
  2017. busy.fetch_add(began.elapsed().as_micros() as u64, Ordering::Relaxed);
  2018. }
  2019. });
  2020. }
  2021. });
  2022. let took = start.elapsed().as_secs_f64();
  2023. println!(
  2024. "{round} {mode:?} {pass}: {:.0} MB/s, {:.2} ms a read",
  2025. (READS * SIZE) as f64 / took / 1e6,
  2026. busy.load(Ordering::Relaxed) as f64 / READS as f64 / 1e3
  2027. );
  2028. }
  2029. }
  2030. }
  2031. }
  2032. /// Every way of reading a file gives its bytes, also past its end.
  2033. #[test]
  2034. fn every_way_of_reading_gives_the_same_bytes() {
  2035. let plain = pattern(300_001);
  2036. let dir = tempfile::tempdir().unwrap();
  2037. let path = dir.path().join("data.bin");
  2038. std::fs::write(&path, &plain).unwrap();
  2039. for mode in [Io::One, Io::Handles, Io::Overlapped, Io::Direct] {
  2040. let file = Files::open_for_test(path.to_str().unwrap(), mode);
  2041. for (at, len) in [(0, 4096), (1, 100), (4095, 2), (8192, 200_000), (12_345, 250_000), (299_990, 11), (300_000, 1)] {
  2042. let mut out = vec![0u8; len];
  2043. let mut done = 0;
  2044. while done < len {
  2045. let n = file.read_at(&mut out[done..], (at + done) as u64).unwrap();
  2046. assert_ne!(n, 0, "{mode:?} {at} {len}");
  2047. done += n;
  2048. }
  2049. assert!(out == plain[at..at + len], "{mode:?} {at} {len}");
  2050. }
  2051. let mut out = [0u8; 16];
  2052. assert_eq!(file.read_at(&mut out, 299_999).unwrap(), 2, "{mode:?}");
  2053. assert_eq!(file.read_at(&mut out, 300_001).unwrap(), 0, "{mode:?}");
  2054. assert_eq!(file.read_at(&mut out, 400_000).unwrap(), 0, "{mode:?}");
  2055. }
  2056. }
  2057. /// Lanes without workers: what `start` picks, and when statuses land.
  2058. fn lanes(staging: u64) -> Lanes {
  2059. Lanes {
  2060. lanes: HashMap::new(),
  2061. next_id: 0,
  2062. next_seq: 0,
  2063. staged: 0,
  2064. staging,
  2065. starved: false,
  2066. clock: [0; 3],
  2067. now: 0,
  2068. lane_now: [0; 3],
  2069. done: Default::default(),
  2070. refused: 0,
  2071. bcpack: Default::default(),
  2072. since: None,
  2073. }
  2074. }
  2075. fn read(lanes: &mut Lanes, id: u64, options: u64, size: u32) {
  2076. let mut r = request(options, std::ptr::null_mut(), 0, std::ptr::null(), 0, 0);
  2077. (r.destination_size, r.source_size) = (size, size);
  2078. let lane = lanes.lanes.get_mut(&id).unwrap();
  2079. let note = Note::default();
  2080. lane.unsubmitted.push(Command::Read(Read { request: r, note }));
  2081. }
  2082. #[test]
  2083. fn priorities_share_by_bytes_about_tenfold() {
  2084. let mut l = lanes(STAGING);
  2085. l.lanes.insert(0, Lane::new(0, 4096));
  2086. l.lanes.insert(1, Lane::new(1, 4096));
  2087. l.lanes.insert(2, Lane::new(2, 4096)); // real-time: as high
  2088. for _ in 0..400 {
  2089. for id in 0..3 {
  2090. read(&mut l, id, 0, 4096);
  2091. }
  2092. }
  2093. (0..3).for_each(|id| l.submit(id, false));
  2094. let mut started = [0u32; 3];
  2095. for _ in 0..330 {
  2096. let job = l.start().unwrap();
  2097. started[job.lane as usize] += 1;
  2098. l.finish(&job, Ok(()));
  2099. }
  2100. // Normal gets about a tenth of what high and real-time get together.
  2101. assert_eq!(started[1] + started[2], 300, "{started:?}");
  2102. assert_eq!(started[0], 30, "{started:?}");
  2103. assert!(started[1].abs_diff(started[2]) <= 1, "{started:?}");
  2104. }
  2105. #[test]
  2106. fn staging_bounds_compressed_bytes_in_flight() {
  2107. let mut l = lanes(100);
  2108. l.lanes.insert(0, Lane::new(0, 64));
  2109. read(&mut l, 0, ZLIB, 60);
  2110. read(&mut l, 0, ZLIB, 60);
  2111. read(&mut l, 0, 0, 1000); // raw: straight to its destination
  2112. l.submit(0, false);
  2113. let first = l.start().unwrap();
  2114. assert!(l.start().is_none(), "60 + 60 > 100");
  2115. l.finish(&first, Ok(()));
  2116. let second = l.start().unwrap();
  2117. let raw = l.start().unwrap();
  2118. assert_eq!((second.staging, raw.staging), (60, 0));
  2119. // Alone, a request larger than the buffer still runs.
  2120. read(&mut l, 0, ZLIB, 500);
  2121. l.submit(0, false);
  2122. assert!(l.start().is_none());
  2123. l.finish(&second, Ok(()));
  2124. assert!(l.start().is_some());
  2125. }
  2126. #[test]
  2127. fn a_status_waits_for_every_earlier_read() {
  2128. let mut l = lanes(STAGING);
  2129. l.lanes.insert(0, Lane::new(0, 64));
  2130. let array = status_array(2).cast::<Instance<StatusArray>>();
  2131. let status = |index| {
  2132. add_ref_instance(array);
  2133. Command::Status(Status { array, index, enqueued: 0 })
  2134. };
  2135. read(&mut l, 0, 0, 16);
  2136. read(&mut l, 0, 0, 16);
  2137. l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(0));
  2138. read(&mut l, 0, 0, 16);
  2139. l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(1));
  2140. // SAFETY: an array we created.
  2141. for entry in unsafe { &(*array).state.entries }.iter() {
  2142. entry.store(E_PENDING, Ordering::Release);
  2143. }
  2144. l.submit(0, false);
  2145. let jobs: Vec<Job> = (0..3).map(|_| l.start().unwrap()).collect();
  2146. // The last read and the first finish; the second then fails.
  2147. l.finish(&jobs[2], Ok(()));
  2148. l.finish(&jobs[0], Ok(()));
  2149. let results = || (result(array.cast(), 0), result(array.cast(), 1));
  2150. assert_eq!(results(), (E_PENDING, E_PENDING));
  2151. l.finish(&jobs[1], Err(INVALID_DATA));
  2152. assert_eq!(results(), (INVALID_DATA, S_OK));
  2153. }
  2154. #[test]
  2155. fn zlib_then_bcpack() {
  2156. with_test_tables();
  2157. let packed = compress_zlib(&BC4_STREAM);
  2158. let (_dir, file) = file_with(&packed);
  2159. let (queue, array) = (new_queue(0), status_array(1));
  2160. let mut out = [0u8; 16];
  2161. let options = ZLIB | 4 << 1;
  2162. let mut r = request(options, out.as_mut_ptr().cast(), 16, file, 0, packed.len());
  2163. r.intermediate_size = BC4_STREAM.len() as u32;
  2164. enqueue(queue, &r);
  2165. enqueue_status(queue, array, 0);
  2166. void(queue, 0x30);
  2167. assert_eq!(wait(array, 0), S_OK);
  2168. assert_eq!(out, bc4_blocks());
  2169. }
  2170. /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits,
  2171. /// next 3 bits), in a folder kept for the test process.
  2172. fn with_test_tables() {
  2173. static DIR: OnceLock<()> = OnceLock::new();
  2174. DIR.get_or_init(|| {
  2175. let mut t = Vec::new();
  2176. for m in 0..128 {
  2177. let g = m / 16;
  2178. for b in 0..9 {
  2179. let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 };
  2180. t.extend_from_slice(&f.to_le_bytes());
  2181. }
  2182. }
  2183. t.extend([0; 256 + 64 + 256]);
  2184. t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4));
  2185. t.resize(bcpack::TABLES_SIZE, 0);
  2186. let dir = tempfile::tempdir().unwrap().keep();
  2187. std::fs::write(dir.join("tables.bin"), t).unwrap();
  2188. use_bcpack_tables(dir);
  2189. });
  2190. }
  2191. /// Two BC4 blocks from the format's test encoder: endpoints 10, -3 with
  2192. /// indices p -> p & 7, then the same block plus 1 everywhere.
  2193. const BC4_STREAM: [u8; 88] = [
  2194. 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 4, 4, 4, 4, 1, 1, 1, 1, 0x10, 0x10, 0x10, 0x10, 2, 1,
  2195. 0, 0, 0, 0, 0, 0, 0, 0, 0x14, 5, 0x20, 0x68, 0xb0, 0xf8, 3, 3, 2, 2, 0x24, 0x24, 0x24,
  2196. 0x24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 0x10, 0x10, 0x10, 0x10, 0, 0, 0, 0,
  2197. 0x20, 0x68, 0xb0, 0xf8, 0x24, 0x24, 0x24, 0x24, 0, 0, 0, 0, 0, 0, 0, 0,
  2198. ];
  2199. /// What `BC4_STREAM` unpacks to.
  2200. fn bc4_blocks() -> [u8; 16] {
  2201. let code = [0u64, 2, 3, 4, 5, 6, 7, 1];
  2202. let block = |e0: u64, e1: u64, add: usize| {
  2203. let bits = (0..16).fold(0, |a, p| a | code[(p + add) & 7] << (16 + 3 * p));
  2204. (e0 | e1 << 8 | bits).to_le_bytes()
  2205. };
  2206. let mut out = [0; 16];
  2207. out[..8].copy_from_slice(&block(138, 125, 0));
  2208. out[8..].copy_from_slice(&block(139, 126, 1));
  2209. out
  2210. }
  2211. #[test]
  2212. fn bcpack_requests_unpack_into_the_destination() {
  2213. with_test_tables();
  2214. let mut contents = pattern(100);
  2215. contents.extend_from_slice(&BC4_STREAM);
  2216. let (_dir, file) = file_with(&contents);
  2217. let (queue, array) = (new_queue(0), status_array(1));
  2218. let mut out = [0u8; 16];
  2219. enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88));
  2220. enqueue_status(queue, array, 0);
  2221. void(queue, 0x30);
  2222. assert_eq!(wait(array, 0), S_OK);
  2223. assert_eq!(out, bc4_blocks());
  2224. }
  2225. #[test]
  2226. fn a_closed_queue_completes_nothing() {
  2227. let (_dir, file) = file_with(&pattern(64));
  2228. let (queue, array) = (new_queue(0), status_array(1));
  2229. let mut out = [0u8; 16];
  2230. enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 0, 16));
  2231. enqueue_status(queue, array, 0);
  2232. void(queue, 0x40);
  2233. void(queue, 0x30);
  2234. std::thread::sleep(Duration::from_millis(50));
  2235. assert_eq!(result(array, 0), E_PENDING);
  2236. assert_eq!(out, [0; 16]);
  2237. }
  2238. #[test]
  2239. fn physical_page_destinations() {
  2240. use crate::modules::xmem;
  2241. let mut pages = [0usize; 2];
  2242. let mut n = 2;
  2243. assert_eq!(
  2244. xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()),
  2245. 1
  2246. );
  2247. // Where the title would see them: a reservation of 64 KiB pages.
  2248. let mapped = xmem::XMemVirtualAlloc(
  2249. std::ptr::null_mut(),
  2250. 2 * PAGE,
  2251. 0x2000 | 0x2040_0000, // reserve, 64 KiB pages
  2252. 0,
  2253. 0x04,
  2254. );
  2255. assert!(!mapped.is_null());
  2256. assert_eq!(
  2257. xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()),
  2258. mapped
  2259. );
  2260. let plain = pattern(100);
  2261. let (queue, array) = (new_queue(1), status_array(1));
  2262. let mut r = request(
  2263. PAGE_DESTINATION | MEMORY_SOURCE,
  2264. pages.as_mut_ptr().cast(),
  2265. plain.len(),
  2266. plain.as_ptr().cast(),
  2267. 0,
  2268. plain.len(),
  2269. );
  2270. r.page_offset = (PAGE - 40) as u64; // across the page boundary
  2271. enqueue(queue, &r);
  2272. enqueue_status(queue, array, 0);
  2273. void(queue, 0x30);
  2274. assert_eq!(wait(array, 0), S_OK);
  2275. // SAFETY: both pages are mapped read-write.
  2276. let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>().add(PAGE - 40), 100) };
  2277. assert_eq!(seen, plain);
  2278. }
  2279. #[test]
  2280. fn zlib_into_pages_in_place_and_across_allocations() {
  2281. use crate::modules::xmem;
  2282. let allocate = |n: usize| {
  2283. let (mut pages, mut given) = (vec![0usize; n], n);
  2284. assert_eq!(
  2285. xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()),
  2286. 1
  2287. );
  2288. pages
  2289. };
  2290. let (a, b) = (allocate(3), allocate(1));
  2291. let plain = pattern(2 * PAGE + 100);
  2292. let packed = compress_zlib(&plain);
  2293. // One allocation's pages in order (one window), then pages of two
  2294. // (through a buffer), both from 50 bytes into the first.
  2295. let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]];
  2296. let (queue, array) = (new_queue(1), status_array(1));
  2297. for pages in &mut destinations {
  2298. let mut r = request(
  2299. ZLIB | PAGE_DESTINATION | MEMORY_SOURCE,
  2300. pages.as_mut_ptr().cast(),
  2301. plain.len(),
  2302. packed.as_ptr().cast(),
  2303. 0,
  2304. packed.len(),
  2305. );
  2306. r.page_offset = 50;
  2307. enqueue(queue, &r);
  2308. }
  2309. enqueue_status(queue, array, 0);
  2310. void(queue, 0x30);
  2311. assert_eq!(wait(array, 0), S_OK);
  2312. for pages in &destinations {
  2313. let mapped = xmem::XMemVirtualAlloc(
  2314. std::ptr::null_mut(),
  2315. 3 * PAGE,
  2316. 0x2000 | 0x2040_0000, // reserve, 64 KiB pages
  2317. 0,
  2318. 0x04,
  2319. );
  2320. assert!(!mapped.is_null());
  2321. assert_eq!(
  2322. xmem::XMemMapPhysicalPages(mapped, 3, pages.as_ptr()),
  2323. mapped
  2324. );
  2325. // SAFETY: all three pages are mapped read-write.
  2326. let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>(), 3 * PAGE) };
  2327. assert!(seen[..50].iter().all(|&b| b == 0));
  2328. assert_eq!(seen[50..50 + plain.len()], plain);
  2329. assert_eq!(
  2330. xmem::XMemMapPhysicalPages(mapped, 3, std::ptr::null()),
  2331. mapped
  2332. );
  2333. }
  2334. assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1);
  2335. assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1);
  2336. }
  2337. #[test]
  2338. fn zlib_inflate_handles_short_exact_empty_and_bad_streams() {
  2339. let plain = pattern(65_537);
  2340. let packed = compress_zlib(&plain);
  2341. // Exact fit.
  2342. let mut exact = vec![0u8; plain.len()];
  2343. assert_eq!(inflate(&packed, &mut exact), Ok(plain.len()));
  2344. assert_eq!(exact, plain);
  2345. // Short stream into a larger buffer passes and returns bytes written;
  2346. // guard bytes outside the slice passed to `inflate` stay untouched.
  2347. let mut larger = vec![0xAA; plain.len() + 64];
  2348. assert_eq!(
  2349. inflate(&packed, &mut larger[..plain.len() + 32]),
  2350. Ok(plain.len())
  2351. );
  2352. assert_eq!(&larger[..plain.len()], &plain[..]);
  2353. assert!(larger[plain.len() + 32..].iter().all(|&b| b == 0xAA));
  2354. // Empty valid stream passes for empty or non-empty destinations.
  2355. let empty = compress_zlib(&[]);
  2356. assert_eq!(inflate(&empty, &mut []), Ok(0));
  2357. let mut scratch = [0x55u8; 4];
  2358. assert_eq!(inflate(&empty, &mut scratch), Ok(0));
  2359. // Oversized stream (destination too small, including empty) fails.
  2360. let mut small = vec![0u8; plain.len() - 1];
  2361. assert_eq!(inflate(&packed, &mut small), Err(INVALID_DATA));
  2362. assert_eq!(inflate(&packed, &mut []), Err(INVALID_DATA));
  2363. // Truncated stream (missing trailer or payload bytes) fails.
  2364. let mut out = vec![0u8; plain.len()];
  2365. assert_eq!(
  2366. inflate(&packed[..packed.len() - 1], &mut out),
  2367. Err(INVALID_DATA)
  2368. );
  2369. assert_eq!(
  2370. inflate(&packed[..packed.len() / 2], &mut out),
  2371. Err(INVALID_DATA)
  2372. );
  2373. assert_eq!(inflate(&[], &mut out), Err(INVALID_DATA));
  2374. // Corrupt Adler-32 trailer fails.
  2375. let mut bad_adler = packed.clone();
  2376. *bad_adler.last_mut().unwrap() ^= 1;
  2377. assert_eq!(inflate(&bad_adler, &mut out), Err(INVALID_DATA));
  2378. // Corrupt header/payload fails, and subsequent valid inflate on the
  2379. // same thread still succeeds (verifies thread-local state reset).
  2380. let mut bad_body = packed.clone();
  2381. bad_body[2] ^= 0xFF;
  2382. assert_eq!(inflate(&bad_body, &mut out), Err(INVALID_DATA));
  2383. assert_eq!(inflate(&packed, &mut out), Ok(plain.len()));
  2384. assert_eq!(out, plain);
  2385. }
  2386. }