forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.cpp
1763 lines (1560 loc) · 69.7 KB
/
event.cpp
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
//===--------- event.cpp - Level Zero Adapter -----------------------------===//
//
// Copyright (C) 2023 Intel Corporation
//
// Part of the Unified-Runtime Project, under the Apache License v2.0 with LLVM
// Exceptions. See LICENSE.TXT
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <algorithm>
#include <climits>
#include <mutex>
#include <optional>
#include <string.h>
#include "command_buffer.hpp"
#include "common.hpp"
#include "event.hpp"
#include "logger/ur_logger.hpp"
#include "ur_interface_loader.hpp"
#include "ur_level_zero.hpp"
void printZeEventList(const _ur_ze_event_list_t &UrZeEventList) {
if (UrL0Debug & UR_L0_DEBUG_BASIC) {
std::stringstream ss;
ss << " NumEventsInWaitList " << UrZeEventList.Length << ":";
for (uint32_t I = 0; I < UrZeEventList.Length; I++) {
ss << " " << ur_cast<std::uintptr_t>(UrZeEventList.ZeEventList[I]);
}
logger::debug(ss.str().c_str());
}
}
// This is an experimental option that allows the use of multiple command lists
// when submitting barriers. The default is 0.
static const bool UseMultipleCmdlistBarriers = [] {
const char *UrRet = std::getenv("UR_L0_USE_MULTIPLE_COMMANDLIST_BARRIERS");
const char *PiRet =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_MULTIPLE_COMMANDLIST_BARRIERS");
const char *UseMultipleCmdlistBarriersFlag =
UrRet ? UrRet : (PiRet ? PiRet : nullptr);
if (!UseMultipleCmdlistBarriersFlag)
return true;
return std::atoi(UseMultipleCmdlistBarriersFlag) > 0;
}();
bool WaitListEmptyOrAllEventsFromSameQueue(
ur_queue_handle_t Queue, uint32_t NumEventsInWaitList,
const ur_event_handle_t *EventWaitList) {
if (!NumEventsInWaitList)
return true;
for (uint32_t i = 0; i < NumEventsInWaitList; ++i) {
if (Queue != EventWaitList[i]->UrQueue)
return false;
}
return true;
}
namespace ur::level_zero {
ur_result_t urEnqueueEventsWait(
/// [in] handle of the queue object
ur_queue_handle_t Queue,
/// [in] size of the event wait list
uint32_t NumEventsInWaitList,
/// [in][optional][range(0, numEventsInWaitList)] pointer to a list of
/// events that must be complete before this command can be executed. If
/// nullptr, the numEventsInWaitList must be 0, indicating that all
/// previously enqueued commands must be complete.
const ur_event_handle_t *EventWaitList,
/// [in,out][optional] return an event object that identifies this
/// particular command instance.
ur_event_handle_t *OutEvent) {
if (EventWaitList) {
bool UseCopyEngine = false;
// Lock automatically releases when this goes out of scope.
std::scoped_lock<ur_shared_mutex> lock(Queue->Mutex);
_ur_ze_event_list_t TmpWaitList = {};
UR_CALL(TmpWaitList.createAndRetainUrZeEventList(
NumEventsInWaitList, EventWaitList, Queue, UseCopyEngine));
// Get a new command list to be used on this call
ur_command_list_ptr_t CommandList{};
UR_CALL(Queue->Context->getAvailableCommandList(
Queue, CommandList, UseCopyEngine, NumEventsInWaitList, EventWaitList,
false /*AllowBatching*/, nullptr /*ForceCmdQueue*/));
ze_event_handle_t ZeEvent = nullptr;
ur_event_handle_t InternalEvent;
bool IsInternal = OutEvent == nullptr;
ur_event_handle_t *Event = OutEvent ? OutEvent : &InternalEvent;
UR_CALL(createEventAndAssociateQueue(Queue, Event, UR_COMMAND_EVENTS_WAIT,
CommandList, IsInternal, false));
ZeEvent = (*Event)->ZeEvent;
(*Event)->WaitList = TmpWaitList;
const auto &WaitList = (*Event)->WaitList;
auto ZeCommandList = CommandList->first;
ZE2UR_CALL(zeCommandListAppendWaitOnEvents,
(ZeCommandList, WaitList.Length, WaitList.ZeEventList));
ZE2UR_CALL(zeCommandListAppendSignalEvent, (ZeCommandList, ZeEvent));
// Execute command list asynchronously as the event will be used
// to track down its completion.
return Queue->executeCommandList(CommandList, false /*IsBlocking*/,
false /*OKToBatchCommand*/);
}
{
// If wait-list is empty, then this particular command should wait until
// all previous enqueued commands to the command-queue have completed.
//
// TODO: find a way to do that without blocking the host.
// Lock automatically releases when this goes out of scope.
std::scoped_lock<ur_shared_mutex> lock(Queue->Mutex);
if (OutEvent) {
UR_CALL(createEventAndAssociateQueue(Queue, OutEvent,
UR_COMMAND_EVENTS_WAIT,
Queue->CommandListMap.end(), false,
/* IsInternal */ false));
}
UR_CALL(Queue->synchronize());
if (OutEvent) {
Queue->LastCommandEvent = reinterpret_cast<ur_event_handle_t>(*OutEvent);
if (!(*OutEvent)->CounterBasedEventsEnabled)
ZE2UR_CALL(zeEventHostSignal, ((*OutEvent)->ZeEvent));
(*OutEvent)->Completed = true;
}
}
if (!Queue->UsingImmCmdLists) {
std::unique_lock<ur_shared_mutex> Lock(Queue->Mutex);
resetCommandLists(Queue);
}
return UR_RESULT_SUCCESS;
}
// Control if wait with barrier is implemented by signal of an event
// as opposed by true barrier command for in-order queue.
static const bool InOrderBarrierBySignal = [] {
const char *UrRet = std::getenv("UR_L0_IN_ORDER_BARRIER_BY_SIGNAL");
return (UrRet ? std::atoi(UrRet) : true);
}();
ur_result_t urEnqueueEventsWaitWithBarrier(
/// [in] handle of the queue object
ur_queue_handle_t Queue,
/// [in] size of the event wait list
uint32_t NumEventsInWaitList,
/// [in][optional][range(0, numEventsInWaitList)] pointer to a list of
/// events that must be complete before this command can be executed. If
/// nullptr, the numEventsInWaitList must be 0, indicating that all
/// previously enqueued commands must be complete.
const ur_event_handle_t *EventWaitList,
/// [in,out][optional] return an event object that identifies this
/// particular command instance.
ur_event_handle_t *OutEvent) {
return ur::level_zero::urEnqueueEventsWaitWithBarrierExt(
Queue, nullptr, NumEventsInWaitList, EventWaitList, OutEvent);
}
ur_result_t urEnqueueEventsWaitWithBarrierExt(
/// [in] handle of the queue object
ur_queue_handle_t Queue,
/// [in][optional] pointer to the extended enqueue
const ur_exp_enqueue_ext_properties_t *EnqueueExtProp,
/// [in] size of the event wait list
uint32_t NumEventsInWaitList,
/// [in][optional][range(0, numEventsInWaitList)] pointer to a list of
/// events that must be complete before this command can be executed. If
/// nullptr, the numEventsInWaitList must be 0, indicating that all
/// previously enqueued commands must be complete.
const ur_event_handle_t *EventWaitList,
/// [in,out][optional] return an event object that identifies this
/// particular command instance.
ur_event_handle_t *OutEvent) {
bool InterruptBasedEventsEnabled =
EnqueueExtProp ? (EnqueueExtProp->flags &
UR_EXP_ENQUEUE_EXT_FLAG_LOW_POWER_EVENTS_SUPPORT) ||
Queue->InterruptBasedEventsEnabled
: Queue->InterruptBasedEventsEnabled;
// Lock automatically releases when this goes out of scope.
std::scoped_lock<ur_shared_mutex> lock(Queue->Mutex);
// Helper function for appending a barrier to a command list.
auto insertBarrierIntoCmdList =
[&Queue](ur_command_list_ptr_t CmdList,
_ur_ze_event_list_t &EventWaitList, ur_event_handle_t &Event,
bool IsInternal, bool InterruptBasedEventsEnabled) {
UR_CALL(createEventAndAssociateQueue(
Queue, &Event, UR_COMMAND_EVENTS_WAIT_WITH_BARRIER, CmdList,
IsInternal, InterruptBasedEventsEnabled));
Event->WaitList = EventWaitList;
// For in-order queue we don't need a real barrier, just wait for
// requested events in potentially different queues and add a "barrier"
// event signal because it is already guaranteed that previous commands
// in this queue are completed when the signal is started.
//
// Only consideration here is that when profiling is used, signalEvent
// cannot be used if EventWaitList.Lenght == 0. In those cases, we need
// to fallback directly to barrier to have correct timestamps. See here:
// https://spec.oneapi.io/level-zero/latest/core/api.html?highlight=appendsignalevent#_CPPv430zeCommandListAppendSignalEvent24ze_command_list_handle_t17ze_event_handle_t
//
// TODO: this and other special handling of in-order queues to be
// updated when/if Level Zero adds native support for in-order queues.
//
if (Queue->isInOrderQueue() && InOrderBarrierBySignal &&
!Queue->isProfilingEnabled()) {
if (EventWaitList.Length) {
ZE2UR_CALL(zeCommandListAppendWaitOnEvents,
(CmdList->first, EventWaitList.Length,
EventWaitList.ZeEventList));
}
ZE2UR_CALL(zeCommandListAppendSignalEvent,
(CmdList->first, Event->ZeEvent));
} else {
ZE2UR_CALL(zeCommandListAppendBarrier,
(CmdList->first, Event->ZeEvent, EventWaitList.Length,
EventWaitList.ZeEventList));
}
return UR_RESULT_SUCCESS;
};
// If the queue is in-order then each command in it effectively acts as a
// barrier, so we don't need to do anything except if we were requested
// a "barrier" event to be created. Or if we need to wait for events in
// potentially different queues.
//
if (Queue->isInOrderQueue() && NumEventsInWaitList == 0 && !OutEvent) {
return UR_RESULT_SUCCESS;
}
ur_event_handle_t ResultEvent = nullptr;
bool IsInternal = OutEvent == nullptr;
// For in-order queue and wait-list which is empty or has events from
// the same queue just use the last command event as the barrier event.
// This optimization is disabled when profiling is enabled to ensure
// accurate profiling values & the overhead that profiling incurs.
if (Queue->isInOrderQueue() && !Queue->isProfilingEnabled() &&
WaitListEmptyOrAllEventsFromSameQueue(Queue, NumEventsInWaitList,
EventWaitList) &&
Queue->LastCommandEvent && !Queue->LastCommandEvent->IsDiscarded) {
UR_CALL(ur::level_zero::urEventRetain(Queue->LastCommandEvent));
ResultEvent = Queue->LastCommandEvent;
if (OutEvent) {
*OutEvent = ResultEvent;
}
return UR_RESULT_SUCCESS;
}
// Indicator for whether batching is allowed. This may be changed later in
// this function, but allow it by default.
bool OkToBatch = true;
// If we have a list of events to make the barrier from, then we can create a
// barrier on these and use the resulting event as our future barrier.
// We use the same approach if
// UR_L0_USE_MULTIPLE_COMMANDLIST_BARRIERS is not set to a
// positive value.
// We use the same approach if we have in-order queue because every command
// depends on previous one, so we don't need to insert barrier to multiple
// command lists.
if (NumEventsInWaitList || !UseMultipleCmdlistBarriers ||
Queue->isInOrderQueue()) {
// Retain the events as they will be owned by the result event.
_ur_ze_event_list_t TmpWaitList;
UR_CALL(TmpWaitList.createAndRetainUrZeEventList(
NumEventsInWaitList, EventWaitList, Queue, false /*UseCopyEngine=*/));
// Get an arbitrary command-list in the queue.
ur_command_list_ptr_t CmdList;
UR_CALL(Queue->Context->getAvailableCommandList(
Queue, CmdList, false /*UseCopyEngine=*/, NumEventsInWaitList,
EventWaitList, OkToBatch, nullptr /*ForcedCmdQueue*/));
// Insert the barrier into the command-list and execute.
UR_CALL(insertBarrierIntoCmdList(CmdList, TmpWaitList, ResultEvent,
IsInternal, InterruptBasedEventsEnabled));
UR_CALL(
Queue->executeCommandList(CmdList, false /*IsBlocking*/, OkToBatch));
// Because of the dependency between commands in the in-order queue we don't
// need to keep track of any active barriers if we have in-order queue.
if (UseMultipleCmdlistBarriers && !Queue->isInOrderQueue()) {
auto UREvent = reinterpret_cast<ur_event_handle_t>(ResultEvent);
Queue->ActiveBarriers.add(UREvent);
}
if (OutEvent) {
*OutEvent = ResultEvent;
}
return UR_RESULT_SUCCESS;
}
// Since there are no events to explicitly create a barrier for, we are
// inserting a queue-wide barrier.
// Command list(s) for putting barriers.
std::vector<ur_command_list_ptr_t> CmdLists;
// There must be at least one L0 queue.
auto &ComputeGroup = Queue->ComputeQueueGroupsByTID.get();
auto &CopyGroup = Queue->CopyQueueGroupsByTID.get();
UR_ASSERT(!ComputeGroup.ZeQueues.empty() || !CopyGroup.ZeQueues.empty(),
UR_RESULT_ERROR_INVALID_QUEUE);
size_t NumQueues = 0;
for (auto &QueueMap :
{Queue->ComputeQueueGroupsByTID, Queue->CopyQueueGroupsByTID})
for (auto &QueueGroup : QueueMap)
NumQueues += QueueGroup.second.ZeQueues.size();
OkToBatch = true;
// Get an available command list tied to each command queue. We need
// these so a queue-wide barrier can be inserted into each command
// queue.
CmdLists.reserve(NumQueues);
for (auto &QueueMap :
{Queue->ComputeQueueGroupsByTID, Queue->CopyQueueGroupsByTID})
for (auto &QueueGroup : QueueMap) {
bool UseCopyEngine =
QueueGroup.second.Type != ur_queue_handle_t_::queue_type::Compute;
if (Queue->UsingImmCmdLists) {
// If immediate command lists are being used, each will act as their own
// queue, so we must insert a barrier into each.
for (auto &ImmCmdList : QueueGroup.second.ImmCmdLists)
if (ImmCmdList != Queue->CommandListMap.end())
CmdLists.push_back(ImmCmdList);
} else {
for (auto ZeQueue : QueueGroup.second.ZeQueues) {
if (ZeQueue) {
ur_command_list_ptr_t CmdList;
UR_CALL(Queue->Context->getAvailableCommandList(
Queue, CmdList, UseCopyEngine, NumEventsInWaitList,
EventWaitList, OkToBatch, &ZeQueue));
CmdLists.push_back(CmdList);
}
}
}
}
// If no activity has occurred on the queue then there will be no cmdlists.
// We need one for generating an Event, so create one.
if (CmdLists.size() == 0) {
// Get any available command list.
ur_command_list_ptr_t CmdList;
UR_CALL(Queue->Context->getAvailableCommandList(
Queue, CmdList, false /*UseCopyEngine=*/, NumEventsInWaitList,
EventWaitList, OkToBatch, nullptr /*ForcedCmdQueue*/));
CmdLists.push_back(CmdList);
}
if (CmdLists.size() > 1) {
// Insert a barrier into each unique command queue using the available
// command-lists.
std::vector<ur_event_handle_t> EventWaitVector(CmdLists.size());
for (size_t I = 0; I < CmdLists.size(); ++I) {
_ur_ze_event_list_t waitlist;
UR_CALL(insertBarrierIntoCmdList(CmdLists[I], waitlist,
EventWaitVector[I], true /*IsInternal*/,
InterruptBasedEventsEnabled));
}
// If there were multiple queues we need to create a "convergence" event to
// be our active barrier. This convergence event is signalled by a barrier
// on all the events from the barriers we have inserted into each queue.
// Use the first command list as our convergence command list.
ur_command_list_ptr_t &ConvergenceCmdList = CmdLists[0];
// Create an event list. It will take ownership over all relevant events so
// we relinquish ownership and let it keep all events it needs.
_ur_ze_event_list_t BaseWaitList;
UR_CALL(BaseWaitList.createAndRetainUrZeEventList(
EventWaitVector.size(),
reinterpret_cast<const ur_event_handle_t *>(EventWaitVector.data()),
Queue, ConvergenceCmdList->second.isCopy(Queue)));
// Insert a barrier with the events from each command-queue into the
// convergence command list. The resulting event signals the convergence of
// all barriers.
UR_CALL(insertBarrierIntoCmdList(ConvergenceCmdList, BaseWaitList,
ResultEvent, IsInternal,
InterruptBasedEventsEnabled));
} else {
// If there is only a single queue then insert a barrier and the single
// result event can be used as our active barrier and used as the return
// event. Take into account whether output event is discarded or not.
_ur_ze_event_list_t waitlist;
UR_CALL(insertBarrierIntoCmdList(CmdLists[0], waitlist, ResultEvent,
IsInternal, InterruptBasedEventsEnabled));
}
// Execute each command list so the barriers can be encountered.
for (ur_command_list_ptr_t &CmdList : CmdLists) {
bool IsCopy =
CmdList->second.isCopy(reinterpret_cast<ur_queue_handle_t>(Queue));
const auto &CommandBatch =
(IsCopy) ? Queue->CopyCommandBatch : Queue->ComputeCommandBatch;
// Only batch if the matching CmdList is already open.
OkToBatch = CommandBatch.OpenCommandList == CmdList;
UR_CALL(
Queue->executeCommandList(CmdList, false /*IsBlocking*/, OkToBatch));
}
UR_CALL(Queue->ActiveBarriers.clear());
Queue->ActiveBarriers.add(ResultEvent);
if (OutEvent) {
*OutEvent = ResultEvent;
}
return UR_RESULT_SUCCESS;
}
ur_result_t urEventGetInfo(
/// [in] handle of the event object
ur_event_handle_t Event,
/// [in] the name of the event property to query
ur_event_info_t PropName,
/// [in] size in bytes of the event property value
size_t PropValueSize,
/// [out][optional] value of the event property
void *PropValue,
size_t
/// [out][optional] bytes returned in event property
*PropValueSizeRet) {
UrReturnHelper ReturnValue(PropValueSize, PropValue, PropValueSizeRet);
switch (PropName) {
case UR_EVENT_INFO_COMMAND_QUEUE: {
std::shared_lock<ur_shared_mutex> EventLock(Event->Mutex);
return ReturnValue(ur_queue_handle_t{Event->UrQueue});
}
case UR_EVENT_INFO_CONTEXT: {
std::shared_lock<ur_shared_mutex> EventLock(Event->Mutex);
return ReturnValue(ur_context_handle_t{Event->Context});
}
case UR_EVENT_INFO_COMMAND_TYPE: {
std::shared_lock<ur_shared_mutex> EventLock(Event->Mutex);
return ReturnValue(ur_cast<ur_command_t>(Event->CommandType));
}
case UR_EVENT_INFO_COMMAND_EXECUTION_STATUS: {
// Check to see if the event's Queue has an open command list due to
// batching. If so, go ahead and close and submit it, because it is
// possible that this is trying to query some event's status that
// is part of the batch. This isn't strictly required, but it seems
// like a reasonable thing to do.
auto UrQueue = Event->UrQueue;
if (UrQueue) {
// Lock automatically releases when this goes out of scope.
std::unique_lock<ur_shared_mutex> Lock(UrQueue->Mutex, std::try_to_lock);
// If we fail to acquire the lock, it's possible that the queue might
// already be waiting for this event in synchronize().
if (Lock.owns_lock()) {
const auto &OpenCommandList = UrQueue->eventOpenCommandList(Event);
if (OpenCommandList != UrQueue->CommandListMap.end()) {
UR_CALL(UrQueue->executeOpenCommandList(
OpenCommandList->second.isCopy(UrQueue)));
}
}
}
// Level Zero has a much more explicit notion of command submission than
// OpenCL. It doesn't happen unless the user submits a command list. We've
// done it just above so the status is at least PI_EVENT_SUBMITTED.
//
// NOTE: We currently cannot tell if command is currently running, so
// it will always show up "submitted" before it is finally "completed".
//
uint32_t Result = ur_cast<uint32_t>(UR_EVENT_STATUS_SUBMITTED);
// Make sure that we query a host-visible event only.
// If one wasn't yet created then don't create it here as well, and
// just conservatively return that event is not yet completed.
std::shared_lock<ur_shared_mutex> EventLock(Event->Mutex);
auto HostVisibleEvent = Event->HostVisibleEvent;
if (Event->Completed) {
Result = UR_EVENT_STATUS_COMPLETE;
} else if (HostVisibleEvent) {
ze_result_t ZeResult;
ZeResult =
ZE_CALL_NOCHECK(zeEventQueryStatus, (HostVisibleEvent->ZeEvent));
if (ZeResult == ZE_RESULT_SUCCESS) {
Result = UR_EVENT_STATUS_COMPLETE;
}
}
return ReturnValue(Result);
}
case UR_EVENT_INFO_REFERENCE_COUNT: {
return ReturnValue(Event->RefCount.load());
}
default:
logger::error(
"Unsupported ParamName in urEventGetInfo: ParamName=ParamName={}(0x{})",
PropName, logger::toHex(PropName));
return UR_RESULT_ERROR_INVALID_VALUE;
}
return UR_RESULT_SUCCESS;
}
ur_result_t urEventGetProfilingInfo(
/// [in] handle of the event object
ur_event_handle_t Event,
/// [in] the name of the profiling property to query
ur_profiling_info_t PropName,
/// [in] size in bytes of the profiling property value
size_t PropValueSize,
/// [out][optional] value of the profiling property
void *PropValue,
/// [out][optional] pointer to the actual size in bytes returned in
/// propValue
size_t *PropValueSizeRet) {
std::shared_lock<ur_shared_mutex> EventLock(Event->Mutex);
// The event must either have profiling enabled or be recording timestamps.
bool isTimestampedEvent = Event->isTimestamped();
if (!Event->isProfilingEnabled() && !isTimestampedEvent) {
return UR_RESULT_ERROR_PROFILING_INFO_NOT_AVAILABLE;
}
ur_device_handle_t Device =
Event->UrQueue ? Event->UrQueue->Device : Event->Context->Devices[0];
uint64_t ZeTimerResolution = Device->ZeDeviceProperties->timerResolution;
const uint64_t TimestampMaxValue = Device->getTimestampMask();
UrReturnHelper ReturnValue(PropValueSize, PropValue, PropValueSizeRet);
// For timestamped events we have the timestamps ready directly on the event
// handle, so we short-circuit the return.
// We don't support user events with timestamps due to requiring the UrQueue.
if (isTimestampedEvent && Event->UrQueue) {
uint64_t ContextStartTime = Event->RecordEventStartTimestamp;
switch (PropName) {
case UR_PROFILING_INFO_COMMAND_QUEUED:
case UR_PROFILING_INFO_COMMAND_SUBMIT:
return ReturnValue(ContextStartTime);
case UR_PROFILING_INFO_COMMAND_END:
case UR_PROFILING_INFO_COMMAND_START: {
// If RecordEventEndTimestamp on the event is non-zero it means it has
// collected the result of the queue already. In that case it has been
// adjusted and is ready for immediate return.
if (Event->RecordEventEndTimestamp)
return ReturnValue(Event->RecordEventEndTimestamp);
// Otherwise we need to collect it from the queue.
auto Entry = Event->UrQueue->EndTimeRecordings.find(Event);
// Unexpected state if there is no end-time record.
if (Entry == Event->UrQueue->EndTimeRecordings.end())
return UR_RESULT_ERROR_UNKNOWN;
auto &EndTimeRecording = Entry->second;
// End time needs to be adjusted for resolution and valid bits.
uint64_t ContextEndTime =
(EndTimeRecording & TimestampMaxValue) * ZeTimerResolution;
// If the result is 0, we have not yet gotten results back and so we just
// return it.
if (ContextEndTime == 0)
return ReturnValue(ContextEndTime);
// Handle a possible wrap-around (the underlying HW counter is < 64-bit).
// Note, it will not report correct time if there were multiple wrap
// arounds, and the longer term plan is to enlarge the capacity of the
// HW timestamps.
if (ContextEndTime < ContextStartTime)
ContextEndTime += TimestampMaxValue * ZeTimerResolution;
// Now that we have the result, there is no need to keep it in the queue
// anymore, so we cache it on the event and evict the record from the
// queue.
Event->RecordEventEndTimestamp = ContextEndTime;
Event->UrQueue->EndTimeRecordings.erase(Entry);
return ReturnValue(ContextEndTime);
}
case UR_PROFILING_INFO_COMMAND_COMPLETE:
logger::error("urEventGetProfilingInfo: "
"UR_PROFILING_INFO_COMMAND_COMPLETE not supported");
return UR_RESULT_ERROR_UNSUPPORTED_ENUMERATION;
default:
logger::error("urEventGetProfilingInfo: not supported ParamName");
return UR_RESULT_ERROR_INVALID_VALUE;
}
}
ze_kernel_timestamp_result_t tsResult;
// A Command-buffer consists of three command-lists for which only a single
// event is returned to users. The actual profiling information related to the
// command-buffer should therefore be extrated from graph events themsleves.
// The timestamps of these events are saved in a memory region attached to
// event usning CommandData field. The timings must therefore be recovered
// from this memory.
if (Event->CommandType == UR_COMMAND_ENQUEUE_COMMAND_BUFFER_EXP) {
if (Event->CommandData) {
command_buffer_profiling_t *ProfilingsPtr;
switch (PropName) {
case UR_PROFILING_INFO_COMMAND_START: {
ProfilingsPtr =
static_cast<command_buffer_profiling_t *>(Event->CommandData);
// Sync-point order does not necessarily match to the order of
// execution. We therefore look for the first command executed.
uint64_t MinStart = ProfilingsPtr->Timestamps[0].global.kernelStart;
for (uint64_t i = 1; i < ProfilingsPtr->NumEvents; i++) {
uint64_t Timestamp = ProfilingsPtr->Timestamps[i].global.kernelStart;
if (Timestamp < MinStart) {
MinStart = Timestamp;
}
}
uint64_t ContextStartTime =
(MinStart & TimestampMaxValue) * ZeTimerResolution;
return ReturnValue(ContextStartTime);
}
case UR_PROFILING_INFO_COMMAND_END: {
ProfilingsPtr =
static_cast<command_buffer_profiling_t *>(Event->CommandData);
// Sync-point order does not necessarily match to the order of
// execution. We therefore look for the last command executed.
uint64_t MaxEnd = ProfilingsPtr->Timestamps[0].global.kernelEnd;
uint64_t LastStart = ProfilingsPtr->Timestamps[0].global.kernelStart;
for (uint64_t i = 1; i < ProfilingsPtr->NumEvents; i++) {
uint64_t Timestamp = ProfilingsPtr->Timestamps[i].global.kernelEnd;
if (Timestamp > MaxEnd) {
MaxEnd = Timestamp;
LastStart = ProfilingsPtr->Timestamps[i].global.kernelStart;
}
}
uint64_t ContextStartTime = (LastStart & TimestampMaxValue);
uint64_t ContextEndTime = (MaxEnd & TimestampMaxValue);
//
// Handle a possible wrap-around (the underlying HW counter is <
// 64-bit). Note, it will not report correct time if there were multiple
// wrap arounds, and the longer term plan is to enlarge the capacity of
// the HW timestamps.
//
if (ContextEndTime <= ContextStartTime) {
ContextEndTime += TimestampMaxValue;
}
ContextEndTime *= ZeTimerResolution;
return ReturnValue(ContextEndTime);
}
case UR_PROFILING_INFO_COMMAND_COMPLETE:
logger::error("urEventGetProfilingInfo: "
"UR_PROFILING_INFO_COMMAND_COMPLETE not supported");
return UR_RESULT_ERROR_UNSUPPORTED_ENUMERATION;
default:
logger::error("urEventGetProfilingInfo: not supported ParamName");
return UR_RESULT_ERROR_INVALID_VALUE;
}
} else {
return UR_RESULT_ERROR_PROFILING_INFO_NOT_AVAILABLE;
}
}
switch (PropName) {
case UR_PROFILING_INFO_COMMAND_START: {
ZE2UR_CALL(zeEventQueryKernelTimestamp, (Event->ZeEvent, &tsResult));
uint64_t ContextStartTime =
(tsResult.global.kernelStart & TimestampMaxValue) * ZeTimerResolution;
return ReturnValue(ContextStartTime);
}
case UR_PROFILING_INFO_COMMAND_END: {
ZE2UR_CALL(zeEventQueryKernelTimestamp, (Event->ZeEvent, &tsResult));
uint64_t ContextStartTime =
(tsResult.global.kernelStart & TimestampMaxValue);
uint64_t ContextEndTime = (tsResult.global.kernelEnd & TimestampMaxValue);
//
// Handle a possible wrap-around (the underlying HW counter is < 64-bit).
// Note, it will not report correct time if there were multiple wrap
// arounds, and the longer term plan is to enlarge the capacity of the
// HW timestamps.
//
if (ContextEndTime <= ContextStartTime) {
ContextEndTime += TimestampMaxValue;
}
ContextEndTime *= ZeTimerResolution;
return ReturnValue(ContextEndTime);
}
case UR_PROFILING_INFO_COMMAND_QUEUED:
case UR_PROFILING_INFO_COMMAND_SUBMIT:
// Note: No users for this case
// The "command_submit" time is implemented by recording submission
// timestamp with a call to urDeviceGetGlobalTimestamps before command
// enqueue.
//
return ReturnValue(uint64_t{0});
case UR_PROFILING_INFO_COMMAND_COMPLETE:
logger::error("urEventGetProfilingInfo: UR_PROFILING_INFO_COMMAND_COMPLETE "
"not supported");
return UR_RESULT_ERROR_UNSUPPORTED_ENUMERATION;
default:
logger::error("urEventGetProfilingInfo: not supported ParamName");
return UR_RESULT_ERROR_INVALID_VALUE;
}
return UR_RESULT_SUCCESS;
}
ur_result_t urEnqueueTimestampRecordingExp(
/// [in] handle of the queue object
ur_queue_handle_t Queue,
/// [in] blocking or non-blocking enqueue
bool Blocking,
/// [in] size of the event wait list
uint32_t NumEventsInWaitList,
/// [in][optional][range(0, numEventsInWaitList)] pointer to a list of
/// events that must be complete before this command can be executed. If
/// nullptr, the numEventsInWaitList must be 0, indicating that this
/// command does not wait on any event to complete.
const ur_event_handle_t *EventWaitList,
/// [in,out] return an event object that identifies this particular
/// command instance.
ur_event_handle_t *OutEvent) {
// Lock automatically releases when this goes out of scope.
std::scoped_lock<ur_shared_mutex> lock(Queue->Mutex);
ur_device_handle_t Device = Queue->Device;
bool UseCopyEngine = false;
_ur_ze_event_list_t TmpWaitList;
UR_CALL(TmpWaitList.createAndRetainUrZeEventList(
NumEventsInWaitList, EventWaitList, Queue, UseCopyEngine));
// Get a new command list to be used on this call
ur_command_list_ptr_t CommandList{};
UR_CALL(Queue->Context->getAvailableCommandList(
Queue, CommandList, UseCopyEngine, NumEventsInWaitList, EventWaitList,
/* AllowBatching */ false, nullptr /*ForcedCmdQueue*/));
UR_CALL(createEventAndAssociateQueue(
Queue, OutEvent, UR_COMMAND_TIMESTAMP_RECORDING_EXP, CommandList,
/* IsInternal */ false, /* HostVisible */ true));
ze_event_handle_t ZeEvent = (*OutEvent)->ZeEvent;
(*OutEvent)->WaitList = TmpWaitList;
// Reset the end timestamp, in case it has been previously used.
(*OutEvent)->RecordEventEndTimestamp = 0;
uint64_t DeviceStartTimestamp = 0;
UR_CALL(ur::level_zero::urDeviceGetGlobalTimestamps(
Device, &DeviceStartTimestamp, nullptr));
(*OutEvent)->RecordEventStartTimestamp = DeviceStartTimestamp;
// Create a new entry in the queue's recordings.
Queue->EndTimeRecordings[*OutEvent] = 0;
ZE2UR_CALL(zeCommandListAppendWriteGlobalTimestamp,
(CommandList->first, &Queue->EndTimeRecordings[*OutEvent], ZeEvent,
(*OutEvent)->WaitList.Length, (*OutEvent)->WaitList.ZeEventList));
UR_CALL(
Queue->executeCommandList(CommandList, Blocking, false /* OkToBatch */));
return UR_RESULT_SUCCESS;
}
ur_result_t
/// [in] number of events in the event list
urEventWait(uint32_t NumEvents,
/// [in][range(0, numEvents)] pointer to a
/// list of events to wait for completion
const ur_event_handle_t *EventWaitList) {
for (uint32_t I = 0; I < NumEvents; I++) {
auto e = EventWaitList[I];
auto UrQueue = e->UrQueue;
if (UrQueue && UrQueue->ZeEventsScope == OnDemandHostVisibleProxy) {
// Make sure to add all host-visible "proxy" event signals if needed.
// This ensures that all signalling commands are submitted below and
// thus proxy events can be waited without a deadlock.
//
ur_event_handle_t_ *Event = ur_cast<ur_event_handle_t_ *>(e);
if (!Event->hasExternalRefs())
die("urEventWait must not be called for an internal event");
ze_event_handle_t ZeHostVisibleEvent;
if (auto Res = Event->getOrCreateHostVisibleEvent(ZeHostVisibleEvent))
return Res;
}
}
// Submit dependent open command lists for execution, if any
for (uint32_t I = 0; I < NumEvents; I++) {
ur_event_handle_t_ *Event = ur_cast<ur_event_handle_t_ *>(EventWaitList[I]);
auto UrQueue = Event->UrQueue;
if (UrQueue) {
// Lock automatically releases when this goes out of scope.
std::scoped_lock<ur_shared_mutex> lock(UrQueue->Mutex);
UR_CALL(UrQueue->executeAllOpenCommandLists());
}
}
std::unordered_set<ur_queue_handle_t> Queues;
for (uint32_t I = 0; I < NumEvents; I++) {
{
ur_event_handle_t_ *Event =
ur_cast<ur_event_handle_t_ *>(EventWaitList[I]);
{
std::shared_lock<ur_shared_mutex> EventLock(Event->Mutex);
if (!Event->hasExternalRefs())
die("urEventWait must not be called for an internal event");
if (!Event->Completed) {
auto HostVisibleEvent = Event->HostVisibleEvent;
if (!HostVisibleEvent)
die("The host-visible proxy event missing");
ze_event_handle_t ZeEvent = HostVisibleEvent->ZeEvent;
logger::debug("ZeEvent = {}", ur_cast<std::uintptr_t>(ZeEvent));
// If this event was an inner batched event, then sync with
// the Queue instead of waiting on the event.
if (HostVisibleEvent->IsInnerBatchedEvent && Event->ZeBatchedQueue) {
ZE2UR_CALL(zeHostSynchronize, (Event->ZeBatchedQueue));
} else {
ZE2UR_CALL(zeHostSynchronize, (ZeEvent));
}
Event->Completed = true;
}
}
if (auto Q = Event->UrQueue) {
if (Q->UsingImmCmdLists && Q->isInOrderQueue())
// Use information about waited event to cleanup completed events in
// the in-order queue.
CleanupEventsInImmCmdLists(
Event->UrQueue, false /* QueueLocked */, false /* QueueSynced */,
reinterpret_cast<ur_event_handle_t>(Event));
else {
// NOTE: we are cleaning up after the event here to free resources
// sooner in case run-time is not calling urEventRelease soon enough.
CleanupCompletedEvent(reinterpret_cast<ur_event_handle_t>(Event),
false /*QueueLocked*/,
false /*SetEventCompleted*/);
// For the case when we have out-of-order queue or regular command
// lists its more efficient to check fences so put the queue in the
// set to cleanup later.
Queues.insert(Q);
}
}
}
}
// We waited some events above, check queue for signaled command lists and
// reset them.
for (auto &Q : Queues) {
std::unique_lock<ur_shared_mutex> Lock(Q->Mutex);
resetCommandLists(Q);
}
return UR_RESULT_SUCCESS;
}
ur_result_t
/// [in] handle of the event object
urEventRetain(/** [in] handle of the event object */ ur_event_handle_t Event) {
Event->RefCountExternal++;
Event->RefCount.increment();
return UR_RESULT_SUCCESS;
}
ur_result_t
urEventRelease(/** [in] handle of the event object */ ur_event_handle_t Event) {
Event->RefCountExternal--;
bool isEventsWaitCompleted =
Event->CommandType == UR_COMMAND_EVENTS_WAIT && Event->Completed;
UR_CALL(urEventReleaseInternal(Event));
// If this is a Completed Event Wait Out Event, then we need to cleanup the
// event at user release and not at the time of completion.
if (isEventsWaitCompleted) {
UR_CALL(CleanupCompletedEvent((Event), false, false));
}
return UR_RESULT_SUCCESS;
}
ur_result_t urEventGetNativeHandle(
/// [in] handle of the event.
ur_event_handle_t Event,
/// [out] a pointer to the native handle of the event.
ur_native_handle_t *NativeEvent) {
{
std::shared_lock<ur_shared_mutex> Lock(Event->Mutex);
auto *ZeEvent = ur_cast<ze_event_handle_t *>(NativeEvent);
*ZeEvent = Event->ZeEvent;
}
// Event can potentially be in an open command-list, make sure that
// it is submitted for execution to avoid potential deadlock if
// interop app is going to wait for it.
auto Queue = Event->UrQueue;
if (Queue) {
std::scoped_lock<ur_shared_mutex> lock(Queue->Mutex);
const auto &OpenCommandList = Queue->eventOpenCommandList(Event);
if (OpenCommandList != Queue->CommandListMap.end()) {
UR_CALL(
Queue->executeOpenCommandList(OpenCommandList->second.isCopy(Queue)));
}
}
return UR_RESULT_SUCCESS;
}
ur_result_t urExtEventCreate(
/// [in] handle of the context object
ur_context_handle_t Context,
ur_event_handle_t
/// [out] pointer to the handle of the event object created.
*Event) {
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false /*IsMultiDevice*/,
true /*HostVisible*/, Event,
false /*CounterBasedEventEnabled*/,
false /*ForceDisableProfiling*/, false));
(*Event)->RefCountExternal++;
if (!(*Event)->CounterBasedEventsEnabled)
ZE2UR_CALL(zeEventHostSignal, ((*Event)->ZeEvent));
return UR_RESULT_SUCCESS;
}
ur_result_t urEventCreateWithNativeHandle(
/// [in] the native handle of the event.
ur_native_handle_t NativeEvent,
/// [in] handle of the context object
ur_context_handle_t Context, const ur_event_native_properties_t *Properties,
/// [out] pointer to the handle of the event object created.
ur_event_handle_t *Event) {
// we dont have urEventCreate, so use this check for now to know that
// the call comes from urEventCreate()
if (reinterpret_cast<ze_event_handle_t>(NativeEvent) == nullptr) {
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false /*IsMultiDevice*/,
true /*HostVisible*/, Event,
false /*CounterBasedEventEnabled*/,
false /*ForceDisableProfiling*/, false));
(*Event)->RefCountExternal++;
if (!(*Event)->CounterBasedEventsEnabled)
ZE2UR_CALL(zeEventHostSignal, ((*Event)->ZeEvent));
return UR_RESULT_SUCCESS;
}
auto ZeEvent = ur_cast<ze_event_handle_t>(NativeEvent);
ur_event_handle_t_ *UREvent{};
try {
UREvent = new ur_event_handle_t_(ZeEvent, nullptr /* ZeEventPool */,
Context, UR_EXT_COMMAND_TYPE_USER,
Properties->isNativeHandleOwned);
UREvent->RefCountExternal++;
} catch (const std::bad_alloc &) {
return UR_RESULT_ERROR_OUT_OF_HOST_MEMORY;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
// Assume native event is host-visible, or otherwise we'd
// need to create a host-visible proxy for it.
UREvent->HostVisibleEvent = reinterpret_cast<ur_event_handle_t>(UREvent);
// Unlike regular events managed by SYCL RT we don't have to wait for interop
// events completion, and not need to do the their `cleanup()`. This in
// particular guarantees that the extra `urEventRelease` is not called on
// them. That release is needed to match the `urEventRetain` of regular events
// made for waiting for event completion, but not this interop event.
UREvent->CleanedUp = true;
*Event = reinterpret_cast<ur_event_handle_t>(UREvent);
UREvent->IsInteropNativeHandle = true;
return UR_RESULT_SUCCESS;
}
ur_result_t urEventSetCallback(
/// [in] handle of the event object
ur_event_handle_t Event,
/// [in] execution status of the event
ur_execution_info_t ExecStatus,
/// [in] execution status of the event
ur_event_callback_t Notify,
/// [in][out][optional] pointer to data to be passed to callback.