pipeline.rs 31 KB

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