pipeline.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. //! Pipeline states. Both descriptions start as on PC: the root signature,
  2. //! then the shader stages (five for graphics, one for compute); streams
  3. //! carry the rest of the graphics state as subobjects of the standard
  4. //! types.
  5. //!
  6. //! Host pipelines are made on a pipeline's first draw, not at creation:
  7. //! The title creates some 60,000 pipelines in its first 20
  8. //! seconds and draws with a few dozen (decision 0007, step 3). Shader
  9. //! containers are shared by content hash and translated once, on first
  10. //! use (decision 0003).
  11. //!
  12. //! shortcut: only vertex plus pixel pipelines from streams and compute
  13. //! pipelines get host pipelines; mesh, tessellation and geometry stages,
  14. //! and the plain graphics description, keep their containers only. The 32-byte
  15. //! packet after the header stays zero: titles only copy it inline, which
  16. //! our null command-list limits keep from running.
  17. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  18. use std::collections::HashMap;
  19. use std::mem::offset_of;
  20. use std::sync::{Arc, Mutex, OnceLock};
  21. use crate::object::{self, E_INVALIDARG, HRESULT, Iid, Object, PIPELINE, Table, This, guid};
  22. use crate::resource::PAGEABLE_IIDS;
  23. const PIPELINE_IIDS: [Iid; 4] = [
  24. guid(
  25. 0x765a30f3,
  26. 0xf624,
  27. 0x4c6f,
  28. [0xa8, 0x28, 0xac, 0xe9, 0x48, 0x62, 0x24, 0x45],
  29. ),
  30. PAGEABLE_IIDS[0],
  31. PAGEABLE_IIDS[1],
  32. PAGEABLE_IIDS[2],
  33. ];
  34. #[repr(C)]
  35. pub(crate) struct Bytecode {
  36. code: *const u8,
  37. size: usize,
  38. }
  39. #[repr(C)]
  40. pub(crate) struct GraphicsHead {
  41. root: This,
  42. /// Vertex, pixel, domain, hull, geometry.
  43. stages: [Bytecode; 5],
  44. }
  45. #[repr(C)]
  46. pub(crate) struct ComputeHead {
  47. root: This,
  48. stage: Bytecode,
  49. }
  50. /// A shader container a title passed, shared by every pipeline with the
  51. /// same bytes.
  52. pub(crate) struct Shader {
  53. pub(crate) stage: &'static str,
  54. /// The first 8 bytes of its BLAKE3, as logged.
  55. pub(crate) hash: String,
  56. container: Vec<u8>,
  57. #[cfg(windows)]
  58. translated: OnceLock<Option<Translated>>,
  59. }
  60. impl std::fmt::Debug for Shader {
  61. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  62. write!(f, "{} {}", self.stage, self.hash)
  63. }
  64. }
  65. /// Every container seen, by full content hash.
  66. static SHADERS: Mutex<Option<HashMap<[u8; 32], Arc<Shader>>>> = Mutex::new(None);
  67. /// For the memory lines: containers kept and their bytes, translations
  68. /// kept and the bytes of their host code. None of them is ever let go.
  69. static KEPT: [std::sync::atomic::AtomicU64; 4] = [const { std::sync::atomic::AtomicU64::new(0) }; 4];
  70. /// What the shader table and the pipeline library keep in memory:
  71. /// containers and their bytes, translations and their bytes, the bytes of
  72. /// the library's file (kept whole while the library lives) and what its
  73. /// last save wrote.
  74. #[cfg(windows)]
  75. #[cfg_attr(not(feature = "diagnostics"), allow(dead_code))]
  76. pub(crate) fn kept() -> [u64; 7] {
  77. use std::sync::atomic::Ordering::Relaxed;
  78. [
  79. KEPT[0].load(Relaxed),
  80. KEPT[1].load(Relaxed),
  81. KEPT[2].load(Relaxed),
  82. KEPT[3].load(Relaxed),
  83. library::BLOB.load(Relaxed),
  84. library::SAVED.load(Relaxed),
  85. library::TRIMMED_BYTES.load(Relaxed),
  86. ]
  87. }
  88. /// The shared container for `bytes`.
  89. fn shader(stage: &'static str, bytes: &[u8]) -> Arc<Shader> {
  90. let full = blake3::hash(bytes);
  91. let mut shaders = SHADERS.lock().unwrap_or_else(|e| e.into_inner());
  92. shaders
  93. .get_or_insert_with(HashMap::new)
  94. .entry(*full.as_bytes())
  95. .or_insert_with(|| {
  96. KEPT[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  97. KEPT[1].fetch_add(bytes.len() as u64, std::sync::atomic::Ordering::Relaxed);
  98. Arc::new(Shader {
  99. stage,
  100. hash: full.to_hex()[..16].to_owned(),
  101. container: bytes.to_vec(),
  102. #[cfg(windows)]
  103. translated: OnceLock::new(),
  104. })
  105. })
  106. .clone()
  107. }
  108. /// A translated shader and the console resources its code reads.
  109. #[cfg(windows)]
  110. pub(crate) struct Translated {
  111. pub(crate) host: victory_shader::emit::HostShader,
  112. pub(crate) used: Vec<victory_shader::UsedResource>,
  113. /// Whether the shader's code can store to buffer memory ([`stores`]);
  114. /// true when its code is not known.
  115. pub(crate) stores: bool,
  116. /// Whether it can store through raw addresses ([`stores_by_address`]).
  117. pub(crate) stores_by_address: bool,
  118. /// Whether it stores through a view it picks from the heap by an index,
  119. /// once asked (`crate::picked`).
  120. pub(crate) picks: std::sync::atomic::AtomicU8,
  121. }
  122. #[cfg(windows)]
  123. impl Shader {
  124. /// The translation, made on first use; a shader that does not
  125. /// translate is logged once.
  126. pub(crate) fn translated(&self) -> Option<&Translated> {
  127. self.translated
  128. .get_or_init(|| {
  129. let done = translate(&self.container);
  130. // `VICTORY_SHADER_SAVE=<dir>`: each shader as the title gave it (`.cdxil`) and as
  131. // translated (`.dxil`), by the hash crash reports name it with
  132. if let Some(dir) = std::env::var_os("VICTORY_SHADER_SAVE") {
  133. let dir = std::path::PathBuf::from(dir);
  134. let _ = std::fs::create_dir_all(&dir);
  135. let stem = format!("{}.{}", self.hash, self.stage);
  136. let _ = std::fs::write(dir.join(format!("{stem}.cdxil")), &self.container);
  137. if let Ok(t) = &done {
  138. let _ = std::fs::write(dir.join(format!("{stem}.dxil")), &t.host.dxil);
  139. }
  140. }
  141. if let Ok(t) = &done {
  142. KEPT[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
  143. KEPT[3].fetch_add(t.host.dxil.len() as u64, std::sync::atomic::Ordering::Relaxed);
  144. }
  145. match &done {
  146. Ok(t) => tracing::info!(
  147. stage = self.stage,
  148. hash = %self.hash,
  149. user_data = t.host.user_data.len(),
  150. samplers = t.host.samplers.len(),
  151. "shader translated"
  152. ),
  153. Err(e) => tracing::warn!(
  154. stage = self.stage,
  155. hash = %self.hash,
  156. error = %e,
  157. "shader does not translate; its pipelines' draws are dropped"
  158. ),
  159. }
  160. done.ok()
  161. })
  162. .as_ref()
  163. }
  164. }
  165. #[cfg(windows)]
  166. impl Shader {
  167. /// The console programs of the container; `None` if they are not known.
  168. pub(crate) fn programs(&self) -> Option<Vec<victory_shader::NativeProgram>> {
  169. use victory_shader::{Container, FourCC};
  170. let c = Container::parse(&self.container).ok()?;
  171. let part = c.part(FourCC::DXIL).or(c.part(FourCC::ACCC))?;
  172. victory_shader::native_programs(part.data).ok()
  173. }
  174. }
  175. #[cfg(windows)]
  176. fn translate(container: &[u8]) -> Result<Translated, String> {
  177. use victory_shader::{Container, FourCC, HwStage};
  178. // The translation depends on it (a view index past a capped heap).
  179. crate::descriptor::host::probe_view_limit();
  180. let c = Container::parse(container).map_err(|e| e.to_string())?;
  181. let programs = match c.part(FourCC::DXIL).or(c.part(FourCC::ACCC)) {
  182. Some(part) => victory_shader::native_programs(part.data).map_err(|e| e.to_string())?,
  183. None => Vec::new(),
  184. };
  185. let host = crate::shader_cache::host_shader(container)?;
  186. let stores = programs.is_empty() || programs.iter().any(stores);
  187. let stores_by_address = programs.is_empty() || programs.iter().any(stores_by_address);
  188. let used = programs
  189. .into_iter()
  190. .find(|p| {
  191. matches!(
  192. p.stage,
  193. HwStage::Vs | HwStage::Ps | HwStage::Ms | HwStage::Cs
  194. )
  195. })
  196. .map(|p| p.used)
  197. .unwrap_or_default();
  198. Ok(Translated {
  199. host,
  200. used,
  201. stores,
  202. stores_by_address,
  203. picks: Default::default(),
  204. })
  205. }
  206. /// The compute pipelines of the console's ray-tracing structure builder
  207. /// (`XboxBvhBuilder.dll`; its programs are the ones with a spilled
  208. /// user-data table) run **all or none**. Its stages feed each other
  209. /// through memory: a stage that runs on what a dropped stage never wrote
  210. /// computes its store offsets from garbage. The structures lie in plain
  211. /// title memory, between the title's own objects, and a root view has no
  212. /// size, so those stores land on the neighbours (run 98, with 14 of 35
  213. /// stages translated: the title died within a second of the first builder
  214. /// submission, on pointers that had become bounding-box bit patterns).
  215. ///
  216. /// So a builder dispatch runs only while every builder pipeline the title
  217. /// has created has a host pipeline; the first builder dispatch makes them
  218. /// all on the spot instead of over the next frames (a stage "still being
  219. /// made" would be a dropped stage). One that cannot be made turns the
  220. /// builder off for the rest of the run.
  221. ///
  222. /// shortcut: and only with `VICTORY_BVH_BUILDER=1`, until a run has shown
  223. /// the whole builder and the host side of title memory by address
  224. /// (`memory.rs`) working on a card; nothing reads the structures before
  225. /// the programs that walk them translate.
  226. #[cfg(windows)]
  227. struct Builder {
  228. pipelines: Vec<Arc<make::Pending>>,
  229. /// Every one of `pipelines` has a host pipeline.
  230. whole: bool,
  231. /// One could not be made.
  232. off: bool,
  233. }
  234. #[cfg(windows)]
  235. static BUILDER: Mutex<Builder> = Mutex::new(Builder {
  236. pipelines: Vec::new(),
  237. whole: false,
  238. off: false,
  239. });
  240. /// Whether `shaders` are a pipeline of the structure builder.
  241. #[cfg(windows)]
  242. fn of_builder(shaders: &[Arc<Shader>]) -> bool {
  243. use victory_shader::{Container, FourCC};
  244. let [shader] = shaders else { return false };
  245. if shader.stage != "compute" {
  246. return false;
  247. }
  248. let Ok(c) = Container::parse(&shader.container) else {
  249. return false;
  250. };
  251. c.part(FourCC::DXIL)
  252. .and_then(|part| victory_shader::native_programs(part.data).ok())
  253. .is_some_and(|programs| programs.iter().any(victory_shader::spill::is_spilled))
  254. }
  255. /// `VICTORY_BVH_QUARANTINE=1`: what the structure builder's stages store
  256. /// stays in the host's copies and is not copied back into title memory. A
  257. /// check for a first run of the whole builder: a stage that stores where
  258. /// it should not can then not reach the title's own objects (run 98), and
  259. /// the programs that walk the structures read the host's copies anyway.
  260. /// shortcut: not a way to run: the title also reads results back (sizes,
  261. /// counters) and gets none, and a copy's pages are overwritten from title
  262. /// memory when the title writes them.
  263. #[cfg(windows)]
  264. pub(crate) fn builder_quarantined(this: This) -> bool {
  265. static ON: OnceLock<bool> = OnceLock::new();
  266. is_builder(this) && *ON.get_or_init(|| std::env::var_os("VICTORY_BVH_QUARANTINE").is_some_and(|v| v == "1"))
  267. }
  268. /// Whether the title's pipeline `this` is one of the structure builder's.
  269. #[cfg(windows)]
  270. pub(crate) fn is_builder(this: This) -> bool {
  271. !this.is_null() && pipeline(this).builder
  272. }
  273. /// A stage of the builder was dropped after all: none runs from here on.
  274. #[cfg(windows)]
  275. pub(crate) fn builder_off(why: &'static str) {
  276. let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
  277. if !b.off {
  278. b.off = true;
  279. tracing::warn!(why, "the ray-tracing structure builder is turned off for the rest of the run: its stages run all or none");
  280. }
  281. }
  282. /// At a dispatch of a builder pipeline: whether the builder runs (see
  283. /// [`Builder`]).
  284. #[cfg(windows)]
  285. pub(crate) fn builder_runs() -> bool {
  286. static ALLOWED: OnceLock<bool> = OnceLock::new();
  287. if !*ALLOWED.get_or_init(|| std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1")) {
  288. return false;
  289. }
  290. let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
  291. if b.off {
  292. return false;
  293. }
  294. if b.whole {
  295. return true;
  296. }
  297. let missing = b.pipelines.iter().filter(|p| !make::now(p)).count();
  298. if missing > 0 {
  299. b.off = true;
  300. tracing::warn!(
  301. missing,
  302. of = b.pipelines.len(),
  303. "the ray-tracing structure builder stays off: not all of its programs have a host pipeline, and its stages run all or none"
  304. );
  305. return false;
  306. }
  307. tracing::info!(
  308. pipelines = b.pipelines.len(),
  309. "the ray-tracing structure builder runs: all of its programs have host pipelines"
  310. );
  311. b.whole = true;
  312. true
  313. }
  314. /// Whether a console program can store to buffer memory: it has a buffer,
  315. /// typed-buffer, scalar-memory, flat or global store or atomic, or code
  316. /// that is not all known (an instruction of those kinds outside our table,
  317. /// an indirect jump, code that does not decode). Stores to textures
  318. /// (image instructions) and to the program's own scratch memory do not
  319. /// count: neither reaches a buffer's host copy. After upstream #413,
  320. /// which leaves scalar-memory stores out and counts image stores.
  321. #[cfg(windows)]
  322. fn stores(program: &victory_shader::NativeProgram) -> bool {
  323. use victory_shader::gfx10::{Encoding, decode};
  324. let Ok(code) = decode(&program.code) else {
  325. return true;
  326. };
  327. code.iter().any(|i| {
  328. let name = i.name();
  329. match i.encoding {
  330. Encoding::Mubuf
  331. | Encoding::Mtbuf
  332. | Encoding::Smem
  333. | Encoding::Flat
  334. | Encoding::Global => name.is_none_or(|n| {
  335. (n.contains("store") || n.contains("atomic")) && !n.contains("scratch")
  336. }),
  337. Encoding::Sop1 => name.is_none_or(|n| matches!(n, "s_setpc_b64" | "s_swappc_b64")),
  338. _ => false,
  339. }
  340. })
  341. }
  342. /// Whether a console program can store to memory through raw addresses
  343. /// (`crate::memory`): a flat or global store or atomic, or code that does
  344. /// not decode. The programs that only walk ray-tracing structures do not,
  345. /// whatever they store through views.
  346. #[cfg(windows)]
  347. fn stores_by_address(program: &victory_shader::NativeProgram) -> bool {
  348. use victory_shader::gfx10::{Encoding, decode};
  349. let Ok(code) = decode(&program.code) else {
  350. return true;
  351. };
  352. code.iter().any(|i| {
  353. matches!(i.encoding, Encoding::Flat | Encoding::Global)
  354. && i.name()
  355. .is_none_or(|n| (n.contains("store") || n.contains("atomic")) && !n.contains("scratch"))
  356. })
  357. }
  358. #[repr(C)]
  359. struct Pipeline {
  360. object: Object,
  361. packet: [u32; 8],
  362. /// Each used stage's container.
  363. shaders: Vec<Arc<Shader>>,
  364. /// Whether a list has bound it yet (its shaders are logged then).
  365. bound: std::sync::atomic::AtomicBool,
  366. /// What its host pipeline is made from, and the host pipeline once made
  367. /// (by a worker: the title may release the pipeline meanwhile).
  368. #[cfg(windows)]
  369. host: Arc<make::Pending>,
  370. /// One of the ray-tracing structure builder's ([`Builder`]).
  371. #[cfg(windows)]
  372. builder: bool,
  373. }
  374. const _: () = assert!(offset_of!(Pipeline, packet) == 0x10);
  375. /// Stage names, in description order.
  376. const GRAPHICS_STAGES: [&str; 5] = ["vertex", "pixel", "domain", "hull", "geometry"];
  377. fn pipeline<'a>(this: This) -> &'a Pipeline {
  378. // SAFETY: the title passes one of our pipelines.
  379. unsafe { &*this.cast::<Pipeline>() }
  380. }
  381. /// List method: logs each pipeline's shaders the first time a list binds
  382. /// it, so a run lists the shaders its frames need first.
  383. pub(crate) fn bound(this: This) {
  384. if this.is_null() {
  385. return;
  386. }
  387. let p = pipeline(this);
  388. if p.bound.swap(true, std::sync::atomic::Ordering::Relaxed) {
  389. return;
  390. }
  391. let frame = crate::frame::current();
  392. for shader in &p.shaders {
  393. tracing::info!(pipeline = ?this, frame, stage = shader.stage, size = shader.container.len(), hash = %shader.hash, "first bind");
  394. }
  395. }
  396. /// The host pipeline of a title pipeline; `None` if one of its shaders does
  397. /// not translate, the host refuses it, or it is still being made (its first
  398. /// use starts that, see [`make`]).
  399. #[cfg(windows)]
  400. pub(crate) fn host_pipeline<'a>(this: This) -> Option<&'a host::HostPipeline> {
  401. if this.is_null() {
  402. return None;
  403. }
  404. make::ready(&pipeline(this).host)
  405. }
  406. /// Host pipelines queued and not made yet.
  407. #[cfg(windows)]
  408. pub(crate) fn making() -> u64 {
  409. make::waiting()
  410. }
  411. /// Draws and dispatches dropped since the last [`take_drops`], by reason
  412. /// (diagnostics).
  413. #[cfg(all(windows, feature = "diagnostics"))]
  414. static DROPS: Mutex<Option<HashMap<String, u64>>> = Mutex::new(None);
  415. /// Shader hashes as printed in the pipeline diagnostics.
  416. #[cfg(all(windows, feature = "diagnostics"))]
  417. fn parse_skip_hashes(value: &str) -> Vec<String> {
  418. value
  419. .split(',')
  420. .map(str::trim)
  421. .filter(|hash| !hash.is_empty())
  422. .filter_map(|hash| {
  423. if hash.len() == 16 && hash.bytes().all(|byte| byte.is_ascii_hexdigit()) {
  424. Some(hash.to_ascii_lowercase())
  425. } else {
  426. tracing::warn!(
  427. hash,
  428. "VICTORY_SKIP_PIPELINES expects 16-digit shader hashes"
  429. );
  430. None
  431. }
  432. })
  433. .collect()
  434. }
  435. #[cfg(all(windows, feature = "diagnostics"))]
  436. fn skipped_shader(p: &Pipeline) -> Option<&str> {
  437. static HASHES: OnceLock<Vec<String>> = OnceLock::new();
  438. let hashes = HASHES.get_or_init(|| {
  439. let value = std::env::var("VICTORY_SKIP_PIPELINES").unwrap_or_default();
  440. parse_skip_hashes(&value)
  441. });
  442. if hashes.is_empty() {
  443. return None;
  444. }
  445. p.shaders
  446. .iter()
  447. .find(|shader| hashes.contains(&shader.hash))
  448. .map(|shader| shader.hash.as_str())
  449. }
  450. #[cfg(all(windows, feature = "diagnostics"))]
  451. pub(crate) fn is_skipped(this: This) -> bool {
  452. !this.is_null() && skipped_shader(pipeline(this)).is_some()
  453. }
  454. /// Counts a draw or dispatch of `this` intentionally skipped or dropped
  455. /// for want of a host pipeline (diagnostics).
  456. #[cfg(all(windows, feature = "diagnostics"))]
  457. pub(crate) fn note_drop(this: This) {
  458. let why = if this.is_null() {
  459. Some("no pipeline set".to_owned())
  460. } else {
  461. let p = pipeline(this);
  462. skipped_shader(p)
  463. .map(|hash| format!("skipped shader {hash}"))
  464. .or_else(|| make::missing(&p.host))
  465. };
  466. if let Some(why) = why {
  467. note_why(why);
  468. }
  469. }
  470. /// Counts a draw or dispatch dropped for `why` (diagnostics).
  471. #[cfg(all(windows, feature = "diagnostics"))]
  472. pub(crate) fn note_why(why: String) {
  473. crate::capture::op(0, || format!("DROPPED {why}"));
  474. let mut drops = DROPS.lock().unwrap_or_else(|e| e.into_inner());
  475. *drops.get_or_insert_with(HashMap::new).entry(why).or_default() += 1;
  476. }
  477. /// The drops counted since the last call, most first (diagnostics).
  478. #[cfg(all(windows, feature = "diagnostics"))]
  479. pub(crate) fn take_drops() -> Vec<(String, u64)> {
  480. let drops = DROPS.lock().unwrap_or_else(|e| e.into_inner()).take();
  481. let mut drops: Vec<(String, u64)> = drops.into_iter().flatten().collect();
  482. // Frame reports only show the first 40 reasons. Keep ties ordered so
  483. // a HashMap iteration order change cannot change which reasons appear.
  484. drops.sort_unstable_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
  485. drops
  486. }
  487. /// The stage's container, if it has one.
  488. fn copy(stage: &'static str, code: &Bytecode) -> Option<Arc<Shader>> {
  489. if code.code.is_null() || code.size == 0 {
  490. return None;
  491. }
  492. // SAFETY: the title passes `size` bytes of shader code.
  493. Some(shader(stage, unsafe {
  494. std::slice::from_raw_parts(code.code, code.size)
  495. }))
  496. }
  497. fn hand_out(
  498. shaders: Vec<Arc<Shader>>,
  499. #[cfg(windows)] graphics: Option<Box<host::GraphicsState>>,
  500. iid: *const Iid,
  501. out: *mut This,
  502. ) -> HRESULT {
  503. tracing::trace!(?shaders, "pipeline state");
  504. #[cfg(windows)]
  505. let host = Arc::new(make::Pending::new(shaders.clone(), graphics));
  506. #[cfg(windows)]
  507. make::early(&host);
  508. #[cfg(windows)]
  509. let builder = of_builder(&shaders);
  510. #[cfg(windows)]
  511. if builder {
  512. // Another stage: the group is looked at again at its next dispatch.
  513. let mut b = BUILDER.lock().unwrap_or_else(|e| e.into_inner());
  514. b.pipelines.push(host.clone());
  515. b.whole = false;
  516. }
  517. let pipeline = Box::new(Pipeline {
  518. object: Object::new(&FUNCTIONS),
  519. packet: [0; 8],
  520. #[cfg(windows)]
  521. host,
  522. #[cfg(windows)]
  523. builder,
  524. shaders,
  525. bound: std::sync::atomic::AtomicBool::new(false),
  526. });
  527. object::hand_out(PIPELINE, pipeline, iid, &PIPELINE_IIDS, out)
  528. }
  529. /// Device method.
  530. pub(crate) extern "system" fn create_graphics(
  531. _: This,
  532. desc: *const GraphicsHead,
  533. iid: *const Iid,
  534. out: *mut This,
  535. ) -> HRESULT {
  536. // SAFETY: the title passes a description (null is tolerated).
  537. let Some(desc) = (unsafe { desc.as_ref() }) else {
  538. return E_INVALIDARG;
  539. };
  540. let stages = GRAPHICS_STAGES.iter().zip(&desc.stages);
  541. let shaders = stages.filter_map(|(s, c)| copy(s, c)).collect();
  542. hand_out(
  543. shaders,
  544. #[cfg(windows)]
  545. None,
  546. iid,
  547. out,
  548. )
  549. }
  550. /// Device method.
  551. pub(crate) extern "system" fn create_compute(
  552. _: This,
  553. desc: *const ComputeHead,
  554. iid: *const Iid,
  555. out: *mut This,
  556. ) -> HRESULT {
  557. // SAFETY: the title passes a description (null is tolerated).
  558. let Some(desc) = (unsafe { desc.as_ref() }) else {
  559. return E_INVALIDARG;
  560. };
  561. hand_out(
  562. copy("compute", &desc.stage).into_iter().collect(),
  563. #[cfg(windows)]
  564. None,
  565. iid,
  566. out,
  567. )
  568. }
  569. /// Device method 0x1f0: the plain compute description plus console
  570. /// extensions `(desc, extension count, extensions, iid, out)`.
  571. /// shortcut: the extensions (console shader settings) are ignored, as is
  572. /// the rest of the description.
  573. pub(crate) extern "system" fn create_compute_x(
  574. this: This,
  575. desc: *const ComputeHead,
  576. _extensions: u32,
  577. _extended: *const u8,
  578. iid: *const Iid,
  579. out: *mut This,
  580. ) -> HRESULT {
  581. create_compute(this, desc, iid, out)
  582. }
  583. /// A pipeline described as a stream: its size and the subobjects, each a
  584. /// type then its data, padded to 8 bytes.
  585. #[repr(C)]
  586. pub(crate) struct StreamDesc {
  587. size: usize,
  588. stream: *const u8,
  589. }
  590. /// A subobject type's size (type included), and the stage it is if it is a
  591. /// shader. The console numbers amplification and mesh shaders 23 and 24
  592. /// (PC: 24 and 25); its own types from 25 on are not sized yet.
  593. fn subobject(kind: u32) -> Option<(usize, Option<&'static str>)> {
  594. let stage = |name| Some((24, Some(name)));
  595. match kind {
  596. 1 => stage("vertex"),
  597. 2 => stage("pixel"),
  598. 3 => stage("domain"),
  599. 4 => stage("hull"),
  600. 5 => stage("geometry"),
  601. 6 => stage("compute"),
  602. 23 => stage("amplification"),
  603. 24 => stage("mesh"),
  604. 0 => Some((16, None)),
  605. 12 | 19 => Some((24, None)),
  606. 7 | 15 => Some((40, None)),
  607. 8 => Some((336, None)),
  608. 10 => Some((48, None)),
  609. 11 => Some((56, None)),
  610. 17 => Some((16, None)),
  611. 21 => Some((64, None)),
  612. 22 => Some((32, None)),
  613. 9 | 13 | 14 | 16 | 18 | 20 => Some((8, None)),
  614. _ => None,
  615. }
  616. }
  617. /// Device method: a pipeline from a stream; the shaders are kept, and the
  618. /// graphics state for the host pipeline.
  619. pub(crate) extern "system" fn create_stream(
  620. _: This,
  621. desc: *const StreamDesc,
  622. iid: *const Iid,
  623. out: *mut This,
  624. ) -> HRESULT {
  625. // SAFETY: the title passes a description (null is tolerated).
  626. let Some(desc) = (unsafe { desc.as_ref() }) else {
  627. return E_INVALIDARG;
  628. };
  629. if desc.stream.is_null() {
  630. return E_INVALIDARG;
  631. }
  632. let mut shaders = Vec::new();
  633. #[cfg(windows)]
  634. let mut graphics = host::GraphicsState::default();
  635. let mut at = 0;
  636. while at + 8 <= desc.size {
  637. // SAFETY: inside the stream the title passes.
  638. let kind = unsafe { desc.stream.add(at).cast::<u32>().read_unaligned() };
  639. let Some((size, stage)) = subobject(kind) else {
  640. tracing::warn!(
  641. kind,
  642. at,
  643. "pipeline subobject of unknown size; the rest is ignored"
  644. );
  645. break;
  646. };
  647. if let Some(stage) = stage {
  648. // SAFETY: a shader subobject has its bytecode at +8.
  649. let code = unsafe { &*desc.stream.add(at + 8).cast::<Bytecode>() };
  650. shaders.extend(copy(stage, code));
  651. }
  652. #[cfg(windows)]
  653. // SAFETY: a whole subobject of this kind lies at `at`.
  654. unsafe {
  655. graphics.read(kind, desc.stream.add(at))
  656. };
  657. at += size;
  658. }
  659. hand_out(
  660. shaders,
  661. #[cfg(windows)]
  662. Some(Box::new(graphics)),
  663. iid,
  664. out,
  665. )
  666. }
  667. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  668. let found = object::is(iid, &PIPELINE_IIDS).then_some(this);
  669. object::answer(PIPELINE, iid, found, out)
  670. }
  671. extern "system" fn release(this: This) -> u32 {
  672. object::release_boxed::<Pipeline>(this)
  673. }
  674. /// IUnknown 3, object 4, device child 1, pipeline 3.
  675. static FUNCTIONS: Table<24> = {
  676. let mut f = object::d3d12_object(object::missing_table::<PIPELINE, 24>());
  677. f[0] = query as *const ();
  678. f[2] = release as *const ();
  679. f[7] = object::parent_device as *const (); // 0x38
  680. Table(f)
  681. };
  682. #[cfg(windows)]
  683. pub(crate) mod host;
  684. #[cfg(windows)]
  685. mod library;
  686. #[cfg(windows)]
  687. mod make;
  688. /// Lets the pipeline library's mapped file go from memory when no pipeline
  689. /// has loaded for a while (`library::trim`); called by the host's sweep.
  690. #[cfg(windows)]
  691. pub(crate) fn trim_library() {
  692. library::trim();
  693. }
  694. /// The pipeline library's part of the report when the host device is
  695. /// removed (`library::removal_note`).
  696. #[cfg(windows)]
  697. pub(crate) fn library_removal_note() -> String {
  698. library::removal_note()
  699. }
  700. /// Keeps compiled host pipelines, and the list of title pipelines to start
  701. /// early, in `dir` (a folder of the cache) across runs.
  702. #[cfg(windows)]
  703. pub fn use_pipeline_cache(dir: std::path::PathBuf) {
  704. library::use_pipeline_cache(dir);
  705. }
  706. /// Saves the pipeline cache now if anything was added (at the end of a run).
  707. #[cfg(windows)]
  708. pub fn save_pipeline_cache() {
  709. library::save(true);
  710. }
  711. #[cfg(test)]
  712. mod tests {
  713. #[cfg(all(windows, feature = "diagnostics"))]
  714. #[test]
  715. fn skip_hashes_accepts_full_hashes_only() {
  716. assert!(super::parse_skip_hashes(" , ").is_empty());
  717. assert_eq!(
  718. super::parse_skip_hashes(" 0123456789ABCDEF, 0123456789abcde, xyz, 0011223344556677,"),
  719. ["0123456789abcdef", "0011223344556677"]
  720. );
  721. }
  722. use super::*;
  723. use crate::object::{S_OK, slot};
  724. fn shaders(p: This) -> Vec<(&'static str, Vec<u8>)> {
  725. pipeline(p)
  726. .shaders
  727. .iter()
  728. .map(|s| (s.stage, s.container.clone()))
  729. .collect()
  730. }
  731. #[test]
  732. fn pipelines_keep_their_shaders() {
  733. let (vs, ps) = ([1u8, 2, 3], [4u8; 5]);
  734. let none = || Bytecode {
  735. code: std::ptr::null(),
  736. size: 0,
  737. };
  738. let desc = GraphicsHead {
  739. root: std::ptr::null(),
  740. stages: [
  741. Bytecode {
  742. code: vs.as_ptr(),
  743. size: vs.len(),
  744. },
  745. Bytecode {
  746. code: ps.as_ptr(),
  747. size: ps.len(),
  748. },
  749. none(),
  750. none(),
  751. none(),
  752. ],
  753. };
  754. let mut p = std::ptr::null();
  755. assert_eq!(
  756. create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p),
  757. S_OK
  758. );
  759. assert_eq!(
  760. shaders(p),
  761. [("vertex", vs.to_vec()), ("pixel", ps.to_vec())]
  762. );
  763. // A second pipeline with the same pixel shader shares its container.
  764. let mut q = std::ptr::null();
  765. create_graphics(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut q);
  766. assert!(Arc::ptr_eq(
  767. &pipeline(p).shaders[1],
  768. &pipeline(q).shaders[1]
  769. ));
  770. assert_eq!(slot::<extern "system" fn(This) -> u32>(p, 0x10)(p), 0);
  771. }
  772. /// The stream layout the title builds (title+0x86f090): root
  773. /// signature, five shader slots (the first a mesh shader), blend, sample
  774. /// mask, rasterizer, depth-stencil 1, sample description, input layout,
  775. /// topology, render target and depth formats: 0x2b0 bytes.
  776. #[test]
  777. fn streams_yield_their_shaders() {
  778. let (ms, ps) = ([9u8; 7], [4u8; 5]);
  779. let mut stream = vec![0u8; 0x2b0];
  780. let mut put = |at: usize, v: u64| stream[at..at + 8].copy_from_slice(&v.to_le_bytes());
  781. for (at, kind) in [
  782. (0x10, 24),
  783. (0x28, 2),
  784. (0x40, 3),
  785. (0x58, 4),
  786. (0x70, 5),
  787. (0x88, 8),
  788. (0x1d8, 9),
  789. (0x1e0, 10),
  790. (0x210, 21),
  791. (0x250, 17),
  792. (0x260, 12),
  793. (0x278, 14),
  794. (0x280, 15),
  795. (0x2a8, 16),
  796. ] {
  797. put(at, kind);
  798. }
  799. put(0x18, ms.as_ptr() as u64);
  800. put(0x20, ms.len() as u64);
  801. put(0x30, ps.as_ptr() as u64);
  802. put(0x38, ps.len() as u64);
  803. // Topology type 3 (triangles), one render target of format 28.
  804. put(0x278, 14 | 3 << 32);
  805. put(0x280, 15 | 28 << 32);
  806. put(0x2a0, 1 << 32);
  807. let desc = StreamDesc {
  808. size: stream.len(),
  809. stream: stream.as_ptr(),
  810. };
  811. let mut p = std::ptr::null();
  812. let hr = create_stream(std::ptr::null(), &desc, &PIPELINE_IIDS[0], &mut p);
  813. assert_eq!(hr, S_OK);
  814. assert_eq!(shaders(p), [("mesh", ms.to_vec()), ("pixel", ps.to_vec())]);
  815. #[cfg(windows)]
  816. {
  817. let g = pipeline(p).host.graphics.as_deref().unwrap();
  818. assert_eq!(g.topology.0, 3);
  819. assert_eq!(
  820. (g.targets.NumRenderTargets, g.targets.RTFormats[0].0),
  821. (1, 28)
  822. );
  823. }
  824. }
  825. }