dstorage.rs 94 KB

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