-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
Copy pathd3dx12Residency.h
1620 lines (1338 loc) · 60.4 KB
/
d3dx12Residency.h
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#pragma once
namespace D3DX12Residency
{
#if 0
#define RESIDENCY_CHECK(x) \
if((x) == false) { DebugBreak(); }
#define RESIDENCY_CHECK_RESULT(x) \
if((x) != S_OK) { DebugBreak(); }
#else
#define RESIDENCY_CHECK(x)
#define RESIDENCY_CHECK_RESULT(x) x
#endif
// Note: This library automatically runs in a single-threaded mode if ID3D12Device3 is supported.
#define RESIDENCY_SINGLE_THREADED 0
#define RESIDENCY_MIN(x,y) ((x) < (y) ? (x) : (y))
#define RESIDENCY_MAX(x,y) ((x) > (y) ? (x) : (y))
// This size can be tuned to your app in order to save space
#define MAX_NUM_CONCURRENT_CMD_LISTS 32
namespace Internal
{
class CriticalSection
{
friend class ScopedLock;
public:
CriticalSection()
{
InitializeCriticalSectionAndSpinCount(&CS, 8);
}
~CriticalSection()
{
DeleteCriticalSection(&CS);
}
private:
CRITICAL_SECTION CS;
};
class ScopedLock
{
public:
ScopedLock() : pCS(nullptr) {};
ScopedLock(CriticalSection* pCSIn) : pCS(pCSIn)
{
if (pCS)
{
EnterCriticalSection(&pCS->CS);
}
};
~ScopedLock()
{
if (pCS)
{
LeaveCriticalSection(&pCS->CS);
}
}
private:
CriticalSection* pCS;
};
// One per Residency Manager
class SyncManager
{
public:
SyncManager()
{
for (UINT32 i = 0; i < ARRAYSIZE(AvailableCommandLists); i++)
{
AvailableCommandLists[i] = false;
}
}
Internal::CriticalSection MaskCriticalSection;
static const UINT32 sUnsetValue = UINT32(-1);
// Represents which command lists are currently open for recording
bool AvailableCommandLists[MAX_NUM_CONCURRENT_CMD_LISTS];
};
//Forward Declaration
class ResidencyManagerInternal;
}
// Used to track meta data for each object the app potentially wants
// to make resident or evict.
class ManagedObject
{
public:
enum class RESIDENCY_STATUS
{
RESIDENT,
EVICTED
};
ManagedObject() :
pUnderlying(nullptr),
Size(0),
ResidencyStatus(RESIDENCY_STATUS::RESIDENT),
LastGPUSyncPoint(0),
LastUsedTimestamp(0)
{
memset(CommandListsUsedOn, 0, sizeof(CommandListsUsedOn));
}
void Initialize(ID3D12Pageable* pUnderlyingIn, UINT64 ObjectSize, UINT64 InitialGPUSyncPoint = 0)
{
RESIDENCY_CHECK(pUnderlying == nullptr);
pUnderlying = pUnderlyingIn;
Size = ObjectSize;
LastGPUSyncPoint = InitialGPUSyncPoint;
}
inline bool IsInitialized() { return pUnderlying != nullptr; }
// Wether the object is resident or not
RESIDENCY_STATUS ResidencyStatus;
// The underlying D3D Object being tracked
ID3D12Pageable* pUnderlying;
// The size of the D3D Object in bytes
UINT64 Size;
UINT64 LastGPUSyncPoint;
UINT64 LastUsedTimestamp;
// This is used to track which open command lists this resource is currently used on.
bool CommandListsUsedOn[MAX_NUM_CONCURRENT_CMD_LISTS];
// Linked list entry
LIST_ENTRY ListEntry;
};
// This represents a set of objects which are referenced by a command list i.e. every time a resource
// is bound for rendering, clearing, copy etc. the set must be updated to ensure the it is resident
// for execution.
class ResidencySet
{
friend class ResidencyManager;
friend class Internal::ResidencyManagerInternal;
public:
static const UINT32 InvalidIndex = (UINT32)-1;
ResidencySet() :
CommandListIndex(InvalidIndex),
MaxResidencySetSize(0),
CurrentSetSize(0),
ppSet(nullptr),
IsOpen(false),
OutOfMemory(false),
pSyncManager(nullptr)
{
};
~ResidencySet()
{
delete[](ppSet);
}
// Returns true if the object was inserted, false otherwise
inline bool Insert(ManagedObject* pObject)
{
RESIDENCY_CHECK(IsOpen);
RESIDENCY_CHECK(CommandListIndex != InvalidIndex);
// If we haven't seen this object on this command list mark it
if (pObject->CommandListsUsedOn[CommandListIndex] == false)
{
pObject->CommandListsUsedOn[CommandListIndex] = true;
if (ppSet == nullptr || CurrentSetSize >= MaxResidencySetSize)
{
Realloc();
}
if (ppSet == nullptr)
{
OutOfMemory = true;
return false;
}
ppSet[CurrentSetSize++] = pObject;
return true;
}
else
{
return false;
}
}
HRESULT Open()
{
Internal::ScopedLock Lock(&pSyncManager->MaskCriticalSection);
// It's invalid to open a set that is already open
if (IsOpen)
{
return E_INVALIDARG;
}
RESIDENCY_CHECK(CommandListIndex == InvalidIndex);
bool CommandlistAvailable = false;
// Find the first available command list by bitscanning
for (UINT32 i = 0; i < ARRAYSIZE(pSyncManager->AvailableCommandLists); i++)
{
if (pSyncManager->AvailableCommandLists[i] == false)
{
CommandListIndex = i;
pSyncManager->AvailableCommandLists[i] = true;
CommandlistAvailable = true;
break;
}
}
if (CommandlistAvailable == false)
{
// There are too many open residency sets, consider using less or increasing the value of MAX_NUM_CONCURRENT_CMD_LISTS
RESIDENCY_CHECK(false);
return E_OUTOFMEMORY;
}
CurrentSetSize = 0;
IsOpen = true;
OutOfMemory = false;
return S_OK;
}
HRESULT Close()
{
if (IsOpen == false)
{
return E_INVALIDARG;
}
if (OutOfMemory == true)
{
return E_OUTOFMEMORY;
}
for (INT32 i = 0; i < CurrentSetSize; i++)
{
Remove(ppSet[i]);
}
ReturnCommandListReservation();
IsOpen = false;
return S_OK;
}
private:
inline void Remove(ManagedObject* pObject)
{
pObject->CommandListsUsedOn[CommandListIndex] = false;
}
inline void ReturnCommandListReservation()
{
Internal::ScopedLock Lock(&pSyncManager->MaskCriticalSection);
pSyncManager->AvailableCommandLists[CommandListIndex] = false;
CommandListIndex = ResidencySet::InvalidIndex;
IsOpen = false;
}
void Initialize(Internal::SyncManager* pSyncManagerIn)
{
pSyncManager = pSyncManagerIn;
}
bool Initialize(Internal::SyncManager* pSyncManagerIn, UINT32 MaxSize)
{
pSyncManager = pSyncManagerIn;
MaxResidencySetSize = MaxSize;
ppSet = new ManagedObject*[MaxResidencySetSize];
return ppSet != nullptr;
}
inline void Realloc()
{
MaxResidencySetSize = (MaxResidencySetSize == 0) ? 4096 : INT32(MaxResidencySetSize + (MaxResidencySetSize / 2.0f));
ManagedObject** ppNewAlloc = new ManagedObject*[MaxResidencySetSize];
if (ppSet && ppNewAlloc)
{
memcpy(ppNewAlloc, ppSet, CurrentSetSize * sizeof(ManagedObject*));
delete[](ppSet);
}
ppSet = ppNewAlloc;
}
UINT32 CommandListIndex;
ManagedObject** ppSet;
INT32 MaxResidencySetSize;
INT32 CurrentSetSize;
bool IsOpen;
bool OutOfMemory;
Internal::SyncManager* pSyncManager;
};
namespace Internal
{
/* List Helpers */
inline void InitializeListHead(LIST_ENTRY* pHead)
{
pHead->Flink = pHead->Blink = pHead;
}
inline void InsertHeadList(LIST_ENTRY* pHead, LIST_ENTRY* pEntry)
{
pEntry->Blink = pHead;
pEntry->Flink = pHead->Flink;
pHead->Flink->Blink = pEntry;
pHead->Flink = pEntry;
}
inline void InsertTailList(LIST_ENTRY* pHead, LIST_ENTRY* pEntry)
{
pEntry->Flink = pHead;
pEntry->Blink = pHead->Blink;
pHead->Blink->Flink = pEntry;
pHead->Blink = pEntry;
}
inline void RemoveEntryList(LIST_ENTRY* pEntry)
{
pEntry->Blink->Flink = pEntry->Flink;
pEntry->Flink->Blink = pEntry->Blink;
}
inline LIST_ENTRY* RemoveHeadList(LIST_ENTRY* pHead)
{
LIST_ENTRY* pEntry = pHead->Flink;
Internal::RemoveEntryList(pEntry);
return pEntry;
}
inline LIST_ENTRY* RemoveTailList(LIST_ENTRY* pHead)
{
LIST_ENTRY* pEntry = pHead->Blink;
Internal::RemoveEntryList(pEntry);
return pEntry;
}
inline bool IsListEmpty(LIST_ENTRY* pEntry)
{
return pEntry->Flink == pEntry;
}
struct Fence
{
Fence(UINT64 StartingValue) : pFence(nullptr), FenceValue(StartingValue)
{
Internal::InitializeListHead(&ListEntry);
};
HRESULT Initialize(ID3D12Device* pDevice)
{
HRESULT hr = pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&pFence));
RESIDENCY_CHECK_RESULT(hr);
return hr;
}
void Destroy()
{
if (pFence)
{
pFence->Release();
pFence = nullptr;
}
}
HRESULT GPUWait(ID3D12CommandQueue* pQueue)
{
HRESULT hr = pQueue->Wait(pFence, FenceValue);
RESIDENCY_CHECK_RESULT(hr);
return hr;
}
HRESULT GPUSignal(ID3D12CommandQueue* pQueue)
{
HRESULT hr = pQueue->Signal(pFence, FenceValue);
RESIDENCY_CHECK_RESULT(hr);
return hr;
}
inline void Increment()
{
FenceValue++;
}
ID3D12Fence* pFence;
UINT64 FenceValue;
LIST_ENTRY ListEntry;
};
// Represents a time on a particular queue that a resource was used
struct QueueSyncPoint
{
QueueSyncPoint() : pFence(nullptr), LastUsedValue(0) {};
inline bool IsCompleted() { return LastUsedValue <= pFence->pFence->GetCompletedValue(); }
inline void WaitForCompletion(HANDLE Event)
{
RESIDENCY_CHECK_RESULT(pFence->pFence->SetEventOnCompletion(LastUsedValue, Event));
RESIDENCY_CHECK_RESULT(WaitForSingleObject(Event, INFINITE));
}
Fence* pFence;
UINT64 LastUsedValue;
};
struct DeviceWideSyncPoint
{
DeviceWideSyncPoint(UINT32 NumQueues, UINT64 Generation) :
GenerationID(Generation), NumQueueSyncPoints(NumQueues) {};
// Create the whole structure in one allocation for locality
static DeviceWideSyncPoint* CreateSyncPoint(UINT32 NumQueues, UINT64 Generation)
{
DeviceWideSyncPoint* pSyncPoint = nullptr;
const SIZE_T Size = sizeof(DeviceWideSyncPoint) + (sizeof(QueueSyncPoint) * (NumQueues - 1));
BYTE* pAlloc = new BYTE[Size];
if (pAlloc && Size >= sizeof(DeviceWideSyncPoint))
{
pSyncPoint = new (pAlloc) DeviceWideSyncPoint(NumQueues, Generation);
}
return pSyncPoint;
}
// A device wide fence is completed if all of the queues that were active at that point are completed
inline bool IsCompleted()
{
for (UINT32 i = 0; i < NumQueueSyncPoints; i++)
{
if (pQueueSyncPoints[i].IsCompleted() == false)
{
return false;
}
}
return true;
}
inline void WaitForCompletion(HANDLE Event)
{
for (UINT32 i = 0; i < NumQueueSyncPoints; i++)
{
if (pQueueSyncPoints[i].IsCompleted() == false)
{
pQueueSyncPoints[i].WaitForCompletion(Event);
}
}
}
const UINT64 GenerationID;
const UINT32 NumQueueSyncPoints;
LIST_ENTRY ListEntry;
// NumQueueSyncPoints QueueSyncPoints will be placed below here
QueueSyncPoint pQueueSyncPoints[1];
};
// A Least Recently Used Cache. Tracks all of the objects requested by the app so that objects
// that aren't used freqently can get evicted to help the app stay under buget.
class LRUCache
{
public:
LRUCache() :
NumResidentObjects(0),
NumEvictedObjects(0),
ResidentSize(0)
{
Internal::InitializeListHead(&ResidentObjectListHead);
Internal::InitializeListHead(&EvictedObjectListHead);
};
void Insert(ManagedObject* pObject)
{
if (pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::RESIDENT)
{
Internal::InsertHeadList(&ResidentObjectListHead, &pObject->ListEntry);
NumResidentObjects++;
ResidentSize += pObject->Size;
}
else
{
Internal::InsertHeadList(&EvictedObjectListHead, &pObject->ListEntry);
NumEvictedObjects++;
}
}
void Remove(ManagedObject* pObject)
{
Internal::RemoveEntryList(&pObject->ListEntry);
if (pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::RESIDENT)
{
NumResidentObjects--;
ResidentSize -= pObject->Size;
}
else
{
NumEvictedObjects--;
}
}
// When an object is used by the GPU we move it to the end of the list.
// This way things closer to the head of the list are the objects which
// are stale and better candidates for eviction
void ObjectReferenced(ManagedObject* pObject)
{
RESIDENCY_CHECK(pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::RESIDENT);
Internal::RemoveEntryList(&pObject->ListEntry);
Internal::InsertTailList(&ResidentObjectListHead, &pObject->ListEntry);
}
void MakeResident(ManagedObject* pObject)
{
RESIDENCY_CHECK(pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::EVICTED);
pObject->ResidencyStatus = ManagedObject::RESIDENCY_STATUS::RESIDENT;
Internal::RemoveEntryList(&pObject->ListEntry);
Internal::InsertTailList(&ResidentObjectListHead, &pObject->ListEntry);
NumEvictedObjects--;
NumResidentObjects++;
ResidentSize += pObject->Size;
}
void Evict(ManagedObject* pObject)
{
RESIDENCY_CHECK(pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::RESIDENT);
pObject->ResidencyStatus = ManagedObject::RESIDENCY_STATUS::EVICTED;
Internal::RemoveEntryList(&pObject->ListEntry);
Internal::InsertTailList(&EvictedObjectListHead, &pObject->ListEntry);
NumResidentObjects--;
ResidentSize -= pObject->Size;
NumEvictedObjects++;
}
// Evict all of the resident objects used in sync points up to the specficied one (inclusive)
void TrimToSyncPointInclusive(INT64 CurrentUsage, INT64 CurrentBudget, ID3D12Pageable** EvictionList, UINT32& NumObjectsToEvict, UINT64 SyncPoint)
{
NumObjectsToEvict = 0;
LIST_ENTRY* pResourceEntry = ResidentObjectListHead.Flink;
while (pResourceEntry != &ResidentObjectListHead)
{
ManagedObject* pObject = CONTAINING_RECORD(pResourceEntry, ManagedObject, ListEntry);
if (pObject->LastGPUSyncPoint > SyncPoint || CurrentUsage < CurrentBudget)
{
break;
}
RESIDENCY_CHECK(pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::RESIDENT);
EvictionList[NumObjectsToEvict++] = pObject->pUnderlying;
Evict(pObject);
CurrentUsage -= pObject->Size;
pResourceEntry = ResidentObjectListHead.Flink;
}
}
// Trim all objects which are older than the specified time
void TrimAgedAllocations(DeviceWideSyncPoint* MaxSyncPoint, ID3D12Pageable** EvictionList, UINT32& NumObjectsToEvict, UINT64 CurrentTimeStamp, UINT64 MinDelta)
{
LIST_ENTRY* pResourceEntry = ResidentObjectListHead.Flink;
while (pResourceEntry != &ResidentObjectListHead)
{
ManagedObject* pObject = CONTAINING_RECORD(pResourceEntry, ManagedObject, ListEntry);
if ((MaxSyncPoint && pObject->LastGPUSyncPoint >= MaxSyncPoint->GenerationID) || // Only trim allocations done on the GPU
CurrentTimeStamp - pObject->LastUsedTimestamp <= MinDelta) // Don't evict things which have been used recently
{
break;
}
RESIDENCY_CHECK(pObject->ResidencyStatus == ManagedObject::RESIDENCY_STATUS::RESIDENT);
EvictionList[NumObjectsToEvict++] = pObject->pUnderlying;
Evict(pObject);
pResourceEntry = ResidentObjectListHead.Flink;
}
}
ManagedObject* GetResidentListHead()
{
if (IsListEmpty(&ResidentObjectListHead))
{
return nullptr;
}
return CONTAINING_RECORD(ResidentObjectListHead.Flink, ManagedObject, ListEntry);
}
LIST_ENTRY ResidentObjectListHead;
LIST_ENTRY EvictedObjectListHead;
UINT32 NumResidentObjects;
UINT32 NumEvictedObjects;
UINT64 ResidentSize;
};
class ResidencyManagerInternal
{
public:
ResidencyManagerInternal(SyncManager* pSyncManagerIn) :
Device(nullptr),
Device3(nullptr),
#ifdef __ID3D12DeviceDownlevel_INTERFACE_DEFINED__
DeviceDownlevel(nullptr),
#endif
AsyncThreadFence(0),
CompletionEvent(INVALID_HANDLE_VALUE),
AsyncThreadWorkCompletionEvent(INVALID_HANDLE_VALUE),
Adapter(nullptr),
AsyncWorkEvent(INVALID_HANDLE_VALUE),
AsyncWorkThread(INVALID_HANDLE_VALUE),
FinishAsyncWork(false),
cStartEvicted(false),
CurrentSyncPointGeneration(0),
NumQueuesSeen(0),
NodeIndex(0),
CurrentAsyncWorkloadHead(0),
CurrentAsyncWorkloadTail(0),
cMinEvictionGracePeriod(1.0f),
cMaxEvictionGracePeriod(60.0f),
cTrimPercentageMemoryUsageThreshold(0.7f),
AsyncWorkQueue(nullptr),
MaxSoftwareQueueLatency(6),
AsyncWorkQueueSize(7),
pSyncManager(pSyncManagerIn)
{
Internal::InitializeListHead(&QueueFencesListHead);
Internal::InitializeListHead(&InFlightSyncPointsHead);
BOOL LuidSuccess = AllocateLocallyUniqueId(&ResidencyManagerUniqueID);
RESIDENCY_CHECK(LuidSuccess);
UNREFERENCED_PARAMETER(LuidSuccess);
};
// NOTE: DeviceNodeIndex is an index not a mask. The majority of D3D12 uses bit masks to identify a GPU node whereas DXGI uses 0 based indices.
HRESULT Initialize(ID3D12Device* ParentDevice, UINT DeviceNodeIndex, IDXGIAdapter* ParentAdapter, UINT32 MaxLatency)
{
Device = ParentDevice;
NodeIndex = DeviceNodeIndex;
MaxSoftwareQueueLatency = MaxLatency;
// Try to query for the device interface with a queued MakeResident API.
if (FAILED(Device->QueryInterface(&Device3)))
{
// The queued MakeResident API is not available. Start the paging fence at 1.
AsyncThreadFence.Increment();
}
#ifdef __ID3D12DeviceDownlevel_INTERFACE_DEFINED__
Device->QueryInterface(&DeviceDownlevel);
#endif
if (ParentAdapter)
{
ParentAdapter->QueryInterface(&Adapter);
}
AsyncWorkQueueSize = MaxLatency + 1;
AsyncWorkQueue = new AsyncWorkload[AsyncWorkQueueSize];
if (AsyncWorkQueue == nullptr)
{
return E_OUTOFMEMORY;
}
LARGE_INTEGER Frequency;
QueryPerformanceFrequency(&Frequency);
// Calculate how many QPC ticks are equivalent to the given time in seconds
MinEvictionGracePeriodTicks = UINT64(Frequency.QuadPart * cMinEvictionGracePeriod);
MaxEvictionGracePeriodTicks = UINT64(Frequency.QuadPart * cMaxEvictionGracePeriod);
HRESULT hr = S_OK;
hr = AsyncThreadFence.Initialize(Device);
if (SUCCEEDED(hr))
{
CompletionEvent = CreateEvent(nullptr, false, false, nullptr);
if (CompletionEvent == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
if (SUCCEEDED(hr))
{
AsyncThreadWorkCompletionEvent = CreateEvent(nullptr, false, false, nullptr);
if (AsyncThreadWorkCompletionEvent == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
if (SUCCEEDED(hr))
{
AsyncWorkEvent = CreateEvent(nullptr, true, false, nullptr);
if (AsyncWorkEvent == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
#if !RESIDENCY_SINGLE_THREADED
if (SUCCEEDED(hr) && !Device3)
{
AsyncWorkThread = CreateThread(nullptr, 0, AsyncThreadStart, (void*) this, 0, nullptr);
if (AsyncWorkThread == INVALID_HANDLE_VALUE)
{
hr = HRESULT_FROM_WIN32(GetLastError());
}
}
#endif
return hr;
}
void Destroy()
{
AsyncThreadFence.Destroy();
if (CompletionEvent != INVALID_HANDLE_VALUE)
{
CloseHandle(CompletionEvent);
CompletionEvent = INVALID_HANDLE_VALUE;
}
#if !RESIDENCY_SINGLE_THREADED
AsyncWorkload* pWork = DequeueAsyncWork();
while (pWork)
{
pWork = DequeueAsyncWork();
}
FinishAsyncWork = true;
if (SetEvent(AsyncWorkEvent) == false)
{
RESIDENCY_CHECK_RESULT(HRESULT_FROM_WIN32(GetLastError()));
}
// Make sure the async worker thread is finished to prevent dereferencing
// dangling pointers to ResidencyManagerInternal
if (AsyncWorkThread != INVALID_HANDLE_VALUE)
{
WaitForSingleObject(AsyncWorkThread, INFINITE);
CloseHandle(AsyncWorkThread);
AsyncWorkThread = INVALID_HANDLE_VALUE;
}
if (AsyncWorkEvent != INVALID_HANDLE_VALUE)
{
CloseHandle(AsyncWorkEvent);
AsyncWorkEvent = INVALID_HANDLE_VALUE;
}
#endif
if (AsyncThreadWorkCompletionEvent != INVALID_HANDLE_VALUE)
{
CloseHandle(AsyncThreadWorkCompletionEvent);
AsyncThreadWorkCompletionEvent = INVALID_HANDLE_VALUE;
}
while (Internal::IsListEmpty(&QueueFencesListHead) == false)
{
Internal::Fence* pObject =
CONTAINING_RECORD(QueueFencesListHead.Flink, Internal::Fence, ListEntry);
pObject->Destroy();
Internal::RemoveHeadList(&QueueFencesListHead);
delete(pObject);
}
while (Internal::IsListEmpty(&InFlightSyncPointsHead) == false)
{
Internal::DeviceWideSyncPoint* pPoint =
CONTAINING_RECORD(InFlightSyncPointsHead.Flink, Internal::DeviceWideSyncPoint, ListEntry);
Internal::RemoveHeadList(&InFlightSyncPointsHead);
delete pPoint;
}
delete [] AsyncWorkQueue;
if (Device3)
{
Device3->Release();
Device3 = nullptr;
}
#ifdef __ID3D12DeviceDownlevel_INTERFACE_DEFINED__
if (DeviceDownlevel)
{
DeviceDownlevel->Release();
DeviceDownlevel = nullptr;
}
#endif
if (Adapter)
{
Adapter->Release();
Adapter = nullptr;
}
}
void BeginTrackingObject(ManagedObject* pObject)
{
Internal::ScopedLock Lock(&Mutex);
if (pObject)
{
RESIDENCY_CHECK(pObject->pUnderlying != nullptr);
if (cStartEvicted)
{
pObject->ResidencyStatus = ManagedObject::RESIDENCY_STATUS::EVICTED;
RESIDENCY_CHECK_RESULT(Device->Evict(1, &pObject->pUnderlying));
}
LRU.Insert(pObject);
}
}
void EndTrackingObject(ManagedObject* pObject)
{
Internal::ScopedLock Lock(&Mutex);
LRU.Remove(pObject);
}
// One residency set per command-list
HRESULT ExecuteCommandLists(ID3D12CommandQueue* Queue, ID3D12CommandList** CommandLists, ResidencySet** ResidencySets, UINT32 Count)
{
return ExecuteSubset(Queue, CommandLists, ResidencySets, Count);
}
HRESULT GetCurrentGPUSyncPoint(ID3D12CommandQueue* Queue, UINT64 *pGPUSyncPoint)
{
Internal::Fence* QueueFence = nullptr;
HRESULT hr = GetFence(Queue, QueueFence);
// The signal and increment need to be atomic
if(SUCCEEDED(hr))
{
Internal::ScopedLock Lock(&ExecutionCS);
*pGPUSyncPoint = QueueFence->FenceValue;
hr = SignalFence(Queue, QueueFence);
}
return hr;
}
private:
HRESULT GetFence(ID3D12CommandQueue *Queue, Internal::Fence *&QueueFence)
{
// We have to track each object on each queue so we know when it is safe to evict them. Therefore, for every queue that we
// see, associate a fence with it
GUID FenceGuid = { 0xf0, 0, 0xd, { 0, 0, 0, 0, 0, 0, 0, 0 } };
memcpy(&FenceGuid.Data4, &ResidencyManagerUniqueID, sizeof(ResidencyManagerUniqueID));
QueueFence = nullptr;
HRESULT hr = S_OK;
struct
{
Internal::Fence* pFence;
} CommandQueuePrivateData;
// Find or create the fence for this queue
{
UINT32 Size = sizeof(CommandQueuePrivateData);
hr = Queue->GetPrivateData(FenceGuid, &Size, &CommandQueuePrivateData);
if (FAILED(hr))
{
QueueFence = new Internal::Fence(1);
hr = QueueFence->Initialize(Device);
Internal::InsertTailList(&QueueFencesListHead, &QueueFence->ListEntry);
InterlockedIncrement(&NumQueuesSeen);
if (SUCCEEDED(hr))
{
CommandQueuePrivateData = { QueueFence };
hr = Queue->SetPrivateData(FenceGuid, UINT32(sizeof(CommandQueuePrivateData)), &CommandQueuePrivateData);
RESIDENCY_CHECK_RESULT(hr);
}
}
QueueFence = CommandQueuePrivateData.pFence;
RESIDENCY_CHECK(QueueFence != nullptr);
}
return hr;
}
HRESULT SignalFence(ID3D12CommandQueue *Queue, Internal::Fence *QueueFence)
{
// When this fence is passed it is safe to evict the resources used in the list just submitted
HRESULT hr = QueueFence->GPUSignal(Queue);
QueueFence->Increment();
if (SUCCEEDED(hr))
{
hr = EnqueueSyncPoint();
RESIDENCY_CHECK_RESULT(hr);
}
CurrentSyncPointGeneration++;
return hr;
}
HRESULT ExecuteSubset(ID3D12CommandQueue* Queue, ID3D12CommandList** CommandLists, ResidencySet** ResidencySets, UINT32 Count)
{
HRESULT hr = S_OK;
DXGI_QUERY_VIDEO_MEMORY_INFO LocalMemory;
ZeroMemory(&LocalMemory, sizeof(LocalMemory));
GetCurrentBudget(&LocalMemory, DXGI_MEMORY_SEGMENT_GROUP_LOCAL);
DXGI_QUERY_VIDEO_MEMORY_INFO NonLocalMemory;
ZeroMemory(&NonLocalMemory, sizeof(NonLocalMemory));
GetCurrentBudget(&NonLocalMemory, DXGI_MEMORY_SEGMENT_GROUP_NON_LOCAL);
UINT64 TotalSizeNeeded = 0;
UINT32 MaxObjectsReferenced = 0;
for (UINT32 i = 0; i < Count; i++)
{
if (ResidencySets[i])
{
if (ResidencySets[i]->IsOpen)
{
// Residency Sets must be closed before execution just like Command Lists
return E_INVALIDARG;
}
MaxObjectsReferenced += ResidencySets[i]->CurrentSetSize;
}
}
// Create a set to gather up all unique resources required by this call
ResidencySet* pMasterSet = new ResidencySet();
if (pMasterSet == nullptr || pMasterSet->Initialize(pSyncManager, MaxObjectsReferenced) == false)
{
return E_OUTOFMEMORY;
}
hr = pMasterSet->Open();
if (FAILED(hr))
{
return hr;
}
// For each residency set
for (UINT32 i = 0; i < Count; i++)
{