shader_cache.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. /// Puts the translation of `container` into the cache before any title asks
  90. /// for it (`victory shaders`): whether it was there already, or why it does
  91. /// not translate. The host is opened first, as a run does: what the card
  92. /// can do decides the form of some programs.
  93. pub fn precompile(container: &[u8]) -> Result<bool, String> {
  94. let _ = crate::host::host();
  95. let misses = MISSES.load(Ordering::Relaxed);
  96. host_shader(container)?;
  97. // (Counts other threads' misses too: the caller only adds them up.)
  98. Ok(MISSES.load(Ordering::Relaxed) == misses)
  99. }
  100. /// The translation of a console shader container, from the cache when
  101. /// there is one.
  102. pub(crate) fn host_shader(container: &[u8]) -> Result<HostShader, String> {
  103. let translate = |c: &[u8]| victory_shader::emit::translate(c).map_err(|e| e.to_string());
  104. match CACHE.get() {
  105. Some(cache) => cached(cache, &build(), container, translate),
  106. None => translate(container),
  107. }
  108. }
  109. /// The cache entry's converter: the build and the container in, the
  110. /// encoded translation out. `ran` tells a miss from a hit.
  111. struct Translate<F> {
  112. translate: F,
  113. ran: AtomicBool,
  114. }
  115. impl<F: Fn(&[u8]) -> Result<HostShader, String> + Send + Sync> Converter for Translate<F> {
  116. fn id(&self) -> &'static str {
  117. "shader.dxil"
  118. }
  119. fn version(&self) -> u32 {
  120. // The build fingerprint in the input does the versioning.
  121. 1
  122. }
  123. fn convert(&self, input: &[u8]) -> anyhow::Result<Vec<u8>> {
  124. self.ran.store(true, Ordering::Relaxed);
  125. let shader = (self.translate)(&input[32..]).map_err(anyhow::Error::msg)?;
  126. Ok(encode(&shader))
  127. }
  128. }
  129. fn cached(
  130. cache: &Cache,
  131. build: &[u8; 32],
  132. container: &[u8],
  133. translate: impl Fn(&[u8]) -> Result<HostShader, String> + Send + Sync,
  134. ) -> Result<HostShader, String> {
  135. let input = [&build[..], container].concat();
  136. let converter = Translate {
  137. translate,
  138. ran: AtomicBool::new(false),
  139. };
  140. for _ in 0..2 {
  141. let path = cache
  142. .get_or_convert(&converter, &input)
  143. .map_err(|e| format!("{e:#}"))?;
  144. if let Some(shader) = std::fs::read(&path).ok().and_then(|b| decode(&b)) {
  145. let (counter, what) = if converter.ran.load(Ordering::Relaxed) {
  146. (&MISSES, "translated and cached")
  147. } else {
  148. (&HITS, "from the cache")
  149. };
  150. counter.fetch_add(1, Ordering::Relaxed);
  151. tracing::debug!(path = %path.display(), "shader {what}");
  152. return Ok(shader);
  153. }
  154. tracing::debug!(path = %path.display(), "unreadable shader cache entry; translating again");
  155. let _ = std::fs::remove_file(&path);
  156. }
  157. MISSES.fetch_add(1, Ordering::Relaxed);
  158. (converter.translate)(container)
  159. }
  160. const MAGIC: &[u8; 4] = b"VSH1";
  161. const STAGES: [HwStage; 8] = [
  162. HwStage::Ls,
  163. HwStage::Hs,
  164. HwStage::Es,
  165. HwStage::Gs,
  166. HwStage::Vs,
  167. HwStage::Ps,
  168. HwStage::Ms,
  169. HwStage::Cs,
  170. ];
  171. fn root_code(r: RootType) -> u32 {
  172. match r {
  173. RootType::Constants => 0,
  174. RootType::Descriptor => 1,
  175. RootType::Table => 2,
  176. RootType::ImmediateSampler => 3,
  177. RootType::ResourceHeap => 4,
  178. RootType::SamplerHeap => 5,
  179. RootType::Other(x) => 6 + x,
  180. }
  181. }
  182. fn root_type(code: u32) -> RootType {
  183. match code {
  184. 0 => RootType::Constants,
  185. 1 => RootType::Descriptor,
  186. 2 => RootType::Table,
  187. 3 => RootType::ImmediateSampler,
  188. 4 => RootType::ResourceHeap,
  189. 5 => RootType::SamplerHeap,
  190. x => RootType::Other(x - 6),
  191. }
  192. }
  193. /// Little-endian words and length-prefixed lists.
  194. fn encode(s: &HostShader) -> Vec<u8> {
  195. let mut out = MAGIC.to_vec();
  196. let word = |out: &mut Vec<u8>, v: u32| out.extend(v.to_le_bytes());
  197. let stage = STAGES.iter().position(|&x| x == s.stage).unwrap_or(0) as u32;
  198. word(&mut out, stage);
  199. word(&mut out, s.dxil.len() as u32);
  200. out.extend(&s.dxil);
  201. word(&mut out, s.user_data.len() as u32);
  202. for u in &s.user_data {
  203. for v in [u.index, u32::from(u.slot), root_code(u.root), u.dword] {
  204. word(&mut out, v);
  205. }
  206. }
  207. word(&mut out, s.samplers.len() as u32);
  208. for sampler in &s.samplers {
  209. for &v in sampler {
  210. word(&mut out, v);
  211. }
  212. }
  213. word(&mut out, s.static_samplers.len() as u32);
  214. for t in &s.static_samplers {
  215. let [u, v, w] = t.address;
  216. let words = [
  217. t.filter,
  218. u,
  219. v,
  220. w,
  221. t.mip_lod_bias.to_bits(),
  222. t.max_anisotropy,
  223. t.comparison,
  224. t.border,
  225. t.min_lod.to_bits(),
  226. t.max_lod.to_bits(),
  227. ];
  228. for v in words {
  229. word(&mut out, v);
  230. }
  231. }
  232. for slots in [&s.root_cbvs, &s.root_srvs, &s.root_uavs] {
  233. word(&mut out, slots.len() as u32);
  234. out.extend(slots);
  235. }
  236. word(&mut out, s.root_indexed_views.len() as u32);
  237. for view in &s.root_indexed_views {
  238. for value in [
  239. u32::from(view.table_slot),
  240. u32::from(view.constant_slot),
  241. view.constant_dword,
  242. view.byte_offset,
  243. u32::from(view.shift),
  244. ] {
  245. word(&mut out, value);
  246. }
  247. }
  248. out
  249. }
  250. fn decode(bytes: &[u8]) -> Option<HostShader> {
  251. struct Reader<'a>(&'a [u8]);
  252. impl<'a> Reader<'a> {
  253. fn take(&mut self, n: usize) -> Option<&'a [u8]> {
  254. let (head, rest) = self.0.split_at_checked(n)?;
  255. self.0 = rest;
  256. Some(head)
  257. }
  258. fn word(&mut self) -> Option<u32> {
  259. Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
  260. }
  261. fn list(&mut self) -> Option<Vec<u8>> {
  262. let n = self.word()? as usize;
  263. Some(self.take(n)?.to_vec())
  264. }
  265. }
  266. let mut r = Reader(bytes);
  267. if r.take(4)? != MAGIC {
  268. return None;
  269. }
  270. let stage = *STAGES.get(r.word()? as usize)?;
  271. let dxil = r.list()?;
  272. let n = r.word()? as usize;
  273. let mut user_data = Vec::with_capacity(n.min(256));
  274. for _ in 0..n {
  275. user_data.push(UserData {
  276. index: r.word()?,
  277. slot: u8::try_from(r.word()?).ok()?,
  278. root: root_type(r.word()?),
  279. dword: r.word()?,
  280. });
  281. }
  282. let n = r.word()? as usize;
  283. let mut samplers = Vec::with_capacity(n.min(256));
  284. for _ in 0..n {
  285. samplers.push([r.word()?, r.word()?, r.word()?, r.word()?]);
  286. }
  287. let n = r.word()? as usize;
  288. let mut static_samplers = Vec::with_capacity(n.min(256));
  289. for _ in 0..n {
  290. static_samplers.push(StaticSampler {
  291. filter: r.word()?,
  292. address: [r.word()?, r.word()?, r.word()?],
  293. mip_lod_bias: f32::from_bits(r.word()?),
  294. max_anisotropy: r.word()?,
  295. comparison: r.word()?,
  296. border: r.word()?,
  297. min_lod: f32::from_bits(r.word()?),
  298. max_lod: f32::from_bits(r.word()?),
  299. });
  300. }
  301. let root_cbvs = r.list()?;
  302. let root_srvs = r.list()?;
  303. let root_uavs = r.list()?;
  304. let n = r.word()? as usize;
  305. let mut root_indexed_views = Vec::with_capacity(n.min(256));
  306. for _ in 0..n {
  307. root_indexed_views.push(RootIndexedView {
  308. table_slot: u8::try_from(r.word()?).ok()?,
  309. constant_slot: u8::try_from(r.word()?).ok()?,
  310. constant_dword: r.word()?,
  311. byte_offset: r.word()?,
  312. shift: u8::try_from(r.word()?).ok().filter(|&s| s < 32)?,
  313. });
  314. }
  315. r.0.is_empty().then_some(HostShader {
  316. stage,
  317. dxil,
  318. user_data,
  319. samplers,
  320. static_samplers,
  321. root_cbvs,
  322. root_srvs,
  323. root_uavs,
  324. root_indexed_views,
  325. })
  326. }
  327. #[cfg(test)]
  328. mod tests {
  329. use super::*;
  330. fn shader() -> HostShader {
  331. HostShader {
  332. stage: HwStage::Ps,
  333. dxil: b"DXBC and the rest".to_vec(),
  334. user_data: vec![UserData {
  335. index: 8,
  336. slot: 1,
  337. root: RootType::Table,
  338. dword: 0,
  339. }],
  340. samplers: vec![[0x400, 0xc0_0000, 0x18f0_0000, 0]],
  341. static_samplers: vec![StaticSampler::from_words([
  342. 0x400,
  343. 0xc0_0000,
  344. 0x18f0_0000,
  345. 0,
  346. ])],
  347. root_cbvs: vec![2],
  348. root_srvs: vec![0, 3],
  349. root_uavs: vec![1],
  350. root_indexed_views: vec![RootIndexedView {
  351. table_slot: 1,
  352. constant_slot: 2,
  353. constant_dword: 3,
  354. byte_offset: 32,
  355. shift: 5,
  356. }],
  357. }
  358. }
  359. #[test]
  360. fn translations_come_back_from_the_cache() {
  361. let dir = tempfile::tempdir().unwrap();
  362. let cache = Cache::open(dir.path()).unwrap();
  363. let build = [7u8; 32];
  364. let container = b"a console container".as_slice();
  365. let runs = AtomicU64::new(0);
  366. let translate = |_: &[u8]| {
  367. runs.fetch_add(1, Ordering::Relaxed);
  368. Ok(shader())
  369. };
  370. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  371. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  372. assert_eq!(runs.load(Ordering::Relaxed), 1, "the second came from disk");
  373. // Another build translates again.
  374. assert_eq!(cached(&cache, &[8; 32], container, translate), Ok(shader()));
  375. assert_eq!(runs.load(Ordering::Relaxed), 2);
  376. // A damaged entry is a miss, translated and stored again.
  377. for e in walk(dir.path()) {
  378. std::fs::write(e, b"VSH1 broken").unwrap();
  379. }
  380. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  381. assert_eq!(runs.load(Ordering::Relaxed), 3);
  382. assert_eq!(cached(&cache, &build, container, translate), Ok(shader()));
  383. assert_eq!(runs.load(Ordering::Relaxed), 3);
  384. // Failures are not stored.
  385. let fail = |_: &[u8]| Err::<HostShader, _>("unsupported".to_owned());
  386. assert!(cached(&cache, &build, b"other", fail).is_err());
  387. }
  388. fn walk(dir: &std::path::Path) -> Vec<PathBuf> {
  389. let mut files = Vec::new();
  390. for e in std::fs::read_dir(dir).unwrap().flatten() {
  391. if e.path().is_dir() {
  392. files.extend(walk(&e.path()));
  393. } else {
  394. files.push(e.path());
  395. }
  396. }
  397. files
  398. }
  399. #[test]
  400. fn entries_round_trip_and_reject_damage() {
  401. let bytes = encode(&shader());
  402. assert_eq!(decode(&bytes), Some(shader()));
  403. assert_eq!(decode(&bytes[..bytes.len() - 1]), None);
  404. assert_eq!(decode(&[bytes.as_slice(), &[0]].concat()), None);
  405. assert_eq!(decode(b"VSH0"), None);
  406. }
  407. }