CacheCollection.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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. /// Remove entries from the hash manifest and save it.
  35. /// </summary>
  36. RemoveManifestEntries,
  37. /// <summary>
  38. /// Flush temporary cache to archive.
  39. /// </summary>
  40. FlushToArchive,
  41. /// <summary>
  42. /// Signal when hitting this point. This is useful to know if all previous operations were performed.
  43. /// </summary>
  44. Synchronize
  45. }
  46. /// <summary>
  47. /// Represent an operation to perform on the <see cref="_fileWriterWorkerQueue"/>.
  48. /// </summary>
  49. private class CacheFileOperationTask
  50. {
  51. /// <summary>
  52. /// The type of operation to perform.
  53. /// </summary>
  54. public CacheFileOperation Type;
  55. /// <summary>
  56. /// The data associated to this operation or null.
  57. /// </summary>
  58. public object Data;
  59. }
  60. /// <summary>
  61. /// Data associated to the <see cref="CacheFileOperation.SaveTempEntry"/> operation.
  62. /// </summary>
  63. private class CacheFileSaveEntryTaskData
  64. {
  65. /// <summary>
  66. /// The key of the entry to cache.
  67. /// </summary>
  68. public Hash128 Key;
  69. /// <summary>
  70. /// The value of the entry to cache.
  71. /// </summary>
  72. public byte[] Value;
  73. }
  74. /// <summary>
  75. /// The directory of the shader cache.
  76. /// </summary>
  77. private readonly string _cacheDirectory;
  78. /// <summary>
  79. /// The version of the cache.
  80. /// </summary>
  81. private readonly ulong _version;
  82. /// <summary>
  83. /// The hash type of the cache.
  84. /// </summary>
  85. private readonly CacheHashType _hashType;
  86. /// <summary>
  87. /// The graphics API of the cache.
  88. /// </summary>
  89. private readonly CacheGraphicsApi _graphicsApi;
  90. /// <summary>
  91. /// The table of all the hash registered in the cache.
  92. /// </summary>
  93. private HashSet<Hash128> _hashTable;
  94. /// <summary>
  95. /// The queue of operations to be performed by the file writer worker.
  96. /// </summary>
  97. private AsyncWorkQueue<CacheFileOperationTask> _fileWriterWorkerQueue;
  98. /// <summary>
  99. /// Main storage of the cache collection.
  100. /// </summary>
  101. private ZipArchive _cacheArchive;
  102. /// <summary>
  103. /// Immutable copy of the hash table.
  104. /// </summary>
  105. public ReadOnlySpan<Hash128> HashTable => _hashTable.ToArray();
  106. /// <summary>
  107. /// Get the temp path to the cache data directory.
  108. /// </summary>
  109. /// <returns>The temp path to the cache data directory</returns>
  110. private string GetCacheTempDataPath() => CacheHelper.GetCacheTempDataPath(_cacheDirectory);
  111. /// <summary>
  112. /// The path to the cache archive file.
  113. /// </summary>
  114. /// <returns>The path to the cache archive file</returns>
  115. private string GetArchivePath() => CacheHelper.GetArchivePath(_cacheDirectory);
  116. /// <summary>
  117. /// The path to the cache manifest file.
  118. /// </summary>
  119. /// <returns>The path to the cache manifest file</returns>
  120. private string GetManifestPath() => CacheHelper.GetManifestPath(_cacheDirectory);
  121. /// <summary>
  122. /// Create a new temp path to the given cached file via its hash.
  123. /// </summary>
  124. /// <param name="key">The hash of the cached data</param>
  125. /// <returns>New path to the given cached file</returns>
  126. private string GenCacheTempFilePath(Hash128 key) => CacheHelper.GenCacheTempFilePath(_cacheDirectory, key);
  127. /// <summary>
  128. /// Create a new cache collection.
  129. /// </summary>
  130. /// <param name="baseCacheDirectory">The directory of the shader cache</param>
  131. /// <param name="hashType">The hash type of the shader cache</param>
  132. /// <param name="graphicsApi">The graphics api of the shader cache</param>
  133. /// <param name="shaderProvider">The shader provider name of the shader cache</param>
  134. /// <param name="cacheName">The name of the cache</param>
  135. /// <param name="version">The version of the cache</param>
  136. public CacheCollection(string baseCacheDirectory, CacheHashType hashType, CacheGraphicsApi graphicsApi, string shaderProvider, string cacheName, ulong version)
  137. {
  138. if (hashType != CacheHashType.XxHash128)
  139. {
  140. throw new NotImplementedException($"{hashType}");
  141. }
  142. _cacheDirectory = CacheHelper.GenerateCachePath(baseCacheDirectory, graphicsApi, shaderProvider, cacheName);
  143. _graphicsApi = graphicsApi;
  144. _hashType = hashType;
  145. _version = version;
  146. _hashTable = new HashSet<Hash128>();
  147. Load();
  148. _fileWriterWorkerQueue = new AsyncWorkQueue<CacheFileOperationTask>(HandleCacheTask, $"CacheCollection.Worker.{cacheName}");
  149. }
  150. /// <summary>
  151. /// Load the cache manifest file and recreate it if invalid.
  152. /// </summary>
  153. private void Load()
  154. {
  155. bool isValid = false;
  156. if (Directory.Exists(_cacheDirectory))
  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. isValid = manifestHeader.IsValid(_graphicsApi, _hashType, hashTableRaw.Span) && _version == manifestHeader.Version;
  166. if (isValid)
  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. }
  177. if (!isValid)
  178. {
  179. Logger.Warning?.Print(LogClass.Gpu, $"Shader collection \"{_cacheDirectory}\" got invalidated, cache will need to be rebuilt.");
  180. if (Directory.Exists(_cacheDirectory))
  181. {
  182. Directory.Delete(_cacheDirectory, true);
  183. }
  184. Directory.CreateDirectory(_cacheDirectory);
  185. SaveManifest();
  186. }
  187. FlushToArchive();
  188. }
  189. /// <summary>
  190. /// Queue a task to remove entries from the hash manifest.
  191. /// </summary>
  192. /// <param name="entries">Entries to remove from the manifest</param>
  193. public void RemoveManifestEntriesAsync(HashSet<Hash128> entries)
  194. {
  195. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  196. {
  197. Type = CacheFileOperation.RemoveManifestEntries,
  198. Data = entries
  199. });
  200. }
  201. /// <summary>
  202. /// Remove given entries from the manifest.
  203. /// </summary>
  204. /// <param name="entries">Entries to remove from the manifest</param>
  205. private void RemoveManifestEntries(HashSet<Hash128> entries)
  206. {
  207. lock (_hashTable)
  208. {
  209. foreach (Hash128 entry in entries)
  210. {
  211. _hashTable.Remove(entry);
  212. }
  213. SaveManifest();
  214. }
  215. }
  216. /// <summary>
  217. /// Queue a task to flush temporary files to the archive on the worker.
  218. /// </summary>
  219. public void FlushToArchiveAsync()
  220. {
  221. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  222. {
  223. Type = CacheFileOperation.FlushToArchive
  224. });
  225. }
  226. /// <summary>
  227. /// Wait for all tasks before this given point to be done.
  228. /// </summary>
  229. public void Synchronize()
  230. {
  231. using (ManualResetEvent evnt = new ManualResetEvent(false))
  232. {
  233. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  234. {
  235. Type = CacheFileOperation.Synchronize,
  236. Data = evnt
  237. });
  238. evnt.WaitOne();
  239. }
  240. }
  241. /// <summary>
  242. /// Flush temporary files to the archive.
  243. /// </summary>
  244. /// <remarks>This dispose <see cref="_cacheArchive"/> if not null and reinstantiate it.</remarks>
  245. private void FlushToArchive()
  246. {
  247. EnsureArchiveUpToDate();
  248. // Open the zip in readonly to avoid anyone modifying/corrupting it during normal operations.
  249. _cacheArchive = ZipFile.Open(GetArchivePath(), ZipArchiveMode.Read);
  250. }
  251. /// <summary>
  252. /// Save temporary files not in archive.
  253. /// </summary>
  254. /// <remarks>This dispose <see cref="_cacheArchive"/> if not null.</remarks>
  255. public void EnsureArchiveUpToDate()
  256. {
  257. // First close previous opened instance if found.
  258. if (_cacheArchive != null)
  259. {
  260. _cacheArchive.Dispose();
  261. }
  262. string archivePath = GetArchivePath();
  263. // Open the zip in read/write.
  264. _cacheArchive = ZipFile.Open(archivePath, ZipArchiveMode.Update);
  265. Logger.Info?.Print(LogClass.Gpu, $"Updating cache collection archive {archivePath}...");
  266. // Update the content of the zip.
  267. lock (_hashTable)
  268. {
  269. CacheHelper.EnsureArchiveUpToDate(_cacheDirectory, _cacheArchive, _hashTable);
  270. // Close the instance to force a flush.
  271. _cacheArchive.Dispose();
  272. _cacheArchive = null;
  273. string cacheTempDataPath = GetCacheTempDataPath();
  274. // Create the cache data path if missing.
  275. if (!Directory.Exists(cacheTempDataPath))
  276. {
  277. Directory.CreateDirectory(cacheTempDataPath);
  278. }
  279. }
  280. Logger.Info?.Print(LogClass.Gpu, $"Updated cache collection archive {archivePath}.");
  281. }
  282. /// <summary>
  283. /// Save the manifest file.
  284. /// </summary>
  285. private void SaveManifest()
  286. {
  287. byte[] data;
  288. lock (_hashTable)
  289. {
  290. data = CacheHelper.ComputeManifest(_version, _graphicsApi, _hashType, _hashTable);
  291. }
  292. File.WriteAllBytes(GetManifestPath(), data);
  293. }
  294. /// <summary>
  295. /// Get a cached file with the given hash.
  296. /// </summary>
  297. /// <param name="keyHash">The given hash</param>
  298. /// <returns>The cached file if present or null</returns>
  299. public byte[] GetValueRaw(ref Hash128 keyHash)
  300. {
  301. return GetValueRawFromArchive(ref keyHash) ?? GetValueRawFromFile(ref keyHash);
  302. }
  303. /// <summary>
  304. /// Get a cached file with the given hash that is present in the archive.
  305. /// </summary>
  306. /// <param name="keyHash">The given hash</param>
  307. /// <returns>The cached file if present or null</returns>
  308. private byte[] GetValueRawFromArchive(ref Hash128 keyHash)
  309. {
  310. bool found;
  311. lock (_hashTable)
  312. {
  313. found = _hashTable.Contains(keyHash);
  314. }
  315. if (found)
  316. {
  317. return CacheHelper.ReadFromArchive(_cacheArchive, keyHash);
  318. }
  319. return null;
  320. }
  321. /// <summary>
  322. /// Get a cached file with the given hash that is not present in the archive.
  323. /// </summary>
  324. /// <param name="keyHash">The given hash</param>
  325. /// <returns>The cached file if present or null</returns>
  326. private byte[] GetValueRawFromFile(ref Hash128 keyHash)
  327. {
  328. bool found;
  329. lock (_hashTable)
  330. {
  331. found = _hashTable.Contains(keyHash);
  332. }
  333. if (found)
  334. {
  335. return CacheHelper.ReadFromFile(GetCacheTempDataPath(), keyHash);
  336. }
  337. return null;
  338. }
  339. private void HandleCacheTask(CacheFileOperationTask task)
  340. {
  341. switch (task.Type)
  342. {
  343. case CacheFileOperation.SaveTempEntry:
  344. SaveTempEntry((CacheFileSaveEntryTaskData)task.Data);
  345. break;
  346. case CacheFileOperation.SaveManifest:
  347. SaveManifest();
  348. break;
  349. case CacheFileOperation.RemoveManifestEntries:
  350. RemoveManifestEntries((HashSet<Hash128>)task.Data);
  351. break;
  352. case CacheFileOperation.FlushToArchive:
  353. FlushToArchive();
  354. break;
  355. case CacheFileOperation.Synchronize:
  356. ((ManualResetEvent)task.Data).Set();
  357. break;
  358. default:
  359. throw new NotImplementedException($"{task.Type}");
  360. }
  361. }
  362. /// <summary>
  363. /// Save a new entry in the temp cache.
  364. /// </summary>
  365. /// <param name="entry">The entry to save in the temp cache</param>
  366. private void SaveTempEntry(CacheFileSaveEntryTaskData entry)
  367. {
  368. string tempPath = GenCacheTempFilePath(entry.Key);
  369. File.WriteAllBytes(tempPath, entry.Value);
  370. }
  371. /// <summary>
  372. /// Add a new value in the cache with a given hash.
  373. /// </summary>
  374. /// <param name="keyHash">The hash to use for the value in the cache</param>
  375. /// <param name="value">The value to cache</param>
  376. public void AddValue(ref Hash128 keyHash, byte[] value)
  377. {
  378. Debug.Assert(value != null);
  379. bool isAlreadyPresent;
  380. lock (_hashTable)
  381. {
  382. isAlreadyPresent = !_hashTable.Add(keyHash);
  383. }
  384. if (isAlreadyPresent)
  385. {
  386. // NOTE: Used for debug
  387. File.WriteAllBytes(GenCacheTempFilePath(new Hash128()), value);
  388. throw new InvalidOperationException($"Cache collision found on {GenCacheTempFilePath(keyHash)}");
  389. }
  390. // Queue file change operations
  391. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  392. {
  393. Type = CacheFileOperation.SaveTempEntry,
  394. Data = new CacheFileSaveEntryTaskData
  395. {
  396. Key = keyHash,
  397. Value = value
  398. }
  399. });
  400. // Save the manifest changes
  401. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  402. {
  403. Type = CacheFileOperation.SaveManifest,
  404. });
  405. }
  406. /// <summary>
  407. /// Replace a value at the given hash in the cache.
  408. /// </summary>
  409. /// <param name="keyHash">The hash to use for the value in the cache</param>
  410. /// <param name="value">The value to cache</param>
  411. public void ReplaceValue(ref Hash128 keyHash, byte[] value)
  412. {
  413. Debug.Assert(value != null);
  414. // Only queue file change operations
  415. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  416. {
  417. Type = CacheFileOperation.SaveTempEntry,
  418. Data = new CacheFileSaveEntryTaskData
  419. {
  420. Key = keyHash,
  421. Value = value
  422. }
  423. });
  424. }
  425. public void Dispose()
  426. {
  427. Dispose(true);
  428. }
  429. protected virtual void Dispose(bool disposing)
  430. {
  431. if (disposing)
  432. {
  433. // Make sure all operations on _fileWriterWorkerQueue are done.
  434. Synchronize();
  435. _fileWriterWorkerQueue.Dispose();
  436. EnsureArchiveUpToDate();
  437. }
  438. }
  439. }
  440. }