shader_cache.rs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. //! Translated shaders kept on disk (decision 0003): under the configured
  2. //! cache folder, keyed by the container's content and by the translator
  3. //! (the BLAKE3 of its sources) and its settings, so a changed translator
  4. //! never serves an old translation. Entries go through
  5. //! `victory-pipeline`'s content-addressed cache, which writes them
  6. //! atomically; an entry that does not read back is translated again.
  7. //!
  8. //! The entry is our own encoding of [`HostShader`]: a field added to it
  9. //! must be added to `encode` and `decode` too (entries of older builds
  10. //! are ignored anyway).
  11. use std::path::PathBuf;
  12. use std::sync::OnceLock;
  13. use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
  14. use victory_pipeline::{Cache, Converter};
  15. use victory_shader::emit::{HostShader, StaticSampler, UserData};
  16. use victory_shader::resource::RootIndexedView;
  17. use victory_shader::{HwStage, RootType};
  18. static CACHE: OnceLock<Cache> = OnceLock::new();
  19. static HITS: AtomicU64 = AtomicU64::new(0);
  20. static MISSES: AtomicU64 = AtomicU64::new(0);
  21. /// Keeps translated shaders in `dir` from now on.
  22. pub fn use_shader_cache(dir: PathBuf) {
  23. match Cache::open(dir) {
  24. Ok(cache) => {
  25. let _ = CACHE.set(cache);
  26. }
  27. Err(e) => tracing::warn!(error = %e, "no shader cache"),
  28. }
  29. }
  30. /// Shaders found in the cache and translated since the start.
  31. pub(crate) fn counts() -> (u64, u64) {
  32. (HITS.load(Ordering::Relaxed), MISSES.load(Ordering::Relaxed))
  33. }
  34. /// What identifies a translation beside its container: the translator
  35. /// (the BLAKE3 of its sources, `build.rs`), the settings it runs with, and
  36. /// what it was told of the host. Not our executable: a rebuild of anything
  37. /// else used to translate every shader again.
  38. fn build() -> [u8; 32] {
  39. // The view heap's null slot differs by host GPU: a translation cached
  40. // without the clamp must not be served (`host_settings` below).
  41. crate::descriptor::host::probe_view_limit();
  42. static FIXED: OnceLock<Vec<u8>> = OnceLock::new();
  43. let fixed = FIXED.get_or_init(|| {
  44. let limit = victory_shader::emit::loop_limit();
  45. if limit != victory_shader::emit::DEFAULT_LOOP_LIMIT {
  46. tracing::warn!(
  47. limit,
  48. "VICTORY_SHADER_LOOP_LIMIT: translated loops stop sooner"
  49. );
  50. }
  51. let mut bytes = env!("VICTORY_TRANSLATOR").as_bytes().to_vec();
  52. bytes.extend_from_slice(&limit.to_le_bytes());
  53. // Which group barriers wait is part of the translation too.
  54. bytes.push(victory_shader::emit::group_sync());
  55. // So are the switches that pick the form of a wave64 program:
  56. // without them here a run with `VICTORY_WAVE_WIDE=0` was
  57. // served the translations an earlier run of the same
  58. // executable had cached with the switch unset.
  59. for name in [
  60. "VICTORY_WAVE_WIDE",
  61. "VICTORY_WAVE_DEEP_SKIPS",
  62. "VICTORY_WAVE_OWN_BITS",
  63. "VICTORY_WAVE_LOCAL",
  64. "VICTORY_F16_NEAREST",
  65. "VICTORY_HELPER_OWN",
  66. "VICTORY_FIRSTLANE_OWN",
  67. "VICTORY_FIRST_HALF",
  68. "VICTORY_STRICT_JOINS",
  69. "VICTORY_MESH_OUTPUT_STRICT",
  70. ] {
  71. bytes.extend_from_slice(name.as_bytes());
  72. bytes.push(b'=');
  73. if let Some(value) = std::env::var_os(name) {
  74. bytes.extend_from_slice(value.as_encoded_bytes());
  75. }
  76. bytes.push(0);
  77. }
  78. // And which clean-up passes ran over the translated code.
  79. bytes.extend_from_slice(&victory_shader::emit::shader_opt().to_le_bytes());
  80. bytes
  81. });
  82. let mut hash = blake3::Hasher::new();
  83. hash.update(fixed);
  84. for value in victory_shader::emit::host_settings() {
  85. hash.update(&value.to_le_bytes());
  86. }
  87. *hash.finalize().as_bytes()
  88. }
  89. /// What tells one set of translations from another ([`build`]).
  90. pub(crate) fn translation() -> [u8; 32] {
  91. build()
  92. }
  93. /// Puts the translation of `container` into the cache before any title asks
  94. /// for it (`victory shaders`): whether it was there already, or why it does
  95. /// not translate. The host is opened first, as a run does: what the card
  96. /// can do decides the form of some programs.
  97. pub fn precompile(container: &[u8]) -> Result<bool, String> {
  98. let _ = crate::host::host();
  99. let misses = MISSES.load(Ordering::Relaxed);
  100. host_shader(container)?;
  101. // (Counts other threads' misses too: the caller only adds them up.)
  102. Ok(MISSES.load(Ordering::Relaxed) == misses)
  103. }
  104. /// The translation of a console shader container, from the cache when
  105. /// there is one.
  106. pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
  107. let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
  108. match CACHE.get() {
  109. Some(cache) => cached(cache, &build(), container, translate),
  110. None => translate(container),
  111. }
  112. }
  113. /// The cache entry's converter: the build and the container in, the
  114. /// encoded translation out. `ran` tells a miss from a hit.
  115. struct Translate<F> {
  116. translate: F,
  117. ran: AtomicBool,
  118. }
  119. impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> {
  120. fn id(&self) -> &'static str {
  121. "shader.dxil"
  122. }
  123. fn version(&self) -> u32 {
  124. // The build fingerprint in the input does the versioning.
  125. 1
  126. }
  127. fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> {
  128. self.ran.store(true, Ordering::Relaxed);
  129. let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?;
  130. Ok(encode(&shader))
  131. }
  132. }
  133. fn cached(
  134. cache: &Cache,
  135. build: &[u8; 32],
  136. container: &[u8],
  137. translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
  138. ) -> Result<HostShader, String> {
  139. let input = [&build[..], container].concat();
  140. let converter = Translate {
  141. translate,
  142. ran: AtomicBool::new(false),
  143. };
  144. for _ in 0..2 {
  145. let path = cache
  146. .get_or_convert(&converter, &input)
  147. .map_err(|e| format!("{e:#}"))?;
  148. if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) {
  149. let (counter, what) = if converter.ran.load(Ordering::Relaxed) {
  150. (&MISSES, "translated and cached")
  151. } else {
  152. (&HITS, "from the cache")
  153. };
  154. counter.fetch_add(1, Ordering::Relaxed);
  155. tracing::debug!(path = %path.display(), "shader {what}");
  156. return Ok(shader);
  157. }
  158. tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again");
  159. let _ = std::fs::remove_file(&path);
  160. }
  161. MISSES.fetch_add(1, Ordering::Relaxed);
  162. (converter.translate)(container)
  163. }
  164. const MAGIC: &[u8; 4] = b"VSH1";
  165. const STAGES: [HwStage; 8] = [
  166. HwStage::Ls,
  167. HwStage::Hs,
  168. HwStage::Es,
  169. HwStage::Gs,
  170. HwStage::Vs,
  171. HwStage::Ps,
  172. HwStage::Ms,
  173. HwStage::Cs,
  174. ];
  175. fn root_code(r: RootType) -> u32 {
  176. match r {
  177. RootType::Constants => 0,
  178. RootType::Descriptor => 1,
  179. RootType::Table => 2,
  180. RootType::ImmediateSampler => 3,
  181. RootType::ResourceHeap => 4,
  182. RootType::SamplerHeap => 5,
  183. RootType::Other(x) => 6 + x,
  184. }
  185. }
  186. fn root_type(code: u32) -> RootType {
  187. match code {
  188. 0 => RootType::Constants,
  189. 1 => RootType::Descriptor,
  190. 2 => RootType::Table,
  191. 3 => RootType::ImmediateSampler,
  192. 4 => RootType::ResourceHeap,
  193. 5 => RootType::SamplerHeap,
  194. x => RootType::Other(x - 6),
  195. }
  196. }
  197. /// Little-endian words and length-prefixed lists.
  198. fn encode(s: &HostShader) -> Vec<u8> {
  199. let mut out = MAGIC.to_vec();
  200. let word = |out: &mut Vec<u8>, v: u32| out.extend(v.to_le_bytes());
  201. let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32;
  202. word(&mut out, stage);
  203. word(&mut out, s.dxil.len() as u32);
  204. out.extend(&s.dxil);
  205. word(&mut out, s.user_data.len() as u32);
  206. for u in &s.user_data {
  207. for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] {
  208. word(&mut out, v);
  209. }
  210. }
  211. word(&mut out, s.samplers.len() as u32);
  212. for sampler in &s.samplers {
  213. for &v in sampler {
  214. word(&mut out, v);
  215. }
  216. }
  217. word(&mut out, s.static_samplers.len() as u32);
  218. for t in &s.static_samplers {
  219. let [u, v, w] = t.address;
  220. let words = [
  221. t.filter,
  222. u,
  223. v,
  224. w,
  225. t.mip_lod_bias.to_bits(),
  226. t.max_anisotropy,
  227. t.comparison,
  228. t.border,
  229. t.min_lod.to_bits(),
  230. t.max_lod.to_bits(),
  231. ];
  232. for v in words {
  233. word(&mut out, v);
  234. }
  235. }
  236. for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] {
  237. word(&mut out, slots.len() as u32);
  238. out.extend(slots);
  239. }
  240. word(&mut out, s.root_indexed_views.len() as u32);
  241. for view in &s.root_indexed_views {
  242. for value in [
  243. u32::from(view.table_slot),
  244. u32::from(view.constant_slot),
  245. view.constant_dword,
  246. view.byte_offset,
  247. u32::from(view.shift),
  248. ] {
  249. word(&mut out, value);
  250. }
  251. }
  252. out
  253. }
  254. fn decode(bytes: &[u8]) -> Option<HostShader> {
  255. struct Reader<'a>(&'a [u8]);
  256. impl<'a> Reader<'a> {
  257. fn take(&mut self, n: usize) -> Option<&'a [u8]> {
  258. let (head, rest) = self.0.split_at_checked(n)?;
  259. self.0 = rest;
  260. Some(head)
  261. }
  262. fn word(&mut self) -> Option<u32> {
  263. Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
  264. }
  265. fn list(&mut self) -> Option<Vec<u8>> {
  266. let n = self.word()? as usize;
  267. Some(self.take(n)?.to_vec())
  268. }
  269. }
  270. let mut r = Reader(bytes);
  271. if r.take(4)? != MAGIC {
  272. return None;
  273. }
  274. let stage = *STAGES.get(r.word()? as usize)?;
  275. let dxil = r.list()?;
  276. let n = r.word()? as usize;
  277. let mut user_data = Vec::with_capacity(n.min(256));
  278. for _ in 0..n {
  279. user_data.push(UserData {
  280. index: r.word()?,
  281. slot: u8::try_from(r.word()?).ok()?,
  282. root: root_type(r.word()?),
  283. dword: r.word()?,
  284. });
  285. }
  286. let n = r.word()? as usize;
  287. let mut samplers = Vec::with_capacity(n.min(256));
  288. for _ in 0..n {
  289. samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]);
  290. }
  291. let n = r.word()? as usize;
  292. let mut static_samplers = Vec::with_capacity(n.min(256));
  293. for _ in 0..n {
  294. static_samplers.push(StaticSampler {
  295. filter: r.word()?,
  296. address: [r.word()?, r.word()?, r.word()?],
  297. mip_lod_bias: f32::from_bits(r.word()?),
  298. max_anisotropy: r.word()?,
  299. comparison: r.word()?,
  300. border: r.word()?,
  301. min_lod: f32::from_bits(r.word()?),
  302. max_lod: f32::from_bits(r.word()?),
  303. });
  304. }
  305. let root_cbvs = r.list()?;
  306. let root_srvs = r.list()?;
  307. let root_uavs = r.list()?;
  308. let n = r.word()? as usize;
  309. let mut root_indexed_views = Vec::with_capacity(n.min(256));
  310. for _ in 0..n {
  311. root_indexed_views.push(RootIndexedView {
  312. table_slot: u8::try_from(r.word()?).ok()?,
  313. constant_slot: u8::try_from(r.word()?).ok()?,
  314. constant_dword: r.word()?,
  315. byte_offset: r.word()?,
  316. shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?,
  317. });
  318. }
  319. r.0.is_empty().then_some(HostShader {
  320. stage,
  321. dxil,
  322. user_data,
  323. samplers,
  324. static_samplers,
  325. root_cbvs,
  326. root_srvs,
  327. root_uavs,
  328. root_indexed_views,
  329. })
  330. }
  331. #[cfg(test)]
  332. mod tests {
  333. use super::*;
  334. fn shader() -> HostShader {
  335. HostShader {
  336. stage: HwStage::Ps,
  337. dxil: b"DXBC and the rest".to_vec(),
  338. user_data: vec![UserData {
  339. index: 8,
  340. slot: 1,
  341. root: RootType::Table,
  342. dword: 0,
  343. }],
  344. samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]],
  345. static_samplers: vec![StaticSampler::from_words([
  346. 0x400,
  347. 0xc0_0000,
  348. 0x18f0_0000,
  349. 0,
  350. ])],
  351. root_cbvs: vec![2],
  352. root_srvs: vec![0, 3],
  353. root_uavs: vec![1],
  354. root_indexed_views: vec![RootIndexedView {
  355. table_slot: 1,
  356. constant_slot: 2,
  357. constant_dword: 3,
  358. byte_offset: 32,
  359. shift: 5,
  360. }],
  361. }
  362. }
  363. #[test]
  364. fn translations_come_back_from_the_cache() {
  365. let dir = tempfile::tempdir().unwrap();
  366. let cache = Cache::open(dir.path()).unwrap();
  367. let build = [7u8; 32];
  368. let container = b"a console container".as_slice();
  369. let runs = AtomicU64::new(0);
  370. let translate = |_: &[u8]| {
  371. runs.fetch_add(1, Ordering::Relaxed);
  372. Ok(shader())
  373. };
  374. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  375. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  376. assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk");
  377. // Another build translates again.
  378. assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader()));
  379. assert_eq!(runs.load(Ordering::Relaxed), 2);
  380. // A damaged entry is a miss, translated and stored again.
  381. for e in walk(dir.path()) {
  382. std::fs::write(e, b"VSH1 broken").unwrap();
  383. }
  384. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  385. assert_eq!(runs.load(Ordering::Relaxed), 3);
  386. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  387. assert_eq!(runs.load(Ordering::Relaxed), 3);
  388. // Failures are not stored.
  389. let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned());
  390. assert!(cached(&cache, &build, b"other", fail).is_err());
  391. }
  392. fn walk(dir: &std::path::Path) -> Vec<PathBuf> {
  393. let mut files = Vec::new();
  394. for e in std::fs::read_dir(dir).unwrap().flatten() {
  395. if e.path().is_dir() {
  396. files.extend(walk(&e.path()));
  397. } else {
  398. files.push(e.path());
  399. }
  400. }
  401. files
  402. }
  403. #[test]
  404. fn entries_round_trip_and_reject_damage() {
  405. let bytes = encode(&shader());
  406. assert_eq!(decode(&bytes), Some(shader()));
  407. assert_eq!(decode(&bytes[..bytes.len() - 1]), None);
  408. assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None);
  409. assert_eq!(decode(b"VSH0"), None);
  410. }
  411. }