CacheCollection.cs 18 KB

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