dstorage.rs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710
  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. //! Submitted requests of every queue run on one pool of workers, as the
  8. //! console's hardware runs them: in parallel, started in queue order,
  9. //! queues served by weighted round robin over their priorities (about 10x
  10. //! per level, counted in bytes), with at most the staging buffer's worth of
  11. //! compressed source in flight. Each request reads its source (a file or
  12. //! memory), inflates zlib data and/or unpacks BCPack data, and writes the
  13. //! destination (an address, or physical pages). Completion is what stays
  14. //! in order: a status entry is written once every request enqueued before
  15. //! it on its queue has finished, with the first failure (in queue order)
  16. //! since the previous status entry, or success.
  17. #![allow(non_snake_case)]
  18. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  19. use std::borrow::Cow;
  20. use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
  21. use std::ffi::{CStr, c_char, c_void};
  22. use std::os::windows::fs::FileExt;
  23. use std::os::windows::io::FromRawHandle;
  24. use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering};
  25. use std::sync::{Condvar, Mutex, MutexGuard, OnceLock};
  26. use victory_formats::bcpack::{self, Tables};
  27. use super::xasync::{E_INVALIDARG, E_NOTIMPL, E_PENDING};
  28. use super::xgameruntime::{Guid, HRESULT, Methods, Object, S_OK, add_ref, missing, put};
  29. use crate::{HleModule, hle_export};
  30. /// The factory interface the title asks for.
  31. const FACTORY: Guid = Guid::new(
  32. 0x6295_9d11,
  33. 0xd45f,
  34. 0x4884,
  35. [0xa0, 0xa3, 0xf7, 0x86, 0x2e, 0xa2, 0x43, 0xae],
  36. );
  37. const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
  38. const E_OUTOFMEMORY: HRESULT = 0x8007_000E_u32 as i32;
  39. /// `HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)`: the source ends early.
  40. const END_OF_FILE: HRESULT = 0x8007_0026_u32 as i32;
  41. /// `HRESULT_FROM_WIN32(ERROR_INVALID_DATA)`: a bad compressed stream.
  42. const INVALID_DATA: HRESULT = 0x8007_000D_u32 as i32;
  43. type Out = *mut *mut c_void;
  44. static FACTORY_OBJECT: Object = Object::new("dstorage factory", &FACTORY_VTABLE);
  45. pub extern "system" fn DStorageGetFactory(iid: *const Guid, out: Out) -> HRESULT {
  46. // SAFETY: the title passes a GUID (null tolerated).
  47. match unsafe { iid.as_ref() } {
  48. Some(&iid) if iid == FACTORY => {
  49. put(out, std::ptr::from_ref(&FACTORY_OBJECT).cast_mut().cast())
  50. }
  51. iid => {
  52. tracing::warn!(iid = ?iid.map(Guid::to_string), "DStorageGetFactory: unknown interface");
  53. E_NOINTERFACE
  54. }
  55. }
  56. }
  57. /// One of our objects with state: the runtime's object header (method
  58. /// table first), a reference count, then `T`.
  59. #[repr(C)]
  60. struct Instance<T> {
  61. base: Object,
  62. refs: AtomicU32,
  63. state: T,
  64. }
  65. impl<T> Instance<T> {
  66. fn create(base: Object, state: T) -> *mut c_void {
  67. Box::into_raw(Box::new(Instance {
  68. base,
  69. refs: AtomicU32::new(1),
  70. state,
  71. }))
  72. .cast()
  73. }
  74. }
  75. extern "system" fn add_ref_instance<T>(this: *const Instance<T>) -> u32 {
  76. // SAFETY: an instance we created and the title still holds.
  77. unsafe { &*this }.refs.fetch_add(1, Ordering::Relaxed) + 1
  78. }
  79. extern "system" fn release<T>(this: *mut Instance<T>) -> u32 {
  80. // SAFETY: as above.
  81. let left = unsafe { &*this }.refs.fetch_sub(1, Ordering::AcqRel) - 1;
  82. if left == 0 {
  83. // SAFETY: the last reference; created by `Instance::create`.
  84. drop(unsafe { Box::from_raw(this) });
  85. }
  86. left
  87. }
  88. fn iid_text(iid: *const Guid) -> String {
  89. // SAFETY: the title passes a GUID (null tolerated).
  90. unsafe { iid.as_ref() }.map_or_else(|| "null".into(), Guid::to_string)
  91. }
  92. /// `HRESULT_FROM_WIN32` of a host error.
  93. fn from_win32(error: &std::io::Error) -> HRESULT {
  94. error
  95. .raw_os_error()
  96. .map_or(E_INVALIDARG, |e| (0x8007_0000 | (e as u32 & 0xffff)) as i32)
  97. }
  98. // The factory.
  99. type Factory = *const Object;
  100. /// Opens `path` for reading; the file object owns the handle.
  101. extern "system" fn open_file(_: Factory, path: *const u16, iid: *const Guid, out: Out) -> HRESULT {
  102. const GENERIC_READ: u32 = 0x8000_0000;
  103. const FILE_SHARE_READ: u32 = 1;
  104. const OPEN_EXISTING: u32 = 3;
  105. if path.is_null() {
  106. return E_INVALIDARG;
  107. }
  108. // Goes through `files`, so paths on our virtual drives work too.
  109. let handle = super::files::CreateFileW(
  110. path,
  111. GENERIC_READ,
  112. FILE_SHARE_READ,
  113. std::ptr::null(),
  114. OPEN_EXISTING,
  115. 0,
  116. std::ptr::null_mut(),
  117. );
  118. // SAFETY: the title passes a NUL-terminated path.
  119. let name = unsafe {
  120. let len = (0..).take_while(|&i| *path.add(i) != 0).count();
  121. String::from_utf16_lossy(std::slice::from_raw_parts(path, len))
  122. };
  123. if handle as isize == -1 {
  124. let error = std::io::Error::last_os_error();
  125. tracing::warn!(path = name, %error, "dstorage: opening a file failed");
  126. return from_win32(&error);
  127. }
  128. tracing::info!(path = name, iid = iid_text(iid), "dstorage: file opened");
  129. // SAFETY: a handle we just opened and nobody else owns.
  130. let file = unsafe { std::fs::File::from_raw_handle(handle) };
  131. let file = Instance::create(Object::new("dstorage file", &FILE_VTABLE), File { file });
  132. put(out, file)
  133. }
  134. /// `(capacity, name, iid, out)`.
  135. extern "system" fn create_status_array(
  136. _: Factory,
  137. capacity: u32,
  138. name: *const c_char,
  139. iid: *const Guid,
  140. out: Out,
  141. ) -> HRESULT {
  142. tracing::info!(
  143. capacity,
  144. name = text(name),
  145. iid = iid_text(iid),
  146. "dstorage: status array"
  147. );
  148. let entries = (0..capacity).map(|_| AtomicI32::new(S_OK)).collect();
  149. let array = Instance::create(
  150. Object::new("dstorage status array", &STATUS_VTABLE),
  151. StatusArray { entries },
  152. );
  153. put(out, array)
  154. }
  155. /// The queue's description: as in 2020 (source type, capacity, priority,
  156. /// name), plus a field the title sets to 1.
  157. #[repr(C)]
  158. struct QueueDesc {
  159. source_type: u64,
  160. capacity: u16,
  161. priority: i8,
  162. name: *const c_char,
  163. unknown: u64,
  164. }
  165. extern "system" fn create_queue(
  166. _: Factory,
  167. desc: *const QueueDesc,
  168. iid: *const Guid,
  169. out: Out,
  170. ) -> HRESULT {
  171. // SAFETY: the title passes its description (null tolerated).
  172. let Some(desc) = (unsafe { desc.as_ref() }) else {
  173. return E_INVALIDARG;
  174. };
  175. let name = text(desc.name);
  176. tracing::info!(
  177. source = desc.source_type,
  178. capacity = desc.capacity,
  179. priority = desc.priority,
  180. name,
  181. unknown = desc.unknown,
  182. iid = iid_text(iid),
  183. "dstorage: queue"
  184. );
  185. let Some(scheduler) = scheduler() else {
  186. return E_OUTOFMEMORY;
  187. };
  188. let mut lanes = scheduler.lock();
  189. let id = lanes.next_id;
  190. lanes.next_id += 1;
  191. let lane = Lane::new(desc.priority, desc.capacity);
  192. lanes.lanes.insert(id, lane);
  193. drop(lanes);
  194. put(
  195. out,
  196. Instance::create(Object::new("dstorage queue", &QUEUE_VTABLE), Queue { id }),
  197. )
  198. }
  199. /// The title asks for 32 MiB and stops if this fails.
  200. extern "system" fn set_staging_buffer_size(_: Factory, size: u32) -> HRESULT {
  201. tracing::info!(size, "dstorage: staging buffer size");
  202. if let Some(scheduler) = scheduler() {
  203. scheduler.lock().staging = u64::from(size);
  204. }
  205. S_OK
  206. }
  207. fn text(name: *const c_char) -> String {
  208. if name.is_null() {
  209. return String::new();
  210. }
  211. // SAFETY: a NUL-terminated name from the title.
  212. unsafe { CStr::from_ptr(name) }
  213. .to_string_lossy()
  214. .into_owned()
  215. }
  216. static FACTORY_VTABLE: Methods<16> = Methods([
  217. missing::<0> as *const (),
  218. add_ref as *const (),
  219. add_ref as *const (),
  220. missing::<3> as *const (), // 0x18 (2020: queue creation)
  221. open_file as *const (), // 0x20
  222. create_status_array as *const (), // 0x28
  223. missing::<6> as *const (), // 0x30 (2020: CPU affinity)
  224. missing::<7> as *const (), // 0x38 (2020: debug flags)
  225. set_staging_buffer_size as *const (), // 0x40
  226. missing::<9> as *const (),
  227. create_queue as *const (), // 0x50
  228. missing::<11> as *const (),
  229. missing::<12> as *const (),
  230. missing::<13> as *const (),
  231. missing::<14> as *const (),
  232. missing::<15> as *const (),
  233. ]);
  234. // Files.
  235. struct File {
  236. file: std::fs::File,
  237. }
  238. static FILE_VTABLE: Methods<8> = Methods([
  239. missing::<0> as *const (),
  240. add_ref_instance::<File> as *const (),
  241. release::<File> as *const (),
  242. missing::<3> as *const (),
  243. missing::<4> as *const (),
  244. missing::<5> as *const (),
  245. missing::<6> as *const (),
  246. missing::<7> as *const (),
  247. ]);
  248. // Status arrays.
  249. struct StatusArray {
  250. entries: Box<[AtomicI32]>,
  251. }
  252. type Array = *mut Instance<StatusArray>;
  253. /// The result of the requests before entry `index`: pending, the first
  254. /// failure, or success.
  255. extern "system" fn status_result(this: Array, index: u32) -> HRESULT {
  256. // SAFETY: an array we created and the title still holds.
  257. let entries = &unsafe { &*this }.state.entries;
  258. entries
  259. .get(index as usize)
  260. .map_or(E_INVALIDARG, |e| e.load(Ordering::Acquire))
  261. }
  262. /// The title polls this (entry 0, a `Sleep(1)` loop) and never
  263. /// reads the result itself.
  264. extern "system" fn is_complete(this: Array, index: u32) -> bool {
  265. status_result(this, index) != E_PENDING
  266. }
  267. static STATUS_VTABLE: Methods<5> = Methods([
  268. missing::<0> as *const (),
  269. add_ref_instance::<StatusArray> as *const (),
  270. release::<StatusArray> as *const (),
  271. is_complete as *const (), // 0x18
  272. status_result as *const (), // 0x20
  273. ]);
  274. // Queues.
  275. /// A queue object: its lane in the scheduler.
  276. struct Queue {
  277. id: u64,
  278. }
  279. impl Drop for Queue {
  280. fn drop(&mut self) {
  281. close_lane(self.id);
  282. }
  283. }
  284. type QueueRef = *const Instance<Queue>;
  285. /// Every queue's requests, run by a pool of workers.
  286. struct Scheduler {
  287. lanes: Mutex<Lanes>,
  288. /// Requests to start, or staging space freed.
  289. work: Condvar,
  290. /// A request finished (for full queues and `close`).
  291. finished: Condvar,
  292. }
  293. /// Priority weights per class (low, normal, high and real-time), as the
  294. /// console's: about 10x per level, counted against request sizes.
  295. const COST: [u64; 3] = [100, 10, 1];
  296. /// The console's default staging buffer.
  297. const STAGING: u64 = 32 << 20;
  298. struct Lanes {
  299. lanes: HashMap<u64, Lane>,
  300. next_id: u64,
  301. /// Submission order over all queues.
  302. next_seq: u64,
  303. /// Bytes of staging held by running requests, and the limit.
  304. staged: u64,
  305. staging: u64,
  306. /// A start waited for staging space since the last finish.
  307. starved: bool,
  308. /// Weighted round robin: each class's virtual time (bytes × cost), and
  309. /// the time of the last start; within a class, the lane clock of the
  310. /// last start.
  311. clock: [u64; 3],
  312. now: u64,
  313. lane_now: [u64; 3],
  314. /// Since the last debug summary: requests, bytes written, time spent
  315. /// running them.
  316. done: (u64, u64, std::time::Duration),
  317. refused: u64,
  318. /// BCPack bytes written and time spent on them.
  319. bcpack: (u64, std::time::Duration),
  320. since: Option<std::time::Instant>,
  321. }
  322. /// A queue's requests in the scheduler.
  323. struct Lane {
  324. class: usize,
  325. capacity: usize,
  326. /// Bytes started, for round robin among the lanes of a class.
  327. clock: u64,
  328. /// Enqueued, not yet submitted.
  329. unsubmitted: Vec<Command>,
  330. /// Submitted, by sequence number: reads not started, status entries
  331. /// not written, reads running, and failures not yet reported.
  332. reads: VecDeque<(u64, Request)>,
  333. statuses: VecDeque<(u64, Status)>,
  334. running: BTreeSet<u64>,
  335. failures: BTreeMap<u64, HRESULT>,
  336. closed: bool,
  337. }
  338. // SAFETY: requests point into title memory and our own objects, which stay
  339. // valid until the title has seen them complete; status arrays count their
  340. // references atomically.
  341. unsafe impl Send for Lane {}
  342. /// A read a worker runs.
  343. struct Job {
  344. lane: u64,
  345. seq: u64,
  346. request: Request,
  347. staging: u64,
  348. }
  349. // SAFETY: as for `Lane`.
  350. unsafe impl Send for Job {}
  351. /// The scheduler, with its workers started on first use; `None` if not
  352. /// even one worker could start.
  353. fn scheduler() -> Option<&'static Scheduler> {
  354. static SCHEDULER: OnceLock<Option<Scheduler>> = OnceLock::new();
  355. static STARTED: std::sync::Once = std::sync::Once::new();
  356. let scheduler = SCHEDULER
  357. .get_or_init(|| {
  358. Some(Scheduler {
  359. lanes: Mutex::new(Lanes {
  360. lanes: HashMap::new(),
  361. next_id: 0,
  362. next_seq: 0,
  363. staged: 0,
  364. staging: STAGING,
  365. starved: false,
  366. clock: [0; 3],
  367. now: 0,
  368. lane_now: [0; 3],
  369. done: Default::default(),
  370. refused: 0,
  371. bcpack: Default::default(),
  372. since: None,
  373. }),
  374. work: Condvar::new(),
  375. finished: Condvar::new(),
  376. })
  377. })
  378. .as_ref()?;
  379. STARTED.call_once(|| {
  380. let workers = std::thread::available_parallelism().map_or(4, |n| n.get());
  381. let started = (0..workers)
  382. .filter(|i| {
  383. std::thread::Builder::new()
  384. .name(format!("dstorage {i}"))
  385. .spawn(|| work(scheduler))
  386. .is_ok()
  387. })
  388. .count();
  389. tracing::info!(workers = started, "dstorage: workers");
  390. });
  391. Some(scheduler)
  392. }
  393. impl Scheduler {
  394. fn lock(&self) -> MutexGuard<'_, Lanes> {
  395. self.lanes.lock().unwrap_or_else(|e| e.into_inner())
  396. }
  397. }
  398. /// A worker: runs the next read of the most deserving queue.
  399. fn work(scheduler: &'static Scheduler) {
  400. let mut lanes = scheduler.lock();
  401. loop {
  402. let Some(job) = lanes.start() else {
  403. lanes = scheduler.work.wait(lanes).unwrap_or_else(|e| e.into_inner());
  404. continue;
  405. };
  406. drop(lanes);
  407. let started = std::time::Instant::now();
  408. let result = execute(&job.request);
  409. lanes = scheduler.lock();
  410. lanes.finish(&job, result);
  411. lanes.count(&job, started);
  412. if std::mem::take(&mut lanes.starved) {
  413. scheduler.work.notify_all();
  414. }
  415. scheduler.finished.notify_all();
  416. }
  417. }
  418. impl Lanes {
  419. /// Counts a finished request; every 5 s a debug line sums them up.
  420. fn count(&mut self, job: &Job, started: std::time::Instant) {
  421. let (requests, bytes, busy) = &mut self.done;
  422. *requests += 1;
  423. *bytes += u64::from(job.request.destination_size);
  424. *busy += started.elapsed();
  425. if job.request.options & BCPACK != 0 {
  426. self.bcpack.0 += u64::from(job.request.destination_size);
  427. self.bcpack.1 += started.elapsed();
  428. }
  429. let since = *self.since.get_or_insert(started);
  430. let elapsed = since.elapsed();
  431. if elapsed.as_secs() >= 5 {
  432. let waiting: usize = self.lanes.values().map(|l| l.reads.len()).sum();
  433. let reading = READING.swap(0, Ordering::Relaxed) as f64 / 1e9;
  434. tracing::debug!(
  435. requests = *requests,
  436. mb_per_s = format_args!("{:.1}", *bytes as f64 / elapsed.as_secs_f64() / 1e6),
  437. busy_workers = format_args!("{:.2}", busy.as_secs_f64() / elapsed.as_secs_f64()),
  438. reading_workers = format_args!("{:.2}", reading / elapsed.as_secs_f64()),
  439. staging_waits = std::mem::take(&mut self.refused),
  440. bcpack_mb = self.bcpack.0 / 1_000_000,
  441. bcpack_workers = format_args!("{:.2}", self.bcpack.1.as_secs_f64() / elapsed.as_secs_f64()),
  442. waiting,
  443. "dstorage: last {:.1} s",
  444. elapsed.as_secs_f64()
  445. );
  446. self.done = Default::default();
  447. self.bcpack = Default::default();
  448. self.since = None;
  449. }
  450. }
  451. /// Starts the next read of the class with the least virtual time, from
  452. /// its lane that has started the fewest bytes, if the staging buffer
  453. /// has room for it (or nothing else holds any).
  454. fn start(&mut self) -> Option<Job> {
  455. let busy = || self.lanes.iter().filter(|(_, l)| !l.reads.is_empty());
  456. let (_, class) = busy().map(|(_, l)| (self.clock[l.class], l.class)).min()?;
  457. let (_, _, id) = busy()
  458. .filter(|(_, l)| l.class == class)
  459. .filter_map(|(&id, l)| Some((l.clock, l.reads.front()?.0, id)))
  460. .min()?;
  461. let lane = self.lanes.get_mut(&id)?;
  462. let &(seq, request) = lane.reads.front()?;
  463. let staging = staging_bytes(&request);
  464. if self.staged > 0 && self.staged + staging > self.staging {
  465. self.starved = true;
  466. self.refused += 1;
  467. return None;
  468. }
  469. lane.reads.pop_front();
  470. lane.running.insert(seq);
  471. self.staged += staging;
  472. let size = u64::from(request.destination_size.max(request.source_size)).max(1);
  473. self.now = self.clock[class];
  474. self.clock[class] += size * COST[class];
  475. self.lane_now[class] = lane.clock;
  476. lane.clock += size;
  477. Some(Job {
  478. lane: id,
  479. seq,
  480. request,
  481. staging,
  482. })
  483. }
  484. fn finish(&mut self, job: &Job, result: Result<(), HRESULT>) {
  485. self.staged -= job.staging;
  486. if let Some(lane) = self.lanes.get_mut(&job.lane) {
  487. lane.running.remove(&job.seq);
  488. if let Err(hr) = result {
  489. lane.failures.insert(job.seq, hr);
  490. }
  491. lane.flush();
  492. }
  493. }
  494. /// Moves a queue's enqueued commands to the workers.
  495. fn submit(&mut self, id: u64) {
  496. let Some(class) = self.lanes.get(&id).map(|l| l.class) else {
  497. return;
  498. };
  499. // A class that had nothing waiting starts from now, not from the
  500. // credit it left behind.
  501. if !self
  502. .lanes
  503. .values()
  504. .any(|l| l.class == class && !l.reads.is_empty())
  505. {
  506. self.clock[class] = self.clock[class].max(self.now);
  507. }
  508. let Some(lane) = self.lanes.get_mut(&id) else {
  509. return;
  510. };
  511. if lane.reads.is_empty() {
  512. lane.clock = lane.clock.max(self.lane_now[class]);
  513. }
  514. for command in std::mem::take(&mut lane.unsubmitted) {
  515. let seq = self.next_seq;
  516. self.next_seq += 1;
  517. match command {
  518. Command::Read(request) => lane.reads.push_back((seq, request)),
  519. Command::Status(status) => lane.statuses.push_back((seq, status)),
  520. }
  521. }
  522. lane.flush();
  523. }
  524. }
  525. impl Lane {
  526. fn new(priority: i8, capacity: u16) -> Lane {
  527. Lane {
  528. class: priority.clamp(-1, 1).wrapping_add(1) as usize,
  529. capacity: usize::from(capacity),
  530. clock: 0,
  531. unsubmitted: Vec::new(),
  532. reads: VecDeque::new(),
  533. statuses: VecDeque::new(),
  534. running: BTreeSet::new(),
  535. failures: BTreeMap::new(),
  536. closed: false,
  537. }
  538. }
  539. /// Requests and status entries held, submitted or not.
  540. fn entries(&self) -> usize {
  541. self.unsubmitted.len() + self.reads.len() + self.statuses.len() + self.running.len()
  542. }
  543. /// Writes the status entries whose earlier reads have all finished.
  544. fn flush(&mut self) {
  545. while let Some(&(seq, _)) = self.statuses.front() {
  546. let waiting = self.reads.front().map(|r| r.0);
  547. if waiting.into_iter().chain(self.running.first().copied()).any(|s| s < seq) {
  548. return;
  549. }
  550. let Some((_, status)) = self.statuses.pop_front() else {
  551. return;
  552. };
  553. let later = self.failures.split_off(&seq);
  554. let first = std::mem::replace(&mut self.failures, later)
  555. .into_values()
  556. .next();
  557. status
  558. .entry()
  559. .store(first.unwrap_or(S_OK), Ordering::Release);
  560. }
  561. }
  562. }
  563. /// Staging bytes a request holds while it runs: what it buffers between
  564. /// the file and the destination. Raw reads go straight to their
  565. /// destination, memory sources need none (as on the console).
  566. fn staging_bytes(request: &Request) -> u64 {
  567. let buffered = request.options & (ZLIB | BCPACK | PAGE_DESTINATION) != 0;
  568. if buffered && request.options & MEMORY_SOURCE == 0 {
  569. u64::from(request.source_size)
  570. } else {
  571. 0
  572. }
  573. }
  574. /// Ends a queue: what was not started is dropped, and this waits for the
  575. /// reads already running (they write title memory).
  576. fn close_lane(id: u64) {
  577. let Some(scheduler) = scheduler() else {
  578. return;
  579. };
  580. let mut lanes = scheduler.lock();
  581. let Some(lane) = lanes.lanes.get_mut(&id) else {
  582. return;
  583. };
  584. lane.closed = true;
  585. lane.unsubmitted.clear();
  586. lane.reads.clear();
  587. lane.statuses.clear(); // releases their arrays
  588. while lanes.lanes.get(&id).is_some_and(|l| !l.running.is_empty()) {
  589. lanes = scheduler
  590. .finished
  591. .wait(lanes)
  592. .unwrap_or_else(|e| e.into_inner());
  593. }
  594. lanes.lanes.remove(&id);
  595. scheduler.finished.notify_all();
  596. }
  597. /// A read request as the title builds it, 0x48 bytes.
  598. #[repr(C)]
  599. #[derive(Clone, Copy)]
  600. struct Request {
  601. options: u64,
  602. /// An address, or with `PAGE_DESTINATION` an array of 64 KiB page
  603. /// numbers.
  604. destination: *mut c_void,
  605. /// With `PAGE_DESTINATION`, the low 16 bits are where in the first page
  606. /// the destination starts.
  607. page_offset: u64,
  608. destination_size: u32,
  609. /// Our file object, or with `MEMORY_SOURCE` an address.
  610. source: *const c_void,
  611. offset: u64,
  612. source_size: u32,
  613. /// Compressed size between two decompression stages; unused here.
  614. intermediate_size: u32,
  615. /// Matched by cancellation; the title leaves it 0.
  616. tag: u64,
  617. name: *const c_char,
  618. }
  619. // Request options.
  620. /// Inflate zlib (RFC 1950) data.
  621. const ZLIB: u64 = 1;
  622. /// Bits 1-4: decode BCPack data of this BC format number (0: none).
  623. const BCPACK: u64 = 0xf << 1;
  624. const PAGE_DESTINATION: u64 = 1 << 21;
  625. const MEMORY_SOURCE: u64 = 1 << 22;
  626. // Bits 5-20 select a further transform, bit 23 a source in physical pages;
  627. // The title's packages need neither, so requests with them fail.
  628. const PAGE: usize = 64 * 1024;
  629. enum Command {
  630. Read(Request),
  631. Status(Status),
  632. }
  633. /// A status entry to write, holding a reference on its array.
  634. struct Status {
  635. array: Array,
  636. index: u32,
  637. }
  638. impl Drop for Status {
  639. fn drop(&mut self) {
  640. release(self.array);
  641. }
  642. }
  643. impl Status {
  644. fn entry(&self) -> &AtomicI32 {
  645. // SAFETY: we hold a reference; the index was checked when enqueued.
  646. &unsafe { &*self.array }.state.entries[self.index as usize]
  647. }
  648. }
  649. extern "system" fn enqueue_request(this: QueueRef, request: *const Request) {
  650. // SAFETY: the title passes its request (null tolerated).
  651. let Some(&request) = (unsafe { request.as_ref() }) else {
  652. return;
  653. };
  654. queue(this, Command::Read(request));
  655. }
  656. extern "system" fn enqueue_status(this: QueueRef, array: Array, index: u32) {
  657. // SAFETY: the title passes an array we created (null tolerated).
  658. let Some(entries) = (unsafe { array.as_ref() }).map(|a| &a.state.entries) else {
  659. return;
  660. };
  661. let Some(entry) = entries.get(index as usize) else {
  662. tracing::warn!(index, "dstorage: status entry out of range");
  663. return;
  664. };
  665. entry.store(E_PENDING, Ordering::Release);
  666. add_ref_instance(array);
  667. queue(this, Command::Status(Status { array, index }));
  668. }
  669. /// Adds a command to the queue; blocks while the queue is full, and
  670. /// submits on its own once half of it is enqueued, as the console does.
  671. fn queue(this: QueueRef, command: Command) {
  672. // SAFETY: a queue we created and the title still holds.
  673. let id = unsafe { &*this }.state.id;
  674. let Some(scheduler) = scheduler() else {
  675. return;
  676. };
  677. let mut lanes = scheduler.lock();
  678. loop {
  679. let Some(lane) = lanes.lanes.get(&id).filter(|l| !l.closed) else {
  680. return; // closed: dropped (a status releases its array)
  681. };
  682. // One slot stays free, as the console's count of empty slots says.
  683. if lane.entries() + 1 < lane.capacity.max(2) {
  684. break;
  685. }
  686. lanes = scheduler
  687. .finished
  688. .wait(lanes)
  689. .unwrap_or_else(|e| e.into_inner());
  690. }
  691. let Some(lane) = lanes.lanes.get_mut(&id) else {
  692. return;
  693. };
  694. lane.unsubmitted.push(command);
  695. if lane.unsubmitted.len() >= (lane.capacity / 2).max(1) {
  696. lanes.submit(id);
  697. scheduler.work.notify_all();
  698. }
  699. }
  700. extern "system" fn submit(this: QueueRef) {
  701. // SAFETY: as above.
  702. let id = unsafe { &*this }.state.id;
  703. let Some(scheduler) = scheduler() else {
  704. return;
  705. };
  706. let mut lanes = scheduler.lock();
  707. let pending = lanes.lanes.get(&id).map_or(0, |l| l.unsubmitted.len());
  708. tracing::debug!(commands = pending, "dstorage: submit");
  709. lanes.submit(id);
  710. scheduler.work.notify_all();
  711. }
  712. /// Ends the queue whatever its reference count: what was not started never
  713. /// completes, and this returns once the reads already running have
  714. /// finished. The title calls this, not `Release`.
  715. extern "system" fn close(this: QueueRef) {
  716. // SAFETY: as above.
  717. close_lane(unsafe { &*this }.state.id);
  718. }
  719. /// Reads, inflates and/or unpacks, and writes one request.
  720. fn execute(request: &Request) -> Result<(), HRESULT> {
  721. let options = request.options;
  722. let fail = |hr: HRESULT, why: &str| {
  723. tracing::warn!(
  724. options = format_args!("{options:#x}"),
  725. offset = request.offset,
  726. source_size = request.source_size,
  727. destination_size = request.destination_size,
  728. intermediate_size = request.intermediate_size,
  729. tag = request.tag,
  730. name = text(request.name),
  731. hr = format_args!("{:#010x}", hr as u32),
  732. "dstorage: request failed: {why}"
  733. );
  734. hr
  735. };
  736. if options & !(ZLIB | BCPACK | PAGE_DESTINATION | MEMORY_SOURCE) != 0 {
  737. return Err(fail(E_NOTIMPL, "unsupported options"));
  738. }
  739. if request.source.is_null() || request.destination.is_null() {
  740. return Err(fail(E_INVALIDARG, "no source or destination"));
  741. }
  742. let bc = ((options & BCPACK) >> 1) as u8;
  743. let size = request.destination_size as usize;
  744. if options & (ZLIB | BCPACK) == 0 {
  745. if request.source_size > request.destination_size {
  746. return Err(fail(E_INVALIDARG, "source larger than destination"));
  747. }
  748. let size = request.source_size as usize;
  749. return into_destination(request, size, |out| read_into(request, out).map(|()| size))
  750. .map_err(|hr| fail(hr, "copying"));
  751. }
  752. let tables = if bc != 0 { Some(bcpack_tables()?) } else { None };
  753. let source = read_source(request).map_err(|hr| fail(hr, "reading the source"))?;
  754. // The console's order: zlib first, then BCPack.
  755. let source = if bc != 0 && options & ZLIB != 0 {
  756. let mut packed = vec![0; request.intermediate_size as usize];
  757. let n = inflate(&source, &mut packed).map_err(|hr| fail(hr, "zlib"))?;
  758. packed.truncate(n);
  759. Cow::Owned(packed)
  760. } else {
  761. source
  762. };
  763. into_destination(request, size, |out| match tables {
  764. Some(tables) => bcpack::decode(bc, &source, out, tables)
  765. .map(|()| out.len())
  766. .map_err(|e| fail(INVALID_DATA, &e.to_string())),
  767. None => inflate(&source, out).map_err(|hr| fail(hr, "zlib")),
  768. })?;
  769. tracing::trace!(
  770. options = format_args!("{options:#x}"),
  771. offset = request.offset,
  772. size,
  773. "dstorage: request done"
  774. );
  775. Ok(())
  776. }
  777. /// Inflates a zlib stream into `out`, returning the bytes written. A stream
  778. /// that ends short of `out` passes: the title's chunks fill it exactly, and
  779. /// nothing says that is required.
  780. fn inflate(source: &[u8], out: &mut [u8]) -> Result<usize, HRESULT> {
  781. thread_local! {
  782. static INFLATE: std::cell::RefCell<zlib_rs::Inflate> =
  783. std::cell::RefCell::new(zlib_rs::Inflate::new(true, 15));
  784. }
  785. INFLATE.with_borrow_mut(|state| {
  786. state.reset(true);
  787. // `Inflate::decompress` cannot distinguish a valid empty stream from
  788. // an insufficient buffer when `avail_out == 0`, so use a 1-byte scratch
  789. // destination and verify `written <= out_len` afterward.
  790. let out_len = out.len();
  791. let mut scratch = [0u8; 1];
  792. let dest = if out_len == 0 { &mut scratch[..] } else { out };
  793. let (mut in_pos, mut out_pos) = (0usize, 0usize);
  794. let status = loop {
  795. match state.decompress(
  796. &source[in_pos..],
  797. &mut dest[out_pos..],
  798. zlib_rs::InflateFlush::NoFlush,
  799. ) {
  800. Ok(zlib_rs::Status::StreamEnd) => break Ok(zlib_rs::Status::StreamEnd),
  801. Ok(zlib_rs::Status::Ok) => {
  802. let next_in = state.total_in() as usize;
  803. let next_out = state.total_out() as usize;
  804. if next_in == in_pos && next_out == out_pos {
  805. break Ok(zlib_rs::Status::BufError);
  806. }
  807. in_pos = next_in;
  808. out_pos = next_out;
  809. }
  810. other => break other,
  811. }
  812. };
  813. let written = state.total_out() as usize;
  814. match status {
  815. Ok(zlib_rs::Status::StreamEnd) if written <= out_len => Ok(written),
  816. other => {
  817. tracing::debug!(?other, "dstorage: zlib stream");
  818. Err(INVALID_DATA)
  819. }
  820. }
  821. })
  822. }
  823. /// The BCPack format's constant tables, parsed once for the process. If
  824. /// they do not parse every BCPack request fails: one warning, then debug.
  825. fn bcpack_tables() -> Result<&'static Tables, HRESULT> {
  826. static TABLES: OnceLock<Result<Tables, String>> = OnceLock::new();
  827. static WARNED: AtomicBool = AtomicBool::new(false);
  828. match TABLES.get_or_init(load_bcpack_tables) {
  829. Ok(tables) => Ok(tables),
  830. Err(why) if !WARNED.swap(true, Ordering::Relaxed) => {
  831. tracing::warn!("dstorage: BCPack requests fail: {why} (more at debug)");
  832. Err(E_NOTIMPL)
  833. }
  834. Err(_) => {
  835. tracing::debug!("dstorage: BCPack request failed: no tables");
  836. Err(E_NOTIMPL)
  837. }
  838. }
  839. }
  840. /// The tables VIctory ships with.
  841. #[cfg(not(test))]
  842. fn load_bcpack_tables() -> Result<Tables, String> {
  843. Tables::builtin().map_err(|e| format!("the built-in BCPack tables: {e}"))
  844. }
  845. /// Tests decode streams made against tables of their own, from this folder.
  846. #[cfg(test)]
  847. static BCPACK_DIR: OnceLock<std::path::PathBuf> = OnceLock::new();
  848. #[cfg(test)]
  849. fn use_bcpack_tables(dir: std::path::PathBuf) {
  850. let _ = BCPACK_DIR.set(dir);
  851. }
  852. #[cfg(test)]
  853. fn load_bcpack_tables() -> Result<Tables, String> {
  854. let dir = BCPACK_DIR.get().ok_or("no folder set for the test tables")?;
  855. let bytes = std::fs::read(dir.join("tables.bin")).map_err(|e| e.to_string())?;
  856. Tables::parse(&bytes).map_err(|e| e.to_string())
  857. }
  858. /// A compressed request's source: borrowed from memory, or read from the
  859. /// file.
  860. fn read_source(request: &Request) -> Result<Cow<'static, [u8]>, HRESULT> {
  861. let size = request.source_size as usize;
  862. if request.options & MEMORY_SOURCE != 0 {
  863. // SAFETY: the title's source holds `size` bytes until completion.
  864. let bytes = unsafe { std::slice::from_raw_parts(request.source.cast(), size) };
  865. return Ok(Cow::Borrowed(bytes));
  866. }
  867. let mut bytes = vec![0; size];
  868. read_into(request, &mut bytes)?;
  869. Ok(Cow::Owned(bytes))
  870. }
  871. /// Nanoseconds workers spent reading files, for the debug summary.
  872. static READING: AtomicU64 = AtomicU64::new(0);
  873. /// Fills `out` (the source size) from the request's file or memory.
  874. fn read_into(request: &Request, out: &mut [u8]) -> Result<(), HRESULT> {
  875. if request.options & MEMORY_SOURCE != 0 {
  876. // SAFETY: the title's source holds `out.len()` bytes until completion.
  877. out.copy_from_slice(unsafe { std::slice::from_raw_parts(request.source.cast(), out.len()) });
  878. return Ok(());
  879. }
  880. // SAFETY: a file object we created; the title keeps it open.
  881. let file = &unsafe { &*request.source.cast::<Instance<File>>() }
  882. .state
  883. .file;
  884. let started = std::time::Instant::now();
  885. let mut done = 0;
  886. let result = loop {
  887. if done == out.len() {
  888. break Ok(());
  889. }
  890. match file.seek_read(&mut out[done..], request.offset + done as u64) {
  891. Ok(0) => break Err(END_OF_FILE),
  892. Ok(n) => done += n,
  893. Err(error) => break Err(from_win32(&error)),
  894. }
  895. };
  896. READING.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
  897. result
  898. }
  899. /// Runs `fill` on the destination's first `len` bytes; `fill` returns how
  900. /// many it produced. GPU-visible destinations are host memory like the
  901. /// rest (GPU address = CPU address), so an address is written in place;
  902. /// physical pages are too when they are consecutive pages of one
  903. /// allocation, and otherwise go through a buffer.
  904. fn into_destination(
  905. request: &Request,
  906. len: usize,
  907. fill: impl FnOnce(&mut [u8]) -> Result<usize, HRESULT>,
  908. ) -> Result<(), HRESULT> {
  909. if request.options & PAGE_DESTINATION == 0 {
  910. // Raw reads land through the kernel, which does not fault into the
  911. // GPU side's guard on title buffers; open them first.
  912. victory_gpu::kernel_will_write(request.destination as usize, len);
  913. // SAFETY: the title's destination holds `destination_size` bytes, at
  914. // least `len`, and nothing else writes it until completion.
  915. let out = unsafe { std::slice::from_raw_parts_mut(request.destination.cast::<u8>(), len) };
  916. let filled = fill(out).map(drop);
  917. // Again now that the bytes are there: a texture looked at in between
  918. // was uploaded without them (`xmem::pages_written`).
  919. if super::xmem::stream_notice() {
  920. victory_gpu::kernel_will_write(request.destination as usize, len);
  921. }
  922. return filled;
  923. }
  924. let offset = (request.page_offset & 0xffff) as usize;
  925. let pages = &page_list(request.destination.cast(), offset, len)[..];
  926. // Consecutive pages of one allocation (the usual case): written in
  927. // place through one view.
  928. if let Some(mut window) = super::xmem::page_window(pages, offset, len) {
  929. let filled = fill(window.bytes()).map(drop);
  930. super::xmem::pages_written(pages, offset, len);
  931. return filled;
  932. }
  933. let mut data = vec![0; len];
  934. let n = fill(&mut data)?;
  935. // A page the title has just made, or a view the host refuses for a moment (commit
  936. // or address space short while a load maps many at once), can come right a little
  937. // later: tried again before the request fails (`VICTORY_DSTORAGE_RETRIES`, default 12,
  938. // about 1.5 s in all).
  939. static RETRIES: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
  940. let retries = *RETRIES.get_or_init(|| {
  941. std::env::var("VICTORY_DSTORAGE_RETRIES").ok().and_then(|v| v.parse().ok()).unwrap_or(12)
  942. });
  943. let mut written = super::xmem::write_physical(pages, offset, &data[..n]);
  944. let mut tries = 0;
  945. while !written && tries < retries {
  946. std::thread::sleep(std::time::Duration::from_millis((2u64 << tries.min(6)).min(128)));
  947. tries += 1;
  948. written = super::xmem::write_physical(pages, offset, &data[..n]);
  949. }
  950. if written {
  951. super::xmem::pages_written(pages, offset, n);
  952. if tries > 0 {
  953. tracing::info!(offset, len, tries, "dstorage: a destination's physical pages written after a retry");
  954. }
  955. Ok(())
  956. } else {
  957. let known = super::xmem::pages_known(pages, offset, len);
  958. tracing::warn!(known, last_error = std::io::Error::last_os_error().raw_os_error(), "dstorage: retries used up");
  959. // Said aloud: the title never reads a request's result
  960. // (it only polls for completion), so a destination left unwritten
  961. // is a model or texture that silently holds whatever its pages
  962. // held before.
  963. tracing::warn!(
  964. offset,
  965. len,
  966. pages = pages.len(),
  967. "dstorage: a destination's physical pages could not be written (unknown page or a host failure); its request fails"
  968. );
  969. Err(E_INVALIDARG)
  970. }
  971. }
  972. /// The request's page numbers, one per 64 KiB of destination. The title
  973. /// queues a request before it has filled its page list in, and a worker that
  974. /// reads the list at once finds page 0 in it (pages of models and textures
  975. /// that were then never written: walls missing for the whole run). So a list
  976. /// with a page the title does not own is read again for a while, up to
  977. /// 1.5 s; what it holds then is used as it is.
  978. fn page_list(list: *const usize, offset: usize, len: usize) -> Vec<usize> {
  979. let read = || -> Vec<usize> {
  980. (0..(offset + len).div_ceil(PAGE))
  981. // SAFETY: the title passes a page number per 64 KiB of
  982. // destination, which holds at least `len` bytes from `offset`;
  983. // it may be writing them.
  984. .map(|i| unsafe { list.add(i).read_volatile() })
  985. .collect()
  986. };
  987. let started = std::time::Instant::now();
  988. let mut pages = read();
  989. while !super::xmem::pages_known(&pages, offset, len) && started.elapsed().as_millis() < 1500 {
  990. std::thread::sleep(std::time::Duration::from_millis(1));
  991. pages = read();
  992. }
  993. let waited = started.elapsed();
  994. if waited.as_millis() >= 1 {
  995. tracing::info!(
  996. ms = waited.as_millis() as u64,
  997. known = super::xmem::pages_known(&pages, offset, len),
  998. "dstorage: a destination's page list was not filled in yet"
  999. );
  1000. }
  1001. pages
  1002. }
  1003. /// Slots by the 2020 order, which the argument shapes at
  1004. /// the title's call sites match (0x18, 0x20, 0x30 and 0x40 are called).
  1005. static QUEUE_VTABLE: Methods<12> = Methods([
  1006. missing::<0> as *const (),
  1007. add_ref_instance::<Queue> as *const (),
  1008. release::<Queue> as *const (),
  1009. enqueue_request as *const (), // 0x18
  1010. enqueue_status as *const (), // 0x20
  1011. missing::<5> as *const (), // 0x28 (2020: fence signal)
  1012. submit as *const (), // 0x30
  1013. missing::<7> as *const (), // 0x38 (2020: cancel by tag)
  1014. close as *const (), // 0x40
  1015. missing::<9> as *const (), // 0x48 (2020: error event)
  1016. missing::<10> as *const (), // 0x50 (2020: error record)
  1017. missing::<11> as *const (), // 0x58 (2020: queue info)
  1018. ]);
  1019. pub(crate) fn module() -> HleModule {
  1020. HleModule {
  1021. name: "dstorage",
  1022. dlls: &["xcrdapi.dll"],
  1023. exports: vec![hle_export!(DStorageGetFactory)],
  1024. }
  1025. }
  1026. #[cfg(test)]
  1027. mod tests {
  1028. use std::os::windows::ffi::OsStrExt;
  1029. use std::time::{Duration, Instant};
  1030. use super::*;
  1031. use crate::modules::xgameruntime::method;
  1032. fn call<F: Copy>(object: *mut c_void, slot: usize) -> F {
  1033. // SAFETY: every object here starts with the runtime header.
  1034. method(unsafe { &*object.cast::<Object>() }, slot)
  1035. }
  1036. fn factory() -> *mut c_void {
  1037. let mut factory = std::ptr::null_mut();
  1038. assert_eq!(DStorageGetFactory(&FACTORY, &mut factory), S_OK);
  1039. factory
  1040. }
  1041. fn open(path: &std::path::Path) -> *mut c_void {
  1042. let wide: Vec<u16> = path.as_os_str().encode_wide().chain([0]).collect();
  1043. let open: extern "system" fn(*mut c_void, *const u16, *const Guid, Out) -> HRESULT =
  1044. call(factory(), 0x20);
  1045. let mut file = std::ptr::null_mut();
  1046. assert_eq!(
  1047. open(factory(), wide.as_ptr(), std::ptr::null(), &mut file),
  1048. S_OK
  1049. );
  1050. file
  1051. }
  1052. fn status_array(capacity: u32) -> *mut c_void {
  1053. let create: extern "system" fn(
  1054. *mut c_void,
  1055. u32,
  1056. *const c_char,
  1057. *const Guid,
  1058. Out,
  1059. ) -> HRESULT = call(factory(), 0x28);
  1060. let mut array = std::ptr::null_mut();
  1061. let name = c"test".as_ptr();
  1062. assert_eq!(
  1063. create(factory(), capacity, name, std::ptr::null(), &mut array),
  1064. S_OK
  1065. );
  1066. array
  1067. }
  1068. fn new_queue(source_type: u64) -> *mut c_void {
  1069. let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT =
  1070. call(factory(), 0x50);
  1071. let desc = QueueDesc {
  1072. source_type,
  1073. capacity: 0x80,
  1074. priority: 0,
  1075. name: c"test".as_ptr(),
  1076. unknown: 1,
  1077. };
  1078. let mut queue = std::ptr::null_mut();
  1079. assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK);
  1080. queue
  1081. }
  1082. fn request(
  1083. options: u64,
  1084. destination: *mut c_void,
  1085. destination_size: usize,
  1086. source: *const c_void,
  1087. offset: u64,
  1088. source_size: usize,
  1089. ) -> Request {
  1090. Request {
  1091. options,
  1092. destination,
  1093. page_offset: 0,
  1094. destination_size: destination_size as u32,
  1095. source,
  1096. offset,
  1097. source_size: source_size as u32,
  1098. intermediate_size: 0,
  1099. tag: 0,
  1100. name: std::ptr::null(),
  1101. }
  1102. }
  1103. fn enqueue(queue: *mut c_void, request: &Request) {
  1104. let f: extern "system" fn(*mut c_void, *const Request) = call(queue, 0x18);
  1105. f(queue, request);
  1106. }
  1107. fn enqueue_status(queue: *mut c_void, array: *mut c_void, index: u32) {
  1108. let f: extern "system" fn(*mut c_void, *mut c_void, u32) = call(queue, 0x20);
  1109. f(queue, array, index);
  1110. }
  1111. fn void(object: *mut c_void, slot: usize) {
  1112. let f: extern "system" fn(*mut c_void) = call(object, slot);
  1113. f(object);
  1114. }
  1115. fn result(array: *mut c_void, index: u32) -> HRESULT {
  1116. let f: extern "system" fn(*mut c_void, u32) -> HRESULT = call(array, 0x20);
  1117. f(array, index)
  1118. }
  1119. /// Polls as the title does, then returns the entry's result.
  1120. fn wait(array: *mut c_void, index: u32) -> HRESULT {
  1121. let done: extern "system" fn(*mut c_void, u32) -> bool = call(array, 0x18);
  1122. let start = Instant::now();
  1123. while !done(array, index) {
  1124. assert!(start.elapsed() < Duration::from_secs(10), "never completed");
  1125. std::thread::sleep(Duration::from_millis(1));
  1126. }
  1127. result(array, index)
  1128. }
  1129. fn file_with(bytes: &[u8]) -> (tempfile::TempDir, *mut c_void) {
  1130. let dir = tempfile::tempdir().unwrap();
  1131. let path = dir.path().join("data.bin");
  1132. std::fs::write(&path, bytes).unwrap();
  1133. let file = open(&path);
  1134. (dir, file)
  1135. }
  1136. fn pattern(n: usize) -> Vec<u8> {
  1137. (0..n).map(|i| (i * 7 + i / 251) as u8).collect()
  1138. }
  1139. #[test]
  1140. fn request_layout_is_the_titles() {
  1141. assert_eq!(size_of::<Request>(), 0x48);
  1142. assert_eq!(std::mem::offset_of!(Request, destination_size), 0x18);
  1143. assert_eq!(std::mem::offset_of!(Request, source), 0x20);
  1144. assert_eq!(std::mem::offset_of!(Request, source_size), 0x30);
  1145. assert_eq!(std::mem::offset_of!(Request, name), 0x40);
  1146. assert_eq!(std::mem::offset_of!(QueueDesc, unknown), 0x18);
  1147. }
  1148. fn compress_zlib(plain: &[u8]) -> Vec<u8> {
  1149. let mut buf = vec![0u8; zlib_rs::compress_bound(plain.len())];
  1150. let (packed, rc) =
  1151. zlib_rs::compress_slice(&mut buf, plain, zlib_rs::DeflateConfig::new(6));
  1152. assert_eq!(rc, zlib_rs::ReturnCode::Ok);
  1153. packed.to_vec()
  1154. }
  1155. #[test]
  1156. fn raw_and_zlib_reads_from_a_file() {
  1157. let plain = pattern(300_000);
  1158. let packed = compress_zlib(&plain);
  1159. let mut contents = plain.clone();
  1160. contents.extend_from_slice(&packed);
  1161. let (_dir, file) = file_with(&contents);
  1162. let (queue, array) = (new_queue(0), status_array(1));
  1163. let mut raw = vec![0u8; 1000];
  1164. let mut inflated = vec![0u8; plain.len()];
  1165. let at = |b: &mut Vec<u8>| b.as_mut_ptr().cast();
  1166. enqueue(queue, &request(0, at(&mut raw), 1000, file, 5000, 1000));
  1167. let offset = plain.len() as u64;
  1168. let zlib = request(
  1169. ZLIB,
  1170. at(&mut inflated),
  1171. plain.len(),
  1172. file,
  1173. offset,
  1174. packed.len(),
  1175. );
  1176. enqueue(queue, &zlib);
  1177. enqueue_status(queue, array, 0);
  1178. assert_eq!(result(array, 0), E_PENDING, "pending until done");
  1179. void(queue, 0x30);
  1180. assert_eq!(wait(array, 0), S_OK);
  1181. assert_eq!(raw, plain[5000..6000]);
  1182. assert_eq!(inflated, plain);
  1183. void(queue, 0x40);
  1184. }
  1185. #[test]
  1186. fn memory_sources_inflate_too() {
  1187. let plain = pattern(70_000);
  1188. let packed = compress_zlib(&plain);
  1189. let (queue, array) = (new_queue(1), status_array(1));
  1190. let mut out = vec![0u8; plain.len()];
  1191. let options = ZLIB | MEMORY_SOURCE;
  1192. let r = request(
  1193. options,
  1194. out.as_mut_ptr().cast(),
  1195. out.len(),
  1196. packed.as_ptr().cast(),
  1197. 0,
  1198. packed.len(),
  1199. );
  1200. enqueue(queue, &r);
  1201. enqueue_status(queue, array, 0);
  1202. void(queue, 0x30);
  1203. assert_eq!(wait(array, 0), S_OK);
  1204. assert_eq!(out, plain);
  1205. }
  1206. #[test]
  1207. fn statuses_complete_in_order_with_the_first_failure() {
  1208. let contents = pattern(4096);
  1209. let (_dir, file) = file_with(&contents);
  1210. let (queue, array) = (new_queue(0), status_array(3));
  1211. // Requests in flight together run in any order, so none of them
  1212. // shares a destination (failed ones leave theirs undefined).
  1213. let mut buffers = [[0u8; 16]; 5];
  1214. let [failed, failed_too, out, other, bcpack] = buffers.each_mut().map(|b| b.as_mut_ptr().cast());
  1215. // Segment 0: a read past the end, then a bad stream; the first wins.
  1216. enqueue(queue, &request(0, failed, 16, file, 4090, 16));
  1217. enqueue(queue, &request(ZLIB, failed_too, 16, file, 0, 16));
  1218. enqueue_status(queue, array, 0);
  1219. // Segment 1: two reads.
  1220. enqueue(queue, &request(0, other, 16, file, 0, 16));
  1221. enqueue(queue, &request(0, out, 16, file, 100, 16));
  1222. enqueue_status(queue, array, 1);
  1223. void(queue, 0x30);
  1224. // Segment 2: a BCPack request (BC7) whose stream is empty fails.
  1225. with_test_tables();
  1226. enqueue(queue, &request(7 << 1, bcpack, 16, file, 0, 0));
  1227. enqueue_status(queue, array, 2);
  1228. void(queue, 0x30);
  1229. assert_eq!(wait(array, 2), INVALID_DATA);
  1230. assert_eq!(result(array, 0), END_OF_FILE);
  1231. assert_eq!(result(array, 1), S_OK);
  1232. assert_eq!(buffers[2], contents[100..116]);
  1233. assert_eq!(buffers[3], contents[..16]);
  1234. }
  1235. #[test]
  1236. fn half_a_queue_submits_itself() {
  1237. let (_dir, file) = file_with(&pattern(64));
  1238. let create: extern "system" fn(*mut c_void, *const QueueDesc, *const Guid, Out) -> HRESULT =
  1239. call(factory(), 0x50);
  1240. let desc = QueueDesc {
  1241. source_type: 0,
  1242. capacity: 4,
  1243. priority: 1,
  1244. name: c"small".as_ptr(),
  1245. unknown: 1,
  1246. };
  1247. let mut queue = std::ptr::null_mut();
  1248. assert_eq!(create(factory(), &desc, std::ptr::null(), &mut queue), S_OK);
  1249. let array = status_array(1);
  1250. let mut out = [0u8; 16];
  1251. enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 8, 16));
  1252. enqueue_status(queue, array, 0); // the second of four: no submit needed
  1253. assert_eq!(wait(array, 0), S_OK);
  1254. assert_eq!(out, pattern(64)[8..24]);
  1255. }
  1256. /// Lanes without workers: what `start` picks, and when statuses land.
  1257. fn lanes(staging: u64) -> Lanes {
  1258. Lanes {
  1259. lanes: HashMap::new(),
  1260. next_id: 0,
  1261. next_seq: 0,
  1262. staged: 0,
  1263. staging,
  1264. starved: false,
  1265. clock: [0; 3],
  1266. now: 0,
  1267. lane_now: [0; 3],
  1268. done: Default::default(),
  1269. refused: 0,
  1270. bcpack: Default::default(),
  1271. since: None,
  1272. }
  1273. }
  1274. fn read(lanes: &mut Lanes, id: u64, options: u64, size: u32) {
  1275. let mut r = request(options, std::ptr::null_mut(), 0, std::ptr::null(), 0, 0);
  1276. (r.destination_size, r.source_size) = (size, size);
  1277. let lane = lanes.lanes.get_mut(&id).unwrap();
  1278. lane.unsubmitted.push(Command::Read(r));
  1279. }
  1280. #[test]
  1281. fn priorities_share_by_bytes_about_tenfold() {
  1282. let mut l = lanes(STAGING);
  1283. l.lanes.insert(0, Lane::new(0, 4096));
  1284. l.lanes.insert(1, Lane::new(1, 4096));
  1285. l.lanes.insert(2, Lane::new(2, 4096)); // real-time: as high
  1286. for _ in 0..400 {
  1287. for id in 0..3 {
  1288. read(&mut l, id, 0, 4096);
  1289. }
  1290. }
  1291. (0..3).for_each(|id| l.submit(id));
  1292. let mut started = [0u32; 3];
  1293. for _ in 0..330 {
  1294. let job = l.start().unwrap();
  1295. started[job.lane as usize] += 1;
  1296. l.finish(&job, Ok(()));
  1297. }
  1298. // Normal gets about a tenth of what high and real-time get together.
  1299. assert_eq!(started[1] + started[2], 300, "{started:?}");
  1300. assert_eq!(started[0], 30, "{started:?}");
  1301. assert!(started[1].abs_diff(started[2]) <= 1, "{started:?}");
  1302. }
  1303. #[test]
  1304. fn staging_bounds_compressed_bytes_in_flight() {
  1305. let mut l = lanes(100);
  1306. l.lanes.insert(0, Lane::new(0, 64));
  1307. read(&mut l, 0, ZLIB, 60);
  1308. read(&mut l, 0, ZLIB, 60);
  1309. read(&mut l, 0, 0, 1000); // raw: straight to its destination
  1310. l.submit(0);
  1311. let first = l.start().unwrap();
  1312. assert!(l.start().is_none(), "60 + 60 > 100");
  1313. l.finish(&first, Ok(()));
  1314. let second = l.start().unwrap();
  1315. let raw = l.start().unwrap();
  1316. assert_eq!((second.staging, raw.staging), (60, 0));
  1317. // Alone, a request larger than the buffer still runs.
  1318. read(&mut l, 0, ZLIB, 500);
  1319. l.submit(0);
  1320. assert!(l.start().is_none());
  1321. l.finish(&second, Ok(()));
  1322. assert!(l.start().is_some());
  1323. }
  1324. #[test]
  1325. fn a_status_waits_for_every_earlier_read() {
  1326. let mut l = lanes(STAGING);
  1327. l.lanes.insert(0, Lane::new(0, 64));
  1328. let array = status_array(2).cast::<Instance<StatusArray>>();
  1329. let status = |index| {
  1330. add_ref_instance(array);
  1331. Command::Status(Status { array, index })
  1332. };
  1333. read(&mut l, 0, 0, 16);
  1334. read(&mut l, 0, 0, 16);
  1335. l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(0));
  1336. read(&mut l, 0, 0, 16);
  1337. l.lanes.get_mut(&0).unwrap().unsubmitted.push(status(1));
  1338. // SAFETY: an array we created.
  1339. for entry in unsafe { &(*array).state.entries }.iter() {
  1340. entry.store(E_PENDING, Ordering::Release);
  1341. }
  1342. l.submit(0);
  1343. let jobs: Vec<Job> = (0..3).map(|_| l.start().unwrap()).collect();
  1344. // The last read and the first finish; the second then fails.
  1345. l.finish(&jobs[2], Ok(()));
  1346. l.finish(&jobs[0], Ok(()));
  1347. let results = || (result(array.cast(), 0), result(array.cast(), 1));
  1348. assert_eq!(results(), (E_PENDING, E_PENDING));
  1349. l.finish(&jobs[1], Err(INVALID_DATA));
  1350. assert_eq!(results(), (INVALID_DATA, S_OK));
  1351. }
  1352. #[test]
  1353. fn zlib_then_bcpack() {
  1354. with_test_tables();
  1355. let packed = compress_zlib(&BC4_STREAM);
  1356. let (_dir, file) = file_with(&packed);
  1357. let (queue, array) = (new_queue(0), status_array(1));
  1358. let mut out = [0u8; 16];
  1359. let options = ZLIB | 4 << 1;
  1360. let mut r = request(options, out.as_mut_ptr().cast(), 16, file, 0, packed.len());
  1361. r.intermediate_size = BC4_STREAM.len() as u32;
  1362. enqueue(queue, &r);
  1363. enqueue_status(queue, array, 0);
  1364. void(queue, 0x30);
  1365. assert_eq!(wait(array, 0), S_OK);
  1366. assert_eq!(out, bc4_blocks());
  1367. }
  1368. /// BCPack tables we made (uniform models; BC4 index pairs: low 3 bits,
  1369. /// next 3 bits), in a folder kept for the test process.
  1370. fn with_test_tables() {
  1371. static DIR: OnceLock<()> = OnceLock::new();
  1372. DIR.get_or_init(|| {
  1373. let mut t = Vec::new();
  1374. for m in 0..128 {
  1375. let g = m / 16;
  1376. for b in 0..9 {
  1377. let f: u16 = if b < g + 2 { 1 << (15 - g) } else { 0 };
  1378. t.extend_from_slice(&f.to_le_bytes());
  1379. }
  1380. }
  1381. t.extend([0; 256 + 64 + 256]);
  1382. t.extend((0..64u8).map(|v| (v & 7) | (v >> 3) << 4));
  1383. t.resize(bcpack::TABLES_SIZE, 0);
  1384. let dir = tempfile::tempdir().unwrap().keep();
  1385. std::fs::write(dir.join("tables.bin"), t).unwrap();
  1386. use_bcpack_tables(dir);
  1387. });
  1388. }
  1389. /// Two BC4 blocks from the format's test encoder: endpoints 10, -3 with
  1390. /// indices p -> p & 7, then the same block plus 1 everywhere.
  1391. const BC4_STREAM: [u8; 88] = [
  1392. 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,
  1393. 0, 0, 0, 0, 0, 0, 0, 0, 0x14, 5, 0x20, 0x68, 0xb0, 0xf8, 3, 3, 2, 2, 0x24, 0x24, 0x24,
  1394. 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,
  1395. 0x20, 0x68, 0xb0, 0xf8, 0x24, 0x24, 0x24, 0x24, 0, 0, 0, 0, 0, 0, 0, 0,
  1396. ];
  1397. /// What `BC4_STREAM` unpacks to.
  1398. fn bc4_blocks() -> [u8; 16] {
  1399. let code = [0u64, 2, 3, 4, 5, 6, 7, 1];
  1400. let block = |e0: u64, e1: u64, add: usize| {
  1401. let bits = (0..16).fold(0, |a, p| a | code[(p + add) & 7] << (16 + 3 * p));
  1402. (e0 | e1 << 8 | bits).to_le_bytes()
  1403. };
  1404. let mut out = [0; 16];
  1405. out[..8].copy_from_slice(&block(138, 125, 0));
  1406. out[8..].copy_from_slice(&block(139, 126, 1));
  1407. out
  1408. }
  1409. #[test]
  1410. fn bcpack_requests_unpack_into_the_destination() {
  1411. with_test_tables();
  1412. let mut contents = pattern(100);
  1413. contents.extend_from_slice(&BC4_STREAM);
  1414. let (_dir, file) = file_with(&contents);
  1415. let (queue, array) = (new_queue(0), status_array(1));
  1416. let mut out = [0u8; 16];
  1417. enqueue(queue, &request(4 << 1, out.as_mut_ptr().cast(), 16, file, 100, 88));
  1418. enqueue_status(queue, array, 0);
  1419. void(queue, 0x30);
  1420. assert_eq!(wait(array, 0), S_OK);
  1421. assert_eq!(out, bc4_blocks());
  1422. }
  1423. #[test]
  1424. fn a_closed_queue_completes_nothing() {
  1425. let (_dir, file) = file_with(&pattern(64));
  1426. let (queue, array) = (new_queue(0), status_array(1));
  1427. let mut out = [0u8; 16];
  1428. enqueue(queue, &request(0, out.as_mut_ptr().cast(), 16, file, 0, 16));
  1429. enqueue_status(queue, array, 0);
  1430. void(queue, 0x40);
  1431. void(queue, 0x30);
  1432. std::thread::sleep(Duration::from_millis(50));
  1433. assert_eq!(result(array, 0), E_PENDING);
  1434. assert_eq!(out, [0; 16]);
  1435. }
  1436. #[test]
  1437. fn physical_page_destinations() {
  1438. use crate::modules::xmem;
  1439. let mut pages = [0usize; 2];
  1440. let mut n = 2;
  1441. assert_eq!(
  1442. xmem::XMemAllocatePhysicalPages(0, &mut n, pages.as_mut_ptr()),
  1443. 1
  1444. );
  1445. // Where the title would see them: a reservation of 64 KiB pages.
  1446. let mapped = xmem::XMemVirtualAlloc(
  1447. std::ptr::null_mut(),
  1448. 2 * PAGE,
  1449. 0x2000 | 0x2040_0000, // reserve, 64 KiB pages
  1450. 0,
  1451. 0x04,
  1452. );
  1453. assert!(!mapped.is_null());
  1454. assert_eq!(
  1455. xmem::XMemMapPhysicalPages(mapped, 2, pages.as_ptr()),
  1456. mapped
  1457. );
  1458. let plain = pattern(100);
  1459. let (queue, array) = (new_queue(1), status_array(1));
  1460. let mut r = request(
  1461. PAGE_DESTINATION | MEMORY_SOURCE,
  1462. pages.as_mut_ptr().cast(),
  1463. plain.len(),
  1464. plain.as_ptr().cast(),
  1465. 0,
  1466. plain.len(),
  1467. );
  1468. r.page_offset = (PAGE - 40) as u64; // across the page boundary
  1469. enqueue(queue, &r);
  1470. enqueue_status(queue, array, 0);
  1471. void(queue, 0x30);
  1472. assert_eq!(wait(array, 0), S_OK);
  1473. // SAFETY: both pages are mapped read-write.
  1474. let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>().add(PAGE - 40), 100) };
  1475. assert_eq!(seen, plain);
  1476. }
  1477. #[test]
  1478. fn zlib_into_pages_in_place_and_across_allocations() {
  1479. use crate::modules::xmem;
  1480. let allocate = |n: usize| {
  1481. let (mut pages, mut given) = (vec![0usize; n], n);
  1482. assert_eq!(
  1483. xmem::XMemAllocatePhysicalPages(0, &mut given, pages.as_mut_ptr()),
  1484. 1
  1485. );
  1486. pages
  1487. };
  1488. let (a, b) = (allocate(3), allocate(1));
  1489. let plain = pattern(2 * PAGE + 100);
  1490. let packed = compress_zlib(&plain);
  1491. // One allocation's pages in order (one window), then pages of two
  1492. // (through a buffer), both from 50 bytes into the first.
  1493. let mut destinations = [a.clone(), vec![a[0], a[1], b[0]]];
  1494. let (queue, array) = (new_queue(1), status_array(1));
  1495. for pages in &mut destinations {
  1496. let mut r = request(
  1497. ZLIB | PAGE_DESTINATION | MEMORY_SOURCE,
  1498. pages.as_mut_ptr().cast(),
  1499. plain.len(),
  1500. packed.as_ptr().cast(),
  1501. 0,
  1502. packed.len(),
  1503. );
  1504. r.page_offset = 50;
  1505. enqueue(queue, &r);
  1506. }
  1507. enqueue_status(queue, array, 0);
  1508. void(queue, 0x30);
  1509. assert_eq!(wait(array, 0), S_OK);
  1510. for pages in &destinations {
  1511. let mapped = xmem::XMemVirtualAlloc(
  1512. std::ptr::null_mut(),
  1513. 3 * PAGE,
  1514. 0x2000 | 0x2040_0000, // reserve, 64 KiB pages
  1515. 0,
  1516. 0x04,
  1517. );
  1518. assert!(!mapped.is_null());
  1519. assert_eq!(
  1520. xmem::XMemMapPhysicalPages(mapped, 3, pages.as_ptr()),
  1521. mapped
  1522. );
  1523. // SAFETY: all three pages are mapped read-write.
  1524. let seen = unsafe { std::slice::from_raw_parts(mapped.cast::<u8>(), 3 * PAGE) };
  1525. assert!(seen[..50].iter().all(|&b| b == 0));
  1526. assert_eq!(seen[50..50 + plain.len()], plain);
  1527. assert_eq!(
  1528. xmem::XMemMapPhysicalPages(mapped, 3, std::ptr::null()),
  1529. mapped
  1530. );
  1531. }
  1532. assert_eq!(xmem::XMemFreePhysicalPages(3, a.as_ptr()), 1);
  1533. assert_eq!(xmem::XMemFreePhysicalPages(1, b.as_ptr()), 1);
  1534. }
  1535. #[test]
  1536. fn zlib_inflate_handles_short_exact_empty_and_bad_streams() {
  1537. let plain = pattern(65_537);
  1538. let packed = compress_zlib(&plain);
  1539. // Exact fit.
  1540. let mut exact = vec![0u8; plain.len()];
  1541. assert_eq!(inflate(&packed, &mut exact), Ok(plain.len()));
  1542. assert_eq!(exact, plain);
  1543. // Short stream into a larger buffer passes and returns bytes written;
  1544. // guard bytes outside the slice passed to `inflate` stay untouched.
  1545. let mut larger = vec![0xAA; plain.len() + 64];
  1546. assert_eq!(
  1547. inflate(&packed, &mut larger[..plain.len() + 32]),
  1548. Ok(plain.len())
  1549. );
  1550. assert_eq!(&larger[..plain.len()], &plain[..]);
  1551. assert!(larger[plain.len() + 32..].iter().all(|&b| b == 0xAA));
  1552. // Empty valid stream passes for empty or non-empty destinations.
  1553. let empty = compress_zlib(&[]);
  1554. assert_eq!(inflate(&empty, &mut []), Ok(0));
  1555. let mut scratch = [0x55u8; 4];
  1556. assert_eq!(inflate(&empty, &mut scratch), Ok(0));
  1557. // Oversized stream (destination too small, including empty) fails.
  1558. let mut small = vec![0u8; plain.len() - 1];
  1559. assert_eq!(inflate(&packed, &mut small), Err(INVALID_DATA));
  1560. assert_eq!(inflate(&packed, &mut []), Err(INVALID_DATA));
  1561. // Truncated stream (missing trailer or payload bytes) fails.
  1562. let mut out = vec![0u8; plain.len()];
  1563. assert_eq!(
  1564. inflate(&packed[..packed.len() - 1], &mut out),
  1565. Err(INVALID_DATA)
  1566. );
  1567. assert_eq!(
  1568. inflate(&packed[..packed.len() / 2], &mut out),
  1569. Err(INVALID_DATA)
  1570. );
  1571. assert_eq!(inflate(&[], &mut out), Err(INVALID_DATA));
  1572. // Corrupt Adler-32 trailer fails.
  1573. let mut bad_adler = packed.clone();
  1574. *bad_adler.last_mut().unwrap() ^= 1;
  1575. assert_eq!(inflate(&bad_adler, &mut out), Err(INVALID_DATA));
  1576. // Corrupt header/payload fails, and subsequent valid inflate on the
  1577. // same thread still succeeds (verifies thread-local state reset).
  1578. let mut bad_body = packed.clone();
  1579. bad_body[2] ^= 0xFF;
  1580. assert_eq!(inflate(&bad_body, &mut out), Err(INVALID_DATA));
  1581. assert_eq!(inflate(&packed, &mut out), Ok(plain.len()));
  1582. assert_eq!(out, plain);
  1583. }
  1584. }