shader_cache.rs 14 KB

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