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