-
Notifications
You must be signed in to change notification settings - Fork 188
Expand file tree
/
Copy pathPresentMonTraceConsumer.cpp
More file actions
3736 lines (3348 loc) · 156 KB
/
PresentMonTraceConsumer.cpp
File metadata and controls
3736 lines (3348 loc) · 156 KB
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) 2017-2024 Intel Corporation
// Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved
// SPDX-License-Identifier: MIT
#include "PresentMonTraceConsumer.hpp"
#include "ETW/Intel_PresentMon.h"
#include "ETW/Microsoft_Windows_D3D9.h"
#include "ETW/Microsoft_Windows_Dwm_Core.h"
#include "ETW/Microsoft_Windows_Dwm_Core_Win7.h"
#include "ETW/Microsoft_Windows_DXGI.h"
#include "ETW/Microsoft_Windows_DxgKrnl.h"
#include "ETW/Microsoft_Windows_DxgKrnl_Win7.h"
#include "ETW/Microsoft_Windows_EventMetadata.h"
#include "ETW/Microsoft_Windows_Kernel_Process.h"
#include "ETW/Microsoft_Windows_Win32k.h"
#include "ETW/Nvidia_PCL.h"
#include <algorithm>
#include <assert.h>
#include <d3d9.h>
#include <dxgi.h>
#include <stdlib.h>
#include <unordered_set>
static uint32_t gNextFrameId = 1;
static inline uint64_t GenerateVidPnLayerId(uint32_t vidPnSourceId, uint32_t layerIndex)
{
return (((uint64_t) vidPnSourceId) << 32) | (uint64_t) layerIndex;
}
static inline FrameType ConvertPMPFrameTypeToFrameType(Intel_PresentMon::FrameType frameType)
{
switch (frameType) {
case Intel_PresentMon::FrameType::Unspecified: return FrameType::Unspecified;
case Intel_PresentMon::FrameType::Original: return FrameType::Application;
case Intel_PresentMon::FrameType::Repeated: return FrameType::Repeated;
case Intel_PresentMon::FrameType::Intel_XEFG: return FrameType::Intel_XEFG;
case Intel_PresentMon::FrameType::AMD_AFMF: return FrameType::AMD_AFMF;
}
DebugAssert(false);
return FrameType::Unspecified;
}
// Returns true if a ScreenTime has been set for this present.
static inline bool HasScreenTime(std::shared_ptr<PresentEvent> const& p)
{
for (auto const& pr : p->Displayed) {
if (pr.second != 0) {
return true;
}
}
return false;
}
// Set a ScreenTime for this present.
//
// If a ScreenTime has not yet been set, add it to Displayed and set Presented.
//
// Otherwise, if the set ScreenTime has no FrameType, overwrite both ScreenTime and FrameType.
//
// Otherwise, if the set ScreenTime is zero, overwrite ScreenTime.
//
// Otherwise, if the call has a FrameType, add it to the list.
static inline void SetScreenTime(std::shared_ptr<PresentEvent> const& p, uint64_t screenTime, FrameType frameType = FrameType::NotSet)
{
DebugAssert(screenTime != 0);
auto displayedCount = p->Displayed.size();
if (displayedCount == 0) {
p->Displayed.emplace_back(frameType, screenTime);
p->FinalState = PresentResult::Presented;
} else if (p->Displayed.back().first == FrameType::NotSet) {
p->Displayed.back().first = frameType;
p->Displayed.back().second = screenTime;
} else if (p->Displayed.back().second == 0) {
DebugAssert(frameType == FrameType::NotSet);
for (size_t i = 0; i < displayedCount; ++i) {
if (p->Displayed[i].second == 0) {
p->Displayed.back().second = screenTime;
p->FinalState = PresentResult::Presented;
break;
}
}
} else if (frameType != FrameType::NotSet) {
p->Displayed.emplace_back(frameType, screenTime);
}
}
namespace {
struct WaitOnAddressShim {
using WaitOnAddressFn = BOOL(WINAPI*)(volatile VOID* Address, PVOID CompareAddress, SIZE_T AddressSize, DWORD dwMilliseconds);
using WakeByAddressAllFn = VOID(WINAPI*)(PVOID Address);
WaitOnAddressFn Wait = nullptr;
WakeByAddressAllFn WakeAll = nullptr;
bool Available() const noexcept { return Wait && WakeAll; }
};
static const WaitOnAddressShim& GetWaitOnAddressShim()
{
static WaitOnAddressShim shim = [] {
WaitOnAddressShim s{};
HMODULE k32 = ::GetModuleHandleW(L"kernel32.dll");
if (!k32) return s;
s.Wait = reinterpret_cast<WaitOnAddressShim::WaitOnAddressFn>(::GetProcAddress(k32, "WaitOnAddress"));
s.WakeAll = reinterpret_cast<WaitOnAddressShim::WakeByAddressAllFn>(::GetProcAddress(k32, "WakeByAddressAll"));
return s;
}();
return shim;
}
} // namespace
PresentEvent::PresentEvent()
: PresentStartTime(0)
, ProcessId(0)
, ThreadId(0)
, TimeInPresent(0)
, GPUStartTime(0)
, ReadyTime(0)
, GPUDuration(0)
, GPUVideoDuration(0)
, InputTime(0)
, MouseClickTime(0)
, AppPropagatedPresentStartTime(0)
, AppPropagatedTimeInPresent(0)
, AppPropagatedGPUStartTime(0)
, AppPropagatedReadyTime(0)
, AppPropagatedGPUDuration(0)
, AppPropagatedGPUVideoDuration(0)
, AppFrameId(0)
, AppSleepStartTime(0)
, AppSleepEndTime(0)
, AppSimStartTime(0)
, AppSimEndTime(0)
, AppRenderSubmitStartTime(0)
, AppRenderSubmitEndTime(0)
, AppPresentStartTime(0)
, AppPresentEndTime(0)
, AppInputSample{ 0, InputDeviceType::None }
, SwapChainAddress(0)
, SyncInterval(-1)
, PresentFlags(0)
, CompositionSurfaceLuid(0)
, Win32KPresentCount(0)
, Win32KBindId(0)
, DxgkPresentHistoryToken(0)
, DxgkPresentHistoryTokenData(0)
, DxgkContext(0)
, Hwnd(0)
, QueueSubmitSequence(0)
, RingIndex(UINT32_MAX)
, DestWidth(0)
, DestHeight(0)
, DriverThreadId(0)
, FrameId(gNextFrameId++)
, Runtime(Runtime::Other)
, PresentMode(PresentMode::Unknown)
, FinalState(PresentResult::Unknown)
, InputType(InputDeviceType::None)
, SupportsTearing(false)
, WaitForFlipEvent(false)
, WaitForMPOFlipEvent(false)
, SeenDxgkPresent(false)
, SeenWin32KEvents(false)
, SeenInFrameEvent(false)
, GpuFrameCompleted(false)
, IsCompleted(false)
, IsLost(false)
, PresentFailed(false)
, IsHybridPresent(false)
, PresentInDwmWaitingStruct(false)
, WaitingForPresentStop(false)
, WaitingForFlipFrameType(false)
, DoneWaitingForFlipFrameType(false)
, WaitingForFrameId(false)
{
}
PresentEvent::PresentEvent(uint32_t fid)
: PresentStartTime(0)
, ProcessId(0)
, ThreadId(0)
, TimeInPresent(0)
, GPUStartTime(0)
, ReadyTime(0)
, GPUDuration(0)
, GPUVideoDuration(0)
, InputTime(0)
, MouseClickTime(0)
, AppPropagatedPresentStartTime(0)
, AppPropagatedTimeInPresent(0)
, AppPropagatedGPUStartTime(0)
, AppPropagatedReadyTime(0)
, AppPropagatedGPUDuration(0)
, AppPropagatedGPUVideoDuration(0)
, AppFrameId(0)
, AppSleepStartTime(0)
, AppSleepEndTime(0)
, AppSimStartTime(0)
, AppSimEndTime(0)
, AppRenderSubmitStartTime(0)
, AppRenderSubmitEndTime(0)
, AppPresentStartTime(0)
, AppPresentEndTime(0)
, AppInputSample{ 0, InputDeviceType::None }
, SwapChainAddress(0)
, SyncInterval(-1)
, PresentFlags(0)
, CompositionSurfaceLuid(0)
, Win32KPresentCount(0)
, Win32KBindId(0)
, DxgkPresentHistoryToken(0)
, DxgkPresentHistoryTokenData(0)
, DxgkContext(0)
, Hwnd(0)
, QueueSubmitSequence(0)
, RingIndex(UINT32_MAX)
, DestWidth(0)
, DestHeight(0)
, DriverThreadId(0)
, FrameId(fid)
, Runtime(Runtime::Other)
, PresentMode(PresentMode::Unknown)
, FinalState(PresentResult::Unknown)
, InputType(InputDeviceType::None)
, SupportsTearing(false)
, WaitForFlipEvent(false)
, WaitForMPOFlipEvent(false)
, SeenDxgkPresent(false)
, SeenWin32KEvents(false)
, SeenInFrameEvent(false)
, GpuFrameCompleted(false)
, IsCompleted(false)
, IsLost(false)
, PresentFailed(false)
, IsHybridPresent(false)
, PresentInDwmWaitingStruct(false)
, WaitingForPresentStop(false)
, WaitingForFlipFrameType(false)
, DoneWaitingForFlipFrameType(false)
, WaitingForFrameId(false)
{
}
PMTraceConsumer::PMTraceConsumer()
: mTrackedPresents(PRESENTEVENT_CIRCULAR_BUFFER_SIZE)
, mCompletedPresents(PRESENTEVENT_CIRCULAR_BUFFER_SIZE)
, mCircularBufferSize(PRESENTEVENT_CIRCULAR_BUFFER_SIZE)
, mGpuTrace(this)
{
hEventsReadyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
}
PMTraceConsumer::PMTraceConsumer(uint32_t circularBufferSize)
: mTrackedPresents(circularBufferSize)
, mCompletedPresents(circularBufferSize)
, mCircularBufferSize(circularBufferSize)
, mGpuTrace(this)
{
hEventsReadyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
}
PMTraceConsumer::~PMTraceConsumer()
{
if (hEventsReadyEvent && hEventsReadyEvent != INVALID_HANDLE_VALUE) {
CloseHandle(hEventsReadyEvent);
}
}
void PMTraceConsumer::HandleD3D9Event(EVENT_RECORD* pEventRecord)
{
auto const& hdr = pEventRecord->EventHeader;
switch (hdr.EventDescriptor.Id) {
case Microsoft_Windows_D3D9::Present_Start::Id:
if (IsProcessTrackedForFiltering(hdr.ProcessId)) {
EventDataDesc desc[] = {
{ L"pSwapchain" },
{ L"Flags" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto pSwapchain = desc[0].GetData<uint64_t>();
auto Flags = desc[1].GetData<uint32_t>();
uint32_t dxgiPresentFlags = 0;
if (Flags & D3DPRESENT_DONOTFLIP) dxgiPresentFlags |= DXGI_PRESENT_DO_NOT_SEQUENCE;
if (Flags & D3DPRESENT_DONOTWAIT) dxgiPresentFlags |= DXGI_PRESENT_DO_NOT_WAIT;
if (Flags & D3DPRESENT_FLIPRESTART) dxgiPresentFlags |= DXGI_PRESENT_RESTART;
int32_t syncInterval = -1;
if (Flags & D3DPRESENT_FORCEIMMEDIATE) {
syncInterval = 0;
}
RuntimePresentStart(Runtime::D3D9, hdr, pSwapchain, dxgiPresentFlags, syncInterval);
}
break;
case Microsoft_Windows_D3D9::Present_Stop::Id:
if (IsProcessTrackedForFiltering(hdr.ProcessId)) {
RuntimePresentStop(Runtime::D3D9, hdr, mMetadata.GetEventData<uint32_t>(pEventRecord, L"Result"));
}
break;
default:
assert(!mFilteredEvents); // Assert that filtering is working if expected
break;
}
}
void PMTraceConsumer::HandleDXGIEvent(EVENT_RECORD* pEventRecord)
{
auto const& hdr = pEventRecord->EventHeader;
switch (hdr.EventDescriptor.Id) {
case Microsoft_Windows_DXGI::Present_Start::Id:
case Microsoft_Windows_DXGI::PresentMultiplaneOverlay_Start::Id:
if (IsProcessTrackedForFiltering(hdr.ProcessId)) {
EventDataDesc desc[] = {
{ L"pIDXGISwapChain" },
{ L"Flags" },
{ L"SyncInterval" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto pSwapChain = desc[0].GetData<uint64_t>();
auto Flags = desc[1].GetData<uint32_t>();
auto SyncInterval = desc[2].GetData<int32_t>();
RuntimePresentStart(Runtime::DXGI, hdr, pSwapChain, Flags, SyncInterval);
}
break;
case Microsoft_Windows_DXGI::Present_Stop::Id:
case Microsoft_Windows_DXGI::PresentMultiplaneOverlay_Stop::Id:
if (IsProcessTrackedForFiltering(hdr.ProcessId)) {
RuntimePresentStop(Runtime::DXGI, hdr, mMetadata.GetEventData<uint32_t>(pEventRecord, L"Result"));
}
break;
case Microsoft_Windows_DXGI::SwapChain_Start::Id:
case Microsoft_Windows_DXGI::ResizeBuffers_Start::Id:
if (mTrackHybridPresent) {
if (IsProcessTrackedForFiltering(hdr.ProcessId)) {
EventDataDesc desc[] = {
{ L"pIDXGISwapChain" },
{ L"HybridPresentMode" },
};
// Check to see if the event has both the pIDXGISwapChain and HybridPresentMode
// fields. If not do not process.
uint32_t descCount = _countof(desc);
mMetadata.GetEventData(pEventRecord, desc, &descCount);
if (descCount == _countof(desc)) {
auto pSwapChain = desc[0].GetData<uint64_t>();
auto hybridPresentMode = desc[1].GetData<uint32_t>();
auto key = std::make_pair(hdr.ProcessId, pSwapChain);
mHybridPresentModeBySwapChainPid[key] = hybridPresentMode;
}
}
}
break;
default:
assert(!mFilteredEvents); // Assert that filtering is working if expected
break;
}
}
void PMTraceConsumer::HandleDxgkBlt(EVENT_HEADER const& hdr, uint64_t hwnd, bool redirectedPresent)
{
// Lookup the in-progress present. It should not have a known present mode
// yet, so if it does we assume we looked up a present whose tracking was
// lost.
std::shared_ptr<PresentEvent> presentEvent;
for (;;) {
presentEvent = FindOrCreatePresent(hdr);
if (presentEvent == nullptr) {
return;
}
if (presentEvent->PresentMode == PresentMode::Unknown) {
break;
}
RemoveLostPresent(presentEvent);
}
// This could be one of several types of presents. Further events will clarify.
// For now, assume that this is a blt straight into a surface which is already on-screen.
VerboseTraceBeforeModifyingPresent(presentEvent.get());
presentEvent->Hwnd = hwnd;
if (redirectedPresent) {
presentEvent->PresentMode = PresentMode::Composed_Copy_CPU_GDI;
presentEvent->SupportsTearing = false;
} else {
presentEvent->PresentMode = PresentMode::Hardware_Legacy_Copy_To_Front_Buffer;
presentEvent->SupportsTearing = true;
}
}
// A flip event is emitted during fullscreen present submission.
//
// We expect the following event sequence emitted on the same thread:
// PresentStart
// FlipMultiPlaneOverlay_Info
// QueuePacket_Start SubmitSequence MMIOFLIP bPresent=1
// QueuePacket_Stop SubmitSequence
// PresentStop
std::shared_ptr<PresentEvent> PMTraceConsumer::HandleDxgkFlip(EVENT_HEADER const& hdr)
{
// First, lookup the in-progress present on the same thread.
//
// The present should not have a known QueueSubmitSequence nor seen a DxgkPresent yet, so if it
// does then we've looked up the wrong present. Typically, this means we've lost tracking for
// the looked-up present, and it should be discarded.
//
// However, DWM on recent windows may omit the PresentStart/PresentStop events. In this case,
// we'll end up creating the present here and, because there is no PresentStop, it will be left
// in mPresentByThreadId and looked up again in the next HandleDxgkFlip().
std::shared_ptr<PresentEvent> presentEvent;
for (;;) {
// Lookup the in-progress present on this thread.
auto ii = mPresentByThreadId.find(hdr.ThreadId);
if (ii != mPresentByThreadId.end()) {
presentEvent = ii->second;
// If the in-progress present has seen DxgkPresent, it has lost tracking.
if (presentEvent->SeenDxgkPresent) {
RemoveLostPresent(presentEvent);
continue;
}
// If the in-progress present has seen PresentStop, it has lost tracking.
if (presentEvent->QueueSubmitSequence != 0 &&
presentEvent->TimeInPresent != 0 &&
presentEvent->Runtime != Runtime::Other) {
RemoveLostPresent(presentEvent);
continue;
}
// If we did see a PresentStart, then use this present
if (presentEvent->Runtime != Runtime::Other) {
// There may be duplicate flip events for MPO situations, so only handle the first.
if (presentEvent->PresentMode != PresentMode::Unknown) {
return nullptr;
}
break;
}
// The looked-up present was created by the last Flip, and didn't see a PresentStop; remove
// it from the thread tracking and create a new present for this flip.
mPresentByThreadId.erase(ii);
}
// Create a new present for this flip
if (!IsProcessTrackedForFiltering(hdr.ProcessId)) {
return nullptr;
}
presentEvent = std::make_shared<PresentEvent>();
VerboseTraceBeforeModifyingPresent(presentEvent.get());
presentEvent->PresentStartTime = *(uint64_t*) &hdr.TimeStamp;
presentEvent->ProcessId = hdr.ProcessId;
presentEvent->ThreadId = hdr.ThreadId;
TrackPresent(presentEvent, &mOrderedPresentsByProcessId[hdr.ProcessId]);
break;
}
// Update the present based on the flip event...
VerboseTraceBeforeModifyingPresent(presentEvent.get());
presentEvent->PresentMode = PresentMode::Hardware_Legacy_Flip;
// If this is the DWM thread, make any presents waiting for DWM dependent on it (i.e., they will
// be displayed when it is).
if (hdr.ThreadId == DwmPresentThreadId) {
DebugAssert(presentEvent->DependentPresents.empty());
for (auto& p : mPresentsWaitingForDWM) {
p->PresentInDwmWaitingStruct = false;
}
std::swap(presentEvent->DependentPresents, mPresentsWaitingForDWM);
}
return presentEvent;
}
void PMTraceConsumer::HandleDxgkQueueSubmit(
EVENT_HEADER const& hdr,
uint64_t hContext,
uint32_t submitSequence,
uint32_t packetType,
bool isPresentPacket,
bool isWin7)
{
// Track GPU execution
if (mTrackGPU) {
bool isWaitPacket = packetType == (uint32_t) Microsoft_Windows_DxgKrnl::QueuePacketType::DXGKETW_WAIT_COMMAND_BUFFER;
mGpuTrace.EnqueueQueuePacket(hContext, submitSequence, hdr.ProcessId, hdr.TimeStamp.QuadPart, isWaitPacket);
}
// For blt presents on Win7, the only way to distinguish between DWM-off
// fullscreen blts and the DWM-on blt to redirection bitmaps is to track
// whether a PHT was submitted before submitting anything else to the same
// context, which indicates it's a redirected blt. If we get to here
// instead, the present is a fullscreen blt and considered completed once
// its work is done.
if (isWin7) {
auto eventIter = mPresentByDxgkContext.find(hContext);
if (eventIter != mPresentByDxgkContext.end()) {
auto present = eventIter->second;
if (present->PresentMode == PresentMode::Hardware_Legacy_Copy_To_Front_Buffer) {
VerboseTraceBeforeModifyingPresent(present.get());
present->SeenDxgkPresent = true;
// If the work is already done, complete it now.
if (HasScreenTime(present)) {
CompletePresent(present);
}
}
// We're done with DxgkContext tracking, if the present hasn't
// completed remove it from the tracking now.
if (present->DxgkContext != 0) {
mPresentByDxgkContext.erase(eventIter);
present->DxgkContext = 0;
}
}
}
// This event is emitted after a flip/blt/PHT event, and may be the only
// way to trace completion of the present.
if (packetType == (uint32_t) Microsoft_Windows_DxgKrnl::QueuePacketType::DXGKETW_MMIOFLIP_COMMAND_BUFFER ||
packetType == (uint32_t) Microsoft_Windows_DxgKrnl::QueuePacketType::DXGKETW_SOFTWARE_COMMAND_BUFFER ||
isPresentPacket) {
auto present = FindPresentByThreadId(hdr.ThreadId);
if (present != nullptr && present->QueueSubmitSequence == 0) {
VerboseTraceBeforeModifyingPresent(present.get());
present->QueueSubmitSequence = submitSequence;
auto presentsBySubmitSequence = &mPresentBySubmitSequence[submitSequence];
DebugAssert(presentsBySubmitSequence->find(hContext) == presentsBySubmitSequence->end());
(*presentsBySubmitSequence)[hContext] = present;
if (isWin7 && present->PresentMode == PresentMode::Hardware_Legacy_Copy_To_Front_Buffer) {
mPresentByDxgkContext[hContext] = present;
present->DxgkContext = hContext;
}
}
}
}
void PMTraceConsumer::HandleDxgkQueueComplete(uint64_t timestamp, uint64_t hContext, uint32_t submitSequence)
{
// Track GPU execution of the packet
if (mTrackGPU) {
mGpuTrace.CompleteQueuePacket(hContext, submitSequence, timestamp);
}
// If this packet was a present packet being tracked...
auto ii = mPresentBySubmitSequence.find(submitSequence);
if (ii != mPresentBySubmitSequence.end()) {
auto presentsBySubmitSequence = &ii->second;
auto jj = presentsBySubmitSequence->find(hContext);
if (jj != presentsBySubmitSequence->end()) {
auto pEvent = jj->second;
// Stop tracking GPU work for this present.
//
// Note: there is a potential race here because QueuePacket_Stop
// occurs sometime after DmaPacket_Info it's possible that some
// small portion of the next frame's GPU work has started before
// QueuePacket_Stop and will be attributed to this frame. However,
// this is necessarily a small amount of work, and we can't use DMA
// packets as not all present types create them.
if (mTrackGPU) {
mGpuTrace.CompleteFrame(pEvent.get(), timestamp);
}
// We use present packet completion as the screen time for
// Hardware_Legacy_Copy_To_Front_Buffer and Hardware_Legacy_Flip
// present modes, unless we are expecting a subsequent flip/*sync
// event from DXGK.
if (pEvent->PresentMode == PresentMode::Hardware_Legacy_Copy_To_Front_Buffer ||
(pEvent->PresentMode == PresentMode::Hardware_Legacy_Flip && !pEvent->WaitForFlipEvent)) {
VerboseTraceBeforeModifyingPresent(pEvent.get());
if (pEvent->ReadyTime == 0) {
pEvent->ReadyTime = timestamp;
}
SetScreenTime(pEvent, timestamp);
// Sometimes, the queue packets associated with a present will complete
// before the DxgKrnl PresentInfo event is fired. For blit presents in
// this case, we have no way to differentiate between fullscreen and
// windowed blits, so we defer the completion of this present until
// we've also seen the Dxgk Present_Info event.
if (pEvent->SeenDxgkPresent || pEvent->PresentMode != PresentMode::Hardware_Legacy_Copy_To_Front_Buffer) {
CompletePresent(pEvent);
}
}
}
}
}
// Lookup the present associated with this submit sequence. Because some DXGK
// events that reference submit sequence id don't include the queue context,
// it's possible (though rare) that there are multiple presents in flight with
// the same submit sequence id. If that is the case, we pick the oldest one.
std::shared_ptr<PresentEvent> PMTraceConsumer::FindPresentBySubmitSequence(uint32_t submitSequence)
{
auto ii = mPresentBySubmitSequence.find(submitSequence);
if (ii != mPresentBySubmitSequence.end()) {
auto presentsBySubmitSequence = &ii->second;
auto jj = presentsBySubmitSequence->begin();
auto je = presentsBySubmitSequence->end();
DebugAssert(jj != je);
if (jj != je) {
auto present = jj->second;
for (++jj; jj != je; ++jj) {
if (present->PresentStartTime > jj->second->PresentStartTime) {
present = jj->second;
}
}
return present;
}
}
return std::shared_ptr<PresentEvent>();
}
// An MMIOFlip event is emitted when an MMIOFlip packet is dequeued. All GPU
// work submitted prior to the flip has been completed.
//
// It also is emitted when an independent flip PHT is dequed, and will tell us
// whether the present is immediate or vsync.
void PMTraceConsumer::HandleDxgkMMIOFlip(uint64_t timestamp, uint32_t submitSequence, uint32_t flags)
{
auto pEvent = FindPresentBySubmitSequence(submitSequence);
if (pEvent != nullptr) {
VerboseTraceBeforeModifyingPresent(pEvent.get());
pEvent->ReadyTime = timestamp;
if (pEvent->PresentMode == PresentMode::Composed_Flip) {
pEvent->PresentMode = PresentMode::Hardware_Independent_Flip;
}
if (flags & (uint32_t) Microsoft_Windows_DxgKrnl::SetVidPnSourceAddressFlags::FlipImmediate) {
SetScreenTime(pEvent, timestamp);
pEvent->SupportsTearing = true;
if (pEvent->PresentMode == PresentMode::Hardware_Legacy_Flip) {
CompletePresent(pEvent);
}
}
}
}
// The VSyncDPC/HSyncDPC contains a field telling us what flipped to screen.
// This is the way to track completion of a fullscreen present.
void PMTraceConsumer::HandleDxgkSyncDPC(uint64_t timestamp, uint32_t submitSequence)
{
auto pEvent = FindPresentBySubmitSequence(submitSequence);
if (pEvent != nullptr) {
VerboseTraceBeforeModifyingPresent(pEvent.get());
SetScreenTime(pEvent, timestamp);
// For Hardware_Legacy_Flip, we are done tracking the present. If we
// aren't expecting a subsequent *SyncMultiPlaneDPC_Info event, then we
// complete the present now.
//
// If we are expecting a subsequent *SyncMultiPlaneDPC_Info event, then
// we wait for it to complete the present. This is because there are
// rare cases where there may be multiple in-flight presents with the
// same submit sequence and waiting ensures that both the VSyncDPC and
// *SyncMultiPlaneDPC events match to the same present.
if (pEvent->PresentMode == PresentMode::Hardware_Legacy_Flip && !pEvent->WaitForMPOFlipEvent) {
CompletePresent(pEvent);
}
}
}
// These events are emitted during submission of all types of windowed presents
// while DWM is on and gives us a token we can use to match with the
// Microsoft_Windows_DxgKrnl::PresentHistory_Info event.
void PMTraceConsumer::HandleDxgkPresentHistory(
EVENT_HEADER const& hdr,
uint64_t token,
uint64_t tokenData,
Microsoft_Windows_DxgKrnl::PresentModel presentModel)
{
// Lookup the in-progress present. It should not have a known
// DxgkPresentHistoryToken yet, so if it does we assume we looked up a
// present whose tracking was lost.
std::shared_ptr<PresentEvent> presentEvent;
for (;;) {
presentEvent = FindOrCreatePresent(hdr);
if (presentEvent == nullptr) {
return;
}
if (presentEvent->DxgkPresentHistoryToken == 0) {
break;
}
RemoveLostPresent(presentEvent);
}
VerboseTraceBeforeModifyingPresent(presentEvent.get());
presentEvent->ReadyTime = 0;
presentEvent->SupportsTearing = false;
presentEvent->DxgkPresentHistoryToken = token;
if (presentEvent->Displayed.size() == 1 &&
presentEvent->Displayed[0].first == FrameType::NotSet) {
presentEvent->Displayed.clear();
presentEvent->FinalState = PresentResult::Unknown;
}
auto iter = mPresentByDxgkPresentHistoryToken.find(token);
if (iter != mPresentByDxgkPresentHistoryToken.end()) {
RemoveLostPresent(iter->second);
}
DebugAssert(mPresentByDxgkPresentHistoryToken.find(token) == mPresentByDxgkPresentHistoryToken.end());
mPresentByDxgkPresentHistoryToken[token] = presentEvent;
switch (presentEvent->PresentMode) {
case PresentMode::Hardware_Legacy_Copy_To_Front_Buffer:
DebugAssert(presentModel == Microsoft_Windows_DxgKrnl::PresentModel::D3DKMT_PM_UNINITIALIZED ||
presentModel == Microsoft_Windows_DxgKrnl::PresentModel::D3DKMT_PM_REDIRECTED_BLT);
presentEvent->PresentMode = PresentMode::Composed_Copy_GPU_GDI;
break;
case PresentMode::Unknown:
if (presentModel == Microsoft_Windows_DxgKrnl::PresentModel::D3DKMT_PM_REDIRECTED_COMPOSITION) {
/* BEGIN WORKAROUND: DirectComposition presents are currently ignored. There
* were rare situations observed where they would lead to issues during present
* completion (including stackoverflow caused by recursive completion). This
* could not be diagnosed, so we removed support for this present mode for now...
presentEvent->PresentMode = PresentMode::Composed_Composition_Atlas;
*/
RemoveLostPresent(presentEvent);
return;
/* END WORKAROUND */
} else {
// When there's no Win32K events, we'll assume PHTs that aren't after a blt, and aren't composition tokens
// are flip tokens and that they're displayed. There are no Win32K events on Win7, and they might not be
// present in some traces - don't let presents get stuck/dropped just because we can't track them perfectly.
DebugAssert(!presentEvent->SeenWin32KEvents);
presentEvent->PresentMode = PresentMode::Composed_Flip;
}
break;
case PresentMode::Composed_Copy_CPU_GDI:
if (tokenData == 0) {
// This is the best we can do, we won't be able to tell how many frames are actually displayed.
mPresentsWaitingForDWM.emplace_back(presentEvent);
presentEvent->PresentInDwmWaitingStruct = true;
} else {
DebugAssert(mPresentByDxgkPresentHistoryTokenData.find(tokenData) == mPresentByDxgkPresentHistoryTokenData.end());
mPresentByDxgkPresentHistoryTokenData[tokenData] = presentEvent;
presentEvent->DxgkPresentHistoryTokenData = tokenData;
}
break;
}
// If we are not tracking further GPU/display-related events, complete the
// present here.
if (!mTrackDisplay) {
CompletePresent(presentEvent);
}
}
// This event is emitted when a token is being handed off to DWM, and is a good
// way to indicate a ready state.
void PMTraceConsumer::HandleDxgkPresentHistoryInfo(EVENT_HEADER const& hdr, uint64_t token)
{
auto eventIter = mPresentByDxgkPresentHistoryToken.find(token);
if (eventIter == mPresentByDxgkPresentHistoryToken.end()) {
return;
}
VerboseTraceBeforeModifyingPresent(eventIter->second.get());
eventIter->second->ReadyTime = eventIter->second->ReadyTime == 0
? hdr.TimeStamp.QuadPart
: std::min(eventIter->second->ReadyTime, (uint64_t) hdr.TimeStamp.QuadPart);
// Neither Composed Composition Atlas or Win7 Flip has DWM events indicating intent
// to present this frame.
//
// Composed presents are currently ignored.
if (//eventIter->second->PresentMode == PresentMode::Composed_Composition_Atlas ||
(eventIter->second->PresentMode == PresentMode::Composed_Flip && !eventIter->second->SeenWin32KEvents)) {
mPresentsWaitingForDWM.emplace_back(eventIter->second);
eventIter->second->PresentInDwmWaitingStruct = true;
}
if (eventIter->second->PresentMode == PresentMode::Composed_Copy_GPU_GDI) {
// This present will be handed off to DWM. When DWM is ready to
// present, we'll query for the most recent blt targeting this window
// and take it out of the map.
mLastPresentByWindow[eventIter->second->Hwnd] = eventIter->second;
}
mPresentByDxgkPresentHistoryToken.erase(eventIter);
}
void PMTraceConsumer::HandleDXGKEvent(EVENT_RECORD* pEventRecord)
{
auto const& hdr = pEventRecord->EventHeader;
if (hdr.EventDescriptor.Id == Microsoft_Windows_DxgKrnl::PresentHistory_Start::Id ||
(hdr.EventDescriptor.Id == Microsoft_Windows_DxgKrnl::PresentHistoryDetailed_Start::Id && mTrackDisplay)) {
EventDataDesc desc[] = {
{ L"Token" },
{ L"Model" },
{ L"TokenData" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto Token = desc[0].GetData<uint64_t>();
auto Model = desc[1].GetData<Microsoft_Windows_DxgKrnl::PresentModel>();
auto TokenData = desc[2].GetData<uint64_t>();
if (Model != Microsoft_Windows_DxgKrnl::PresentModel::D3DKMT_PM_REDIRECTED_GDI) {
HandleDxgkPresentHistory(hdr, Token, TokenData, Model);
}
return;
}
if (mTrackDisplay) {
switch (hdr.EventDescriptor.Id) {
case Microsoft_Windows_DxgKrnl::Flip_Info::Id:
{
EventDataDesc desc[] = {
{ L"FlipInterval" },
{ L"MMIOFlip" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto FlipInterval = desc[0].GetData<uint32_t>();
auto MMIOFlip = desc[1].GetData<BOOL>() != 0;
auto p = HandleDxgkFlip(hdr);
if (p != nullptr) {
p->SyncInterval = FlipInterval;
if (MMIOFlip) {
p->WaitForFlipEvent = true;
} else if (FlipInterval == 0) {
p->SupportsTearing = true;
}
}
return;
}
case Microsoft_Windows_DxgKrnl::IndependentFlip_Info::Id:
{
EventDataDesc desc[] = {
{ L"SubmitSequence" },
{ L"FlipInterval" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto SubmitSequence = desc[0].GetData<uint32_t>();
auto FlipInterval = desc[1].GetData<uint32_t>();
auto pEvent = FindPresentBySubmitSequence(SubmitSequence);
if (pEvent != nullptr) {
// We should not have already identified as hardware_composed - this
// can only be detected around Vsync/HsyncDPC time.
DebugAssert(pEvent->PresentMode != PresentMode::Hardware_Composed_Independent_Flip);
VerboseTraceBeforeModifyingPresent(pEvent.get());
pEvent->PresentMode = PresentMode::Hardware_Independent_Flip;
pEvent->SyncInterval = FlipInterval;
}
return;
}
case Microsoft_Windows_DxgKrnl::FlipMultiPlaneOverlay_Info::Id:
{
EventDataDesc desc[] = {
{ L"VidPnSourceId" },
{ L"LayerIndex" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto VidPnSourceId = desc[0].GetData<uint32_t>();
auto LayerIndex = desc[1].GetData<uint32_t>();
auto p = HandleDxgkFlip(hdr);
if (p != nullptr) {
p->WaitForFlipEvent = true;
p->WaitForMPOFlipEvent = true;
if (p->SwapChainAddress == 0) {
p->SwapChainAddress = GenerateVidPnLayerId(VidPnSourceId, LayerIndex);
}
}
return;
}
// QueuPacket_Start are used for render queue packets
// QueuPacket_Start_2 are used for monitor wait packets
// QueuPacket_Start_3 are used for monitor signal packets
case Microsoft_Windows_DxgKrnl::QueuePacket_Start::Id:
{
EventDataDesc desc[] = {
{ L"PacketType" },
{ L"SubmitSequence" },
{ L"hContext" },
{ L"bPresent" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto PacketType = desc[0].GetData<uint32_t>();
auto SubmitSequence = desc[1].GetData<uint32_t>();
auto hContext = desc[2].GetData<uint64_t>();
auto bPresent = desc[3].GetData<BOOL>() != 0;
HandleDxgkQueueSubmit(hdr, hContext, SubmitSequence, PacketType, bPresent, false);
return;
}
case Microsoft_Windows_DxgKrnl::QueuePacket_Start_2::Id:
{
EventDataDesc desc[] = {
{ L"hContext" },
{ L"SubmitSequence" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto hContext = desc[0].GetData<uint64_t>();
auto SubmitSequence = desc[1].GetData<uint32_t>();
uint32_t PacketType = (uint32_t) Microsoft_Windows_DxgKrnl::QueuePacketType::DXGKETW_WAIT_COMMAND_BUFFER;
bool bPresent = false;
HandleDxgkQueueSubmit(hdr, hContext, SubmitSequence, PacketType, bPresent, false);
return;
}
case Microsoft_Windows_DxgKrnl::QueuePacket_Stop::Id:
{
EventDataDesc desc[] = {
{ L"hContext" },
{ L"SubmitSequence" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto hContext = desc[0].GetData<uint64_t>();
auto SubmitSequence = desc[1].GetData<uint32_t>();
HandleDxgkQueueComplete(hdr.TimeStamp.QuadPart, hContext, SubmitSequence);
return;
}
case Microsoft_Windows_DxgKrnl::MMIOFlip_Info::Id:
{
EventDataDesc desc[] = {
{ L"FlipSubmitSequence" },
{ L"Flags" },
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc));
auto FlipSubmitSequence = desc[0].GetData<uint32_t>();
auto Flags = desc[1].GetData<uint32_t>();
HandleDxgkMMIOFlip(hdr.TimeStamp.QuadPart, FlipSubmitSequence, Flags);
return;
}
case Microsoft_Windows_DxgKrnl::MMIOFlipMultiPlaneOverlay_Info::Id:
{
auto flipEntryStatusAfterFlipValid = hdr.EventDescriptor.Version >= 2;
EventDataDesc desc[] = {
{ L"FlipSubmitSequence" },
{ L"FlipEntryStatusAfterFlip" }, // optional
};
mMetadata.GetEventData(pEventRecord, desc, _countof(desc) - (flipEntryStatusAfterFlipValid ? 0 : 1));
auto FlipSubmitSequence = desc[0].GetData<uint64_t>();
auto submitSequence = (uint32_t) (FlipSubmitSequence >> 32u);
auto present = FindPresentBySubmitSequence(submitSequence);
if (present != nullptr) {
// Complete the GPU tracking for this frame.
//
// For some present modes (e.g., Hardware_Legacy_Flip) this may be
// the first event telling us the present is ready.
mGpuTrace.CompleteFrame(present.get(), hdr.TimeStamp.QuadPart);
// Check and handle the post-flip status if available.
if (flipEntryStatusAfterFlipValid) {