CacheCollection.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. using Ryujinx.Common;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.Gpu.Shader.Cache.Definition;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.IO.Compression;
  9. using System.Linq;
  10. using System.Runtime.CompilerServices;
  11. using System.Runtime.InteropServices;
  12. using System.Threading;
  13. namespace Ryujinx.Graphics.Gpu.Shader.Cache
  14. {
  15. /// <summary>
  16. /// Represent a cache collection handling one shader cache.
  17. /// </summary>
  18. class CacheCollection : IDisposable
  19. {
  20. /// <summary>
  21. /// Possible operation to do on the <see cref="_fileWriterWorkerQueue"/>.
  22. /// </summary>
  23. private enum CacheFileOperation
  24. {
  25. /// <summary>
  26. /// Save a new entry in the temp cache.
  27. /// </summary>
  28. SaveTempEntry,
  29. /// <summary>
  30. /// Save the hash manifest.
  31. /// </summary>
  32. SaveManifest,
  33. /// <summary>
  34. /// Flush temporary cache to archive.
  35. /// </summary>
  36. FlushToArchive,
  37. /// <summary>
  38. /// Signal when hitting this point. This is useful to know if all previous operations were performed.
  39. /// </summary>
  40. Synchronize
  41. }
  42. /// <summary>
  43. /// Represent an operation to perform on the <see cref="_fileWriterWorkerQueue"/>.
  44. /// </summary>
  45. private class CacheFileOperationTask
  46. {
  47. /// <summary>
  48. /// The type of operation to perform.
  49. /// </summary>
  50. public CacheFileOperation Type;
  51. /// <summary>
  52. /// The data associated to this operation or null.
  53. /// </summary>
  54. public object Data;
  55. }
  56. /// <summary>
  57. /// Data associated to the <see cref="CacheFileOperation.SaveTempEntry"/> operation.
  58. /// </summary>
  59. private class CacheFileSaveEntryTaskData
  60. {
  61. /// <summary>
  62. /// The key of the entry to cache.
  63. /// </summary>
  64. public Hash128 Key;
  65. /// <summary>
  66. /// The value of the entry to cache.
  67. /// </summary>
  68. public byte[] Value;
  69. }
  70. /// <summary>
  71. /// The directory of the shader cache.
  72. /// </summary>
  73. private readonly string _cacheDirectory;
  74. /// <summary>
  75. /// The version of the cache.
  76. /// </summary>
  77. private readonly ulong _version;
  78. /// <summary>
  79. /// The hash type of the cache.
  80. /// </summary>
  81. private readonly CacheHashType _hashType;
  82. /// <summary>
  83. /// The graphics API of the cache.
  84. /// </summary>
  85. private readonly CacheGraphicsApi _graphicsApi;
  86. /// <summary>
  87. /// The table of all the hash registered in the cache.
  88. /// </summary>
  89. private HashSet<Hash128> _hashTable;
  90. /// <summary>
  91. /// The queue of operations to be performed by the file writer worker.
  92. /// </summary>
  93. private AsyncWorkQueue<CacheFileOperationTask> _fileWriterWorkerQueue;
  94. /// <summary>
  95. /// Main storage of the cache collection.
  96. /// </summary>
  97. private ZipArchive _cacheArchive;
  98. /// <summary>
  99. /// Immutable copy of the hash table.
  100. /// </summary>
  101. public ReadOnlySpan<Hash128> HashTable => _hashTable.ToArray();
  102. /// <summary>
  103. /// Get the temp path to the cache data directory.
  104. /// </summary>
  105. /// <returns>The temp path to the cache data directory</returns>
  106. private string GetCacheTempDataPath() => Path.Combine(_cacheDirectory, "temp");
  107. /// <summary>
  108. /// The path to the cache archive file.
  109. /// </summary>
  110. /// <returns>The path to the cache archive file</returns>
  111. private string GetArchivePath() => Path.Combine(_cacheDirectory, "cache.zip");
  112. /// <summary>
  113. /// The path to the cache manifest file.
  114. /// </summary>
  115. /// <returns>The path to the cache manifest file</returns>
  116. private string GetManifestPath() => Path.Combine(_cacheDirectory, "cache.info");
  117. /// <summary>
  118. /// Create a new temp path to the given cached file via its hash.
  119. /// </summary>
  120. /// <param name="key">The hash of the cached data</param>
  121. /// <returns>New path to the given cached file</returns>
  122. private string GenCacheTempFilePath(Hash128 key) => Path.Combine(GetCacheTempDataPath(), key.ToString());
  123. /// <summary>
  124. /// Create a new cache collection.
  125. /// </summary>
  126. /// <param name="baseCacheDirectory">The directory of the shader cache</param>
  127. /// <param name="hashType">The hash type of the shader cache</param>
  128. /// <param name="graphicsApi">The graphics api of the shader cache</param>
  129. /// <param name="shaderProvider">The shader provider name of the shader cache</param>
  130. /// <param name="cacheName">The name of the cache</param>
  131. /// <param name="version">The version of the cache</param>
  132. public CacheCollection(string baseCacheDirectory, CacheHashType hashType, CacheGraphicsApi graphicsApi, string shaderProvider, string cacheName, ulong version)
  133. {
  134. if (hashType != CacheHashType.XxHash128)
  135. {
  136. throw new NotImplementedException($"{hashType}");
  137. }
  138. _cacheDirectory = GenerateCachePath(baseCacheDirectory, graphicsApi, shaderProvider, cacheName);
  139. _graphicsApi = graphicsApi;
  140. _hashType = hashType;
  141. _version = version;
  142. _hashTable = new HashSet<Hash128>();
  143. Load();
  144. _fileWriterWorkerQueue = new AsyncWorkQueue<CacheFileOperationTask>(HandleCacheTask, $"CacheCollection.Worker.{cacheName}");
  145. }
  146. /// <summary>
  147. /// Load the cache manifest file and recreate it if invalid.
  148. /// </summary>
  149. private void Load()
  150. {
  151. bool isInvalid = false;
  152. if (!Directory.Exists(_cacheDirectory))
  153. {
  154. isInvalid = true;
  155. }
  156. else
  157. {
  158. string manifestPath = GetManifestPath();
  159. if (File.Exists(manifestPath))
  160. {
  161. Memory<byte> rawManifest = File.ReadAllBytes(manifestPath);
  162. if (MemoryMarshal.TryRead(rawManifest.Span, out CacheManifestHeader manifestHeader))
  163. {
  164. Memory<byte> hashTableRaw = rawManifest.Slice(Unsafe.SizeOf<CacheManifestHeader>());
  165. isInvalid = !manifestHeader.IsValid(_version, _graphicsApi, _hashType, hashTableRaw.Span);
  166. if (!isInvalid)
  167. {
  168. ReadOnlySpan<Hash128> hashTable = MemoryMarshal.Cast<byte, Hash128>(hashTableRaw.Span);
  169. foreach (Hash128 hash in hashTable)
  170. {
  171. _hashTable.Add(hash);
  172. }
  173. }
  174. }
  175. }
  176. else
  177. {
  178. isInvalid = true;
  179. }
  180. }
  181. if (isInvalid)
  182. {
  183. Logger.Warning?.Print(LogClass.Gpu, $"Shader collection \"{_cacheDirectory}\" got invalidated, cache will need to be rebuilt.");
  184. if (Directory.Exists(_cacheDirectory))
  185. {
  186. Directory.Delete(_cacheDirectory, true);
  187. }
  188. Directory.CreateDirectory(_cacheDirectory);
  189. SaveManifest();
  190. }
  191. FlushToArchive();
  192. }
  193. /// <summary>
  194. /// Remove given entries from the manifest.
  195. /// </summary>
  196. /// <param name="entries">Entries to remove from the manifest</param>
  197. public void RemoveManifestEntries(HashSet<Hash128> entries)
  198. {
  199. lock (_hashTable)
  200. {
  201. foreach (Hash128 entry in entries)
  202. {
  203. _hashTable.Remove(entry);
  204. }
  205. SaveManifest();
  206. }
  207. }
  208. /// <summary>
  209. /// Queue a task to flush temporary files to the archive on the worker.
  210. /// </summary>
  211. public void FlushToArchiveAsync()
  212. {
  213. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  214. {
  215. Type = CacheFileOperation.FlushToArchive
  216. });
  217. }
  218. /// <summary>
  219. /// Wait for all tasks before this given point to be done.
  220. /// </summary>
  221. public void Synchronize()
  222. {
  223. using (ManualResetEvent evnt = new ManualResetEvent(false))
  224. {
  225. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  226. {
  227. Type = CacheFileOperation.Synchronize,
  228. Data = evnt
  229. });
  230. evnt.WaitOne();
  231. }
  232. }
  233. /// <summary>
  234. /// Flush temporary files to the archive.
  235. /// </summary>
  236. /// <remarks>This dispose <see cref="_cacheArchive"/> if not null and reinstantiate it.</remarks>
  237. private void FlushToArchive()
  238. {
  239. EnsureArchiveUpToDate();
  240. // Open the zip in readonly to avoid anyone modifying/corrupting it during normal operations.
  241. _cacheArchive = ZipFile.Open(GetArchivePath(), ZipArchiveMode.Read);
  242. }
  243. /// <summary>
  244. /// Save temporary files not in archive.
  245. /// </summary>
  246. /// <remarks>This dispose <see cref="_cacheArchive"/> if not null.</remarks>
  247. public void EnsureArchiveUpToDate()
  248. {
  249. // First close previous opened instance if found.
  250. if (_cacheArchive != null)
  251. {
  252. _cacheArchive.Dispose();
  253. }
  254. string archivePath = GetArchivePath();
  255. // Open the zip in read/write.
  256. _cacheArchive = ZipFile.Open(archivePath, ZipArchiveMode.Update);
  257. Logger.Info?.Print(LogClass.Gpu, $"Updating cache collection archive {archivePath}...");
  258. // Update the content of the zip.
  259. lock (_hashTable)
  260. {
  261. foreach (Hash128 hash in _hashTable)
  262. {
  263. string cacheTempFilePath = GenCacheTempFilePath(hash);
  264. if (File.Exists(cacheTempFilePath))
  265. {
  266. string cacheHash = $"{hash}";
  267. ZipArchiveEntry entry = _cacheArchive.GetEntry(cacheHash);
  268. entry?.Delete();
  269. _cacheArchive.CreateEntryFromFile(cacheTempFilePath, cacheHash);
  270. File.Delete(cacheTempFilePath);
  271. }
  272. }
  273. // Close the instance to force a flush.
  274. _cacheArchive.Dispose();
  275. _cacheArchive = null;
  276. string cacheTempDataPath = GetCacheTempDataPath();
  277. // Create the cache data path if missing.
  278. if (!Directory.Exists(cacheTempDataPath))
  279. {
  280. Directory.CreateDirectory(cacheTempDataPath);
  281. }
  282. }
  283. Logger.Info?.Print(LogClass.Gpu, $"Updated cache collection archive {archivePath}.");
  284. }
  285. /// <summary>
  286. /// Save the manifest file.
  287. /// </summary>
  288. private void SaveManifest()
  289. {
  290. CacheManifestHeader manifestHeader = new CacheManifestHeader(_version, _graphicsApi, _hashType);
  291. byte[] data;
  292. lock (_hashTable)
  293. {
  294. data = new byte[Unsafe.SizeOf<CacheManifestHeader>() + _hashTable.Count * Unsafe.SizeOf<Hash128>()];
  295. // CacheManifestHeader has the same size as a Hash128.
  296. Span<Hash128> dataSpan = MemoryMarshal.Cast<byte, Hash128>(data.AsSpan()).Slice(1);
  297. int i = 0;
  298. foreach (Hash128 hash in _hashTable)
  299. {
  300. dataSpan[i++] = hash;
  301. }
  302. }
  303. manifestHeader.UpdateChecksum(data.AsSpan().Slice(Unsafe.SizeOf<CacheManifestHeader>()));
  304. MemoryMarshal.Write(data, ref manifestHeader);
  305. File.WriteAllBytes(GetManifestPath(), data);
  306. }
  307. /// <summary>
  308. /// Generate the path to the cache directory.
  309. /// </summary>
  310. /// <param name="baseCacheDirectory">The base of the cache directory</param>
  311. /// <param name="graphicsApi">The graphics api in use</param>
  312. /// <param name="shaderProvider">The name of the shader provider in use</param>
  313. /// <param name="cacheName">The name of the cache</param>
  314. /// <returns>The path to the cache directory</returns>
  315. private static string GenerateCachePath(string baseCacheDirectory, CacheGraphicsApi graphicsApi, string shaderProvider, string cacheName)
  316. {
  317. string graphicsApiName = graphicsApi switch
  318. {
  319. CacheGraphicsApi.OpenGL => "opengl",
  320. CacheGraphicsApi.OpenGLES => "opengles",
  321. CacheGraphicsApi.Vulkan => "vulkan",
  322. CacheGraphicsApi.DirectX => "directx",
  323. CacheGraphicsApi.Metal => "metal",
  324. CacheGraphicsApi.Guest => "guest",
  325. _ => throw new NotImplementedException(graphicsApi.ToString()),
  326. };
  327. return Path.Combine(baseCacheDirectory, graphicsApiName, shaderProvider, cacheName);
  328. }
  329. /// <summary>
  330. /// Get a cached file with the given hash.
  331. /// </summary>
  332. /// <param name="keyHash">The given hash</param>
  333. /// <returns>The cached file if present or null</returns>
  334. public byte[] GetValueRaw(ref Hash128 keyHash)
  335. {
  336. return GetValueRawFromArchive(ref keyHash) ?? GetValueRawFromFile(ref keyHash);
  337. }
  338. /// <summary>
  339. /// Get a cached file with the given hash that is present in the archive.
  340. /// </summary>
  341. /// <param name="keyHash">The given hash</param>
  342. /// <returns>The cached file if present or null</returns>
  343. private byte[] GetValueRawFromArchive(ref Hash128 keyHash)
  344. {
  345. bool found;
  346. lock (_hashTable)
  347. {
  348. found = _hashTable.Contains(keyHash);
  349. }
  350. if (found)
  351. {
  352. ZipArchiveEntry archiveEntry = _cacheArchive.GetEntry($"{keyHash}");
  353. if (archiveEntry != null)
  354. {
  355. try
  356. {
  357. byte[] result = new byte[archiveEntry.Length];
  358. using (Stream archiveStream = archiveEntry.Open())
  359. {
  360. archiveStream.Read(result);
  361. return result;
  362. }
  363. }
  364. catch (Exception e)
  365. {
  366. Logger.Error?.Print(LogClass.Gpu, $"Cannot load cache file {keyHash} from archive");
  367. Logger.Error?.Print(LogClass.Gpu, e.ToString());
  368. }
  369. }
  370. }
  371. return null;
  372. }
  373. /// <summary>
  374. /// Get a cached file with the given hash that is not present in the archive.
  375. /// </summary>
  376. /// <param name="keyHash">The given hash</param>
  377. /// <returns>The cached file if present or null</returns>
  378. private byte[] GetValueRawFromFile(ref Hash128 keyHash)
  379. {
  380. bool found;
  381. lock (_hashTable)
  382. {
  383. found = _hashTable.Contains(keyHash);
  384. }
  385. if (found)
  386. {
  387. string cacheTempFilePath = GenCacheTempFilePath(keyHash);
  388. try
  389. {
  390. return File.ReadAllBytes(GenCacheTempFilePath(keyHash));
  391. }
  392. catch (Exception e)
  393. {
  394. Logger.Error?.Print(LogClass.Gpu, $"Cannot load cache file at {cacheTempFilePath}");
  395. Logger.Error?.Print(LogClass.Gpu, e.ToString());
  396. }
  397. }
  398. return null;
  399. }
  400. private void HandleCacheTask(CacheFileOperationTask task)
  401. {
  402. switch (task.Type)
  403. {
  404. case CacheFileOperation.SaveTempEntry:
  405. SaveTempEntry((CacheFileSaveEntryTaskData)task.Data);
  406. break;
  407. case CacheFileOperation.SaveManifest:
  408. SaveManifest();
  409. break;
  410. case CacheFileOperation.FlushToArchive:
  411. FlushToArchive();
  412. break;
  413. case CacheFileOperation.Synchronize:
  414. ((ManualResetEvent)task.Data).Set();
  415. break;
  416. default:
  417. throw new NotImplementedException($"{task.Type}");
  418. }
  419. }
  420. /// <summary>
  421. /// Save a new entry in the temp cache.
  422. /// </summary>
  423. /// <param name="entry">The entry to save in the temp cache</param>
  424. private void SaveTempEntry(CacheFileSaveEntryTaskData entry)
  425. {
  426. string tempPath = GenCacheTempFilePath(entry.Key);
  427. File.WriteAllBytes(tempPath, entry.Value);
  428. }
  429. /// <summary>
  430. /// Add a new value in the cache with a given hash.
  431. /// </summary>
  432. /// <param name="keyHash">The hash to use for the value in the cache</param>
  433. /// <param name="value">The value to cache</param>
  434. public void AddValue(ref Hash128 keyHash, byte[] value)
  435. {
  436. Debug.Assert(value != null);
  437. Debug.Assert(GetValueRaw(ref keyHash) != null);
  438. bool isAlreadyPresent;
  439. lock (_hashTable)
  440. {
  441. isAlreadyPresent = !_hashTable.Add(keyHash);
  442. }
  443. if (isAlreadyPresent)
  444. {
  445. // NOTE: Used for debug
  446. File.WriteAllBytes(GenCacheTempFilePath(new Hash128()), value);
  447. throw new InvalidOperationException($"Cache collision found on {GenCacheTempFilePath(keyHash)}");
  448. }
  449. // Queue file change operations
  450. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  451. {
  452. Type = CacheFileOperation.SaveTempEntry,
  453. Data = new CacheFileSaveEntryTaskData
  454. {
  455. Key = keyHash,
  456. Value = value
  457. }
  458. });
  459. // Save the manifest changes
  460. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  461. {
  462. Type = CacheFileOperation.SaveManifest,
  463. });
  464. }
  465. /// <summary>
  466. /// Replace a value at the given hash in the cache.
  467. /// </summary>
  468. /// <param name="keyHash">The hash to use for the value in the cache</param>
  469. /// <param name="value">The value to cache</param>
  470. public void ReplaceValue(ref Hash128 keyHash, byte[] value)
  471. {
  472. Debug.Assert(value != null);
  473. // Only queue file change operations
  474. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  475. {
  476. Type = CacheFileOperation.SaveTempEntry,
  477. Data = new CacheFileSaveEntryTaskData
  478. {
  479. Key = keyHash,
  480. Value = value
  481. }
  482. });
  483. }
  484. public void Dispose()
  485. {
  486. Dispose(true);
  487. }
  488. protected virtual void Dispose(bool disposing)
  489. {
  490. if (disposing)
  491. {
  492. // Make sure all operations on _fileWriterWorkerQueue are done.
  493. Synchronize();
  494. _fileWriterWorkerQueue.Dispose();
  495. EnsureArchiveUpToDate();
  496. }
  497. }
  498. }
  499. }