dstorage.rs 79 KB

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