CacheCollection.cs 20 KB

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