CacheCollection.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  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() => Path.Combine(_cacheDirectory, "temp");
  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() => Path.Combine(_cacheDirectory, "cache.zip");
  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() => Path.Combine(_cacheDirectory, "cache.info");
  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) => Path.Combine(GetCacheTempDataPath(), key.ToString());
  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 = 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 isInvalid = false;
  156. if (!Directory.Exists(_cacheDirectory))
  157. {
  158. isInvalid = true;
  159. }
  160. else
  161. {
  162. string manifestPath = GetManifestPath();
  163. if (File.Exists(manifestPath))
  164. {
  165. Memory<byte> rawManifest = File.ReadAllBytes(manifestPath);
  166. if (MemoryMarshal.TryRead(rawManifest.Span, out CacheManifestHeader manifestHeader))
  167. {
  168. Memory<byte> hashTableRaw = rawManifest.Slice(Unsafe.SizeOf<CacheManifestHeader>());
  169. isInvalid = !manifestHeader.IsValid(_version, _graphicsApi, _hashType, hashTableRaw.Span);
  170. if (!isInvalid)
  171. {
  172. ReadOnlySpan<Hash128> hashTable = MemoryMarshal.Cast<byte, Hash128>(hashTableRaw.Span);
  173. foreach (Hash128 hash in hashTable)
  174. {
  175. _hashTable.Add(hash);
  176. }
  177. }
  178. }
  179. }
  180. else
  181. {
  182. isInvalid = true;
  183. }
  184. }
  185. if (isInvalid)
  186. {
  187. Logger.Warning?.Print(LogClass.Gpu, $"Shader collection \"{_cacheDirectory}\" got invalidated, cache will need to be rebuilt.");
  188. if (Directory.Exists(_cacheDirectory))
  189. {
  190. Directory.Delete(_cacheDirectory, true);
  191. }
  192. Directory.CreateDirectory(_cacheDirectory);
  193. SaveManifest();
  194. }
  195. FlushToArchive();
  196. }
  197. /// <summary>
  198. /// Queue a task to remove entries from the hash manifest.
  199. /// </summary>
  200. /// <param name="entries">Entries to remove from the manifest</param>
  201. public void RemoveManifestEntriesAsync(HashSet<Hash128> entries)
  202. {
  203. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  204. {
  205. Type = CacheFileOperation.RemoveManifestEntries,
  206. Data = entries
  207. });
  208. }
  209. /// <summary>
  210. /// Remove given entries from the manifest.
  211. /// </summary>
  212. /// <param name="entries">Entries to remove from the manifest</param>
  213. private void RemoveManifestEntries(HashSet<Hash128> entries)
  214. {
  215. lock (_hashTable)
  216. {
  217. foreach (Hash128 entry in entries)
  218. {
  219. _hashTable.Remove(entry);
  220. }
  221. SaveManifest();
  222. }
  223. }
  224. /// <summary>
  225. /// Queue a task to flush temporary files to the archive on the worker.
  226. /// </summary>
  227. public void FlushToArchiveAsync()
  228. {
  229. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  230. {
  231. Type = CacheFileOperation.FlushToArchive
  232. });
  233. }
  234. /// <summary>
  235. /// Wait for all tasks before this given point to be done.
  236. /// </summary>
  237. public void Synchronize()
  238. {
  239. using (ManualResetEvent evnt = new ManualResetEvent(false))
  240. {
  241. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  242. {
  243. Type = CacheFileOperation.Synchronize,
  244. Data = evnt
  245. });
  246. evnt.WaitOne();
  247. }
  248. }
  249. /// <summary>
  250. /// Flush temporary files to the archive.
  251. /// </summary>
  252. /// <remarks>This dispose <see cref="_cacheArchive"/> if not null and reinstantiate it.</remarks>
  253. private void FlushToArchive()
  254. {
  255. EnsureArchiveUpToDate();
  256. // Open the zip in readonly to avoid anyone modifying/corrupting it during normal operations.
  257. _cacheArchive = ZipFile.Open(GetArchivePath(), ZipArchiveMode.Read);
  258. }
  259. /// <summary>
  260. /// Save temporary files not in archive.
  261. /// </summary>
  262. /// <remarks>This dispose <see cref="_cacheArchive"/> if not null.</remarks>
  263. public void EnsureArchiveUpToDate()
  264. {
  265. // First close previous opened instance if found.
  266. if (_cacheArchive != null)
  267. {
  268. _cacheArchive.Dispose();
  269. }
  270. string archivePath = GetArchivePath();
  271. // Open the zip in read/write.
  272. _cacheArchive = ZipFile.Open(archivePath, ZipArchiveMode.Update);
  273. Logger.Info?.Print(LogClass.Gpu, $"Updating cache collection archive {archivePath}...");
  274. // Update the content of the zip.
  275. lock (_hashTable)
  276. {
  277. foreach (Hash128 hash in _hashTable)
  278. {
  279. string cacheTempFilePath = GenCacheTempFilePath(hash);
  280. if (File.Exists(cacheTempFilePath))
  281. {
  282. string cacheHash = $"{hash}";
  283. ZipArchiveEntry entry = _cacheArchive.GetEntry(cacheHash);
  284. entry?.Delete();
  285. _cacheArchive.CreateEntryFromFile(cacheTempFilePath, cacheHash);
  286. File.Delete(cacheTempFilePath);
  287. }
  288. }
  289. // Close the instance to force a flush.
  290. _cacheArchive.Dispose();
  291. _cacheArchive = null;
  292. string cacheTempDataPath = GetCacheTempDataPath();
  293. // Create the cache data path if missing.
  294. if (!Directory.Exists(cacheTempDataPath))
  295. {
  296. Directory.CreateDirectory(cacheTempDataPath);
  297. }
  298. }
  299. Logger.Info?.Print(LogClass.Gpu, $"Updated cache collection archive {archivePath}.");
  300. }
  301. /// <summary>
  302. /// Save the manifest file.
  303. /// </summary>
  304. private void SaveManifest()
  305. {
  306. CacheManifestHeader manifestHeader = new CacheManifestHeader(_version, _graphicsApi, _hashType);
  307. byte[] data;
  308. lock (_hashTable)
  309. {
  310. data = new byte[Unsafe.SizeOf<CacheManifestHeader>() + _hashTable.Count * Unsafe.SizeOf<Hash128>()];
  311. // CacheManifestHeader has the same size as a Hash128.
  312. Span<Hash128> dataSpan = MemoryMarshal.Cast<byte, Hash128>(data.AsSpan()).Slice(1);
  313. int i = 0;
  314. foreach (Hash128 hash in _hashTable)
  315. {
  316. dataSpan[i++] = hash;
  317. }
  318. }
  319. manifestHeader.UpdateChecksum(data.AsSpan().Slice(Unsafe.SizeOf<CacheManifestHeader>()));
  320. MemoryMarshal.Write(data, ref manifestHeader);
  321. File.WriteAllBytes(GetManifestPath(), data);
  322. }
  323. /// <summary>
  324. /// Generate the path to the cache directory.
  325. /// </summary>
  326. /// <param name="baseCacheDirectory">The base of the cache directory</param>
  327. /// <param name="graphicsApi">The graphics api in use</param>
  328. /// <param name="shaderProvider">The name of the shader provider in use</param>
  329. /// <param name="cacheName">The name of the cache</param>
  330. /// <returns>The path to the cache directory</returns>
  331. private static string GenerateCachePath(string baseCacheDirectory, CacheGraphicsApi graphicsApi, string shaderProvider, string cacheName)
  332. {
  333. string graphicsApiName = graphicsApi switch
  334. {
  335. CacheGraphicsApi.OpenGL => "opengl",
  336. CacheGraphicsApi.OpenGLES => "opengles",
  337. CacheGraphicsApi.Vulkan => "vulkan",
  338. CacheGraphicsApi.DirectX => "directx",
  339. CacheGraphicsApi.Metal => "metal",
  340. CacheGraphicsApi.Guest => "guest",
  341. _ => throw new NotImplementedException(graphicsApi.ToString()),
  342. };
  343. return Path.Combine(baseCacheDirectory, graphicsApiName, shaderProvider, cacheName);
  344. }
  345. /// <summary>
  346. /// Get a cached file with the given hash.
  347. /// </summary>
  348. /// <param name="keyHash">The given hash</param>
  349. /// <returns>The cached file if present or null</returns>
  350. public byte[] GetValueRaw(ref Hash128 keyHash)
  351. {
  352. return GetValueRawFromArchive(ref keyHash) ?? GetValueRawFromFile(ref keyHash);
  353. }
  354. /// <summary>
  355. /// Get a cached file with the given hash that is present in the archive.
  356. /// </summary>
  357. /// <param name="keyHash">The given hash</param>
  358. /// <returns>The cached file if present or null</returns>
  359. private byte[] GetValueRawFromArchive(ref Hash128 keyHash)
  360. {
  361. bool found;
  362. lock (_hashTable)
  363. {
  364. found = _hashTable.Contains(keyHash);
  365. }
  366. if (found)
  367. {
  368. ZipArchiveEntry archiveEntry = _cacheArchive.GetEntry($"{keyHash}");
  369. if (archiveEntry != null)
  370. {
  371. try
  372. {
  373. byte[] result = new byte[archiveEntry.Length];
  374. using (Stream archiveStream = archiveEntry.Open())
  375. {
  376. archiveStream.Read(result);
  377. return result;
  378. }
  379. }
  380. catch (Exception e)
  381. {
  382. Logger.Error?.Print(LogClass.Gpu, $"Cannot load cache file {keyHash} from archive");
  383. Logger.Error?.Print(LogClass.Gpu, e.ToString());
  384. }
  385. }
  386. }
  387. return null;
  388. }
  389. /// <summary>
  390. /// Get a cached file with the given hash that is not present in the archive.
  391. /// </summary>
  392. /// <param name="keyHash">The given hash</param>
  393. /// <returns>The cached file if present or null</returns>
  394. private byte[] GetValueRawFromFile(ref Hash128 keyHash)
  395. {
  396. bool found;
  397. lock (_hashTable)
  398. {
  399. found = _hashTable.Contains(keyHash);
  400. }
  401. if (found)
  402. {
  403. string cacheTempFilePath = GenCacheTempFilePath(keyHash);
  404. try
  405. {
  406. return File.ReadAllBytes(GenCacheTempFilePath(keyHash));
  407. }
  408. catch (Exception e)
  409. {
  410. Logger.Error?.Print(LogClass.Gpu, $"Cannot load cache file at {cacheTempFilePath}");
  411. Logger.Error?.Print(LogClass.Gpu, e.ToString());
  412. }
  413. }
  414. return null;
  415. }
  416. private void HandleCacheTask(CacheFileOperationTask task)
  417. {
  418. switch (task.Type)
  419. {
  420. case CacheFileOperation.SaveTempEntry:
  421. SaveTempEntry((CacheFileSaveEntryTaskData)task.Data);
  422. break;
  423. case CacheFileOperation.SaveManifest:
  424. SaveManifest();
  425. break;
  426. case CacheFileOperation.RemoveManifestEntries:
  427. RemoveManifestEntries((HashSet<Hash128>)task.Data);
  428. break;
  429. case CacheFileOperation.FlushToArchive:
  430. FlushToArchive();
  431. break;
  432. case CacheFileOperation.Synchronize:
  433. ((ManualResetEvent)task.Data).Set();
  434. break;
  435. default:
  436. throw new NotImplementedException($"{task.Type}");
  437. }
  438. }
  439. /// <summary>
  440. /// Save a new entry in the temp cache.
  441. /// </summary>
  442. /// <param name="entry">The entry to save in the temp cache</param>
  443. private void SaveTempEntry(CacheFileSaveEntryTaskData entry)
  444. {
  445. string tempPath = GenCacheTempFilePath(entry.Key);
  446. File.WriteAllBytes(tempPath, entry.Value);
  447. }
  448. /// <summary>
  449. /// Add a new value in the cache with a given hash.
  450. /// </summary>
  451. /// <param name="keyHash">The hash to use for the value in the cache</param>
  452. /// <param name="value">The value to cache</param>
  453. public void AddValue(ref Hash128 keyHash, byte[] value)
  454. {
  455. Debug.Assert(value != null);
  456. Debug.Assert(GetValueRaw(ref keyHash) != null);
  457. bool isAlreadyPresent;
  458. lock (_hashTable)
  459. {
  460. isAlreadyPresent = !_hashTable.Add(keyHash);
  461. }
  462. if (isAlreadyPresent)
  463. {
  464. // NOTE: Used for debug
  465. File.WriteAllBytes(GenCacheTempFilePath(new Hash128()), value);
  466. throw new InvalidOperationException($"Cache collision found on {GenCacheTempFilePath(keyHash)}");
  467. }
  468. // Queue file change operations
  469. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  470. {
  471. Type = CacheFileOperation.SaveTempEntry,
  472. Data = new CacheFileSaveEntryTaskData
  473. {
  474. Key = keyHash,
  475. Value = value
  476. }
  477. });
  478. // Save the manifest changes
  479. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  480. {
  481. Type = CacheFileOperation.SaveManifest,
  482. });
  483. }
  484. /// <summary>
  485. /// Replace a value at the given hash in the cache.
  486. /// </summary>
  487. /// <param name="keyHash">The hash to use for the value in the cache</param>
  488. /// <param name="value">The value to cache</param>
  489. public void ReplaceValue(ref Hash128 keyHash, byte[] value)
  490. {
  491. Debug.Assert(value != null);
  492. // Only queue file change operations
  493. _fileWriterWorkerQueue.Add(new CacheFileOperationTask
  494. {
  495. Type = CacheFileOperation.SaveTempEntry,
  496. Data = new CacheFileSaveEntryTaskData
  497. {
  498. Key = keyHash,
  499. Value = value
  500. }
  501. });
  502. }
  503. public void Dispose()
  504. {
  505. Dispose(true);
  506. }
  507. protected virtual void Dispose(bool disposing)
  508. {
  509. if (disposing)
  510. {
  511. // Make sure all operations on _fileWriterWorkerQueue are done.
  512. Synchronize();
  513. _fileWriterWorkerQueue.Dispose();
  514. EnsureArchiveUpToDate();
  515. }
  516. }
  517. }
  518. }