forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcommand_buffer.cpp
2199 lines (1885 loc) · 90 KB
/
command_buffer.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
//===--------- command_buffer.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 "command_buffer.hpp"
#include "helpers/kernel_helpers.hpp"
#include "logger/ur_logger.hpp"
#include "ur_interface_loader.hpp"
#include "ur_level_zero.hpp"
/* L0 Command-buffer Extension Doc see:
https://github.com/intel/llvm/blob/sycl/sycl/doc/design/CommandGraph.md#level-zero
*/
// Print the name of a variable and its value in the L0 debug log
#define DEBUG_LOG(VAR) logger::debug(#VAR " {}", VAR);
namespace {
// Checks whether zeCommandListImmediateAppendCommandListsExp can be used for a
// given Context and Device.
bool checkImmediateAppendSupport(ur_context_handle_t Context,
ur_device_handle_t Device) {
bool DriverSupportsImmediateAppend =
Context->getPlatform()->ZeCommandListImmediateAppendExt.Supported;
// If this environment variable is:
// - Set to 1: the immediate append path will always be enabled as long the
// pre-requisites are met.
// - Set to 0: the immediate append path will always be disabled.
// - Not Defined: The default behaviour will be used which enables the
// immediate append path only for some devices when the pre-requisites are
// met.
const char *AppendEnvVarName = "UR_L0_CMD_BUFFER_USE_IMMEDIATE_APPEND_PATH";
const char *UrRet = std::getenv(AppendEnvVarName);
if (UrRet) {
const bool EnableAppendPath = std::atoi(UrRet) == 1;
if (EnableAppendPath && !Device->ImmCommandListUsed) {
logger::error("{} is set but immediate command-lists are currently "
"disabled. Immediate command-lists are "
"required to use the immediate append path.",
AppendEnvVarName);
std::abort();
}
if (EnableAppendPath && !DriverSupportsImmediateAppend) {
logger::error("{} is set but "
"the current driver does not support the "
"zeCommandListImmediateAppendCommandListsExp entrypoint.",
AppendEnvVarName);
std::abort();
}
return EnableAppendPath;
}
return Device->isPVC() && Device->ImmCommandListUsed &&
DriverSupportsImmediateAppend;
}
// Checks whether counter based events are supported for a given Device.
bool checkCounterBasedEventsSupport(ur_device_handle_t Device) {
static const bool useDriverCounterBasedEvents = [] {
const char *UrRet = std::getenv("UR_L0_USE_DRIVER_COUNTER_BASED_EVENTS");
if (!UrRet) {
return true;
}
return std::atoi(UrRet) != 0;
}();
return Device->ImmCommandListUsed && Device->useDriverInOrderLists() &&
useDriverCounterBasedEvents &&
Device->Platform->ZeDriverEventPoolCountingEventsExtensionFound;
}
// Gets a C pointer from a vector. If the vector is empty returns nullptr
// instead. This is different from the behaviour of the data() member function
// of the vector class which might not return nullptr when the vector is empty.
template <typename T> T *getPointerFromVector(std::vector<T> &V) {
return V.size() == 0 ? nullptr : V.data();
}
/**
* Default to using compute engine for fill operation, but allow to override
* this with an environment variable. Disable the copy engine if the pattern
* size is larger than the maximum supported.
* @param[in] CommandBuffer The CommandBuffer where the fill command will be
* appended.
* @param[in] PatternSize The pattern size for the fill command.
* @param[out] PreferCopyEngine Whether copy engine usage should be enabled or
* disabled for fill commands.
* @return UR_RESULT_SUCCESS or an error code on failure
*/
ur_result_t
preferCopyEngineForFill(ur_exp_command_buffer_handle_t CommandBuffer,
size_t PatternSize, bool &PreferCopyEngine) {
assert(PatternSize > 0);
PreferCopyEngine = false;
if (!CommandBuffer->useCopyEngine()) {
return UR_RESULT_SUCCESS;
}
// If the copy engine is available, and it supports this pattern size, the
// command should be enqueued in the copy command list, otherwise enqueue it
// in the compute command list.
PreferCopyEngine =
PatternSize <=
CommandBuffer->Device
->QueueGroup[ur_device_handle_t_::queue_group_info_t::MainCopy]
.ZeProperties.maxMemoryFillPatternSize;
if (!PreferCopyEngine) {
// Pattern size must fit the compute queue capabilities.
UR_ASSERT(
PatternSize <=
CommandBuffer->Device
->QueueGroup[ur_device_handle_t_::queue_group_info_t::Compute]
.ZeProperties.maxMemoryFillPatternSize,
UR_RESULT_ERROR_INVALID_VALUE);
}
const char *UrRet = std::getenv("UR_L0_USE_COPY_ENGINE_FOR_FILL");
const char *PiRet =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_COPY_ENGINE_FOR_FILL");
PreferCopyEngine =
PreferCopyEngine &&
(UrRet ? std::stoi(UrRet) : (PiRet ? std::stoi(PiRet) : 0));
return UR_RESULT_SUCCESS;
}
/**
* Helper function for finding the Level Zero events associated with the
* commands in a command-buffer, each event is pointed to by a sync-point in the
* wait list.
* @param[in] CommandBuffer to lookup the L0 events from.
* @param[in] NumSyncPointsInWaitList Length of \p SyncPointWaitList.
* @param[in] SyncPointWaitList List of sync points in \p CommandBuffer to find
* the L0 events for.
* @param[out] ZeEventList Return parameter for the L0 events associated with
* each sync-point in \p SyncPointWaitList.
* @return UR_RESULT_SUCCESS or an error code on failure
*/
ur_result_t getEventsFromSyncPoints(
const ur_exp_command_buffer_handle_t &CommandBuffer,
size_t NumSyncPointsInWaitList,
const ur_exp_command_buffer_sync_point_t *SyncPointWaitList,
std::vector<ze_event_handle_t> &ZeEventList) {
if (!SyncPointWaitList || NumSyncPointsInWaitList == 0)
return UR_RESULT_SUCCESS;
// For each sync-point add associated L0 event to the return list.
for (size_t i = 0; i < NumSyncPointsInWaitList; i++) {
if (auto EventHandle = CommandBuffer->SyncPoints.find(SyncPointWaitList[i]);
EventHandle != CommandBuffer->SyncPoints.end()) {
ZeEventList.push_back(EventHandle->second->ZeEvent);
} else {
return UR_RESULT_ERROR_INVALID_VALUE;
}
}
return UR_RESULT_SUCCESS;
}
/**
* If needed, creates a sync point for a given command and returns the L0
* events associated with the sync point.
* This operations is skipped if the command-buffer is in order.
* @param[in] CommandType The type of the command.
* @param[in] CommandBuffer The CommandBuffer where the command is appended.
* @param[in] NumSyncPointsInWaitList Number of sync points that are
* dependencies for the command.
* @param[in] SyncPointWaitList List of sync point that are dependencies for the
* command.
* @param[in] HostVisible Whether the event associated with the sync point
* should be host visible.
* @param[out][optional] RetSyncPoint The new sync point.
* @param[out] ZeEventList A list of L0 events that are dependencies for this
* sync point.
* @param[out] ZeLaunchEvent The L0 event associated with this sync point.
* @return UR_RESULT_SUCCESS or an error code on failure
*/
ur_result_t createSyncPointAndGetZeEvents(
ur_command_t CommandType, ur_exp_command_buffer_handle_t CommandBuffer,
uint32_t NumSyncPointsInWaitList,
const ur_exp_command_buffer_sync_point_t *SyncPointWaitList,
bool HostVisible, ur_exp_command_buffer_sync_point_t *RetSyncPoint,
std::vector<ze_event_handle_t> &ZeEventList,
ze_event_handle_t &ZeLaunchEvent) {
ZeLaunchEvent = nullptr;
if (CommandBuffer->IsInOrderCmdList) {
return UR_RESULT_SUCCESS;
}
UR_CALL(getEventsFromSyncPoints(CommandBuffer, NumSyncPointsInWaitList,
SyncPointWaitList, ZeEventList));
ur_event_handle_t LaunchEvent;
UR_CALL(EventCreate(CommandBuffer->Context, nullptr /*Queue*/,
false /*IsMultiDevice*/, HostVisible, &LaunchEvent,
false /*CounterBasedEventEnabled*/,
!CommandBuffer->IsProfilingEnabled,
false /*InterruptBasedEventEnabled*/));
LaunchEvent->CommandType = CommandType;
ZeLaunchEvent = LaunchEvent->ZeEvent;
// Get sync point and register the event with it.
ur_exp_command_buffer_sync_point_t SyncPoint =
CommandBuffer->getNextSyncPoint();
CommandBuffer->registerSyncPoint(SyncPoint, LaunchEvent);
if (RetSyncPoint) {
*RetSyncPoint = SyncPoint;
}
return UR_RESULT_SUCCESS;
}
// Shared by all memory read/write/copy PI interfaces.
// Helper function for common code when enqueuing memory operations to a command
// buffer.
ur_result_t enqueueCommandBufferMemCopyHelper(
ur_command_t CommandType, ur_exp_command_buffer_handle_t CommandBuffer,
void *Dst, const void *Src, size_t Size, bool PreferCopyEngine,
uint32_t NumSyncPointsInWaitList,
const ur_exp_command_buffer_sync_point_t *SyncPointWaitList,
ur_exp_command_buffer_sync_point_t *RetSyncPoint) {
std::vector<ze_event_handle_t> ZeEventList;
ze_event_handle_t ZeLaunchEvent = nullptr;
UR_CALL(createSyncPointAndGetZeEvents(
CommandType, CommandBuffer, NumSyncPointsInWaitList, SyncPointWaitList,
false, RetSyncPoint, ZeEventList, ZeLaunchEvent));
ze_command_list_handle_t ZeCommandList =
CommandBuffer->chooseCommandList(PreferCopyEngine);
ZE2UR_CALL(zeCommandListAppendMemoryCopy,
(ZeCommandList, Dst, Src, Size, ZeLaunchEvent, ZeEventList.size(),
getPointerFromVector(ZeEventList)));
return UR_RESULT_SUCCESS;
}
// Helper function for common code when enqueuing rectangular memory operations
// to a command-buffer.
ur_result_t enqueueCommandBufferMemCopyRectHelper(
ur_command_t CommandType, ur_exp_command_buffer_handle_t CommandBuffer,
void *Dst, const void *Src, ur_rect_offset_t SrcOrigin,
ur_rect_offset_t DstOrigin, ur_rect_region_t Region, size_t SrcRowPitch,
size_t DstRowPitch, size_t SrcSlicePitch, size_t DstSlicePitch,
bool PreferCopyEngine, uint32_t NumSyncPointsInWaitList,
const ur_exp_command_buffer_sync_point_t *SyncPointWaitList,
ur_exp_command_buffer_sync_point_t *RetSyncPoint) {
uint32_t SrcOriginX = ur_cast<uint32_t>(SrcOrigin.x);
uint32_t SrcOriginY = ur_cast<uint32_t>(SrcOrigin.y);
uint32_t SrcOriginZ = ur_cast<uint32_t>(SrcOrigin.z);
uint32_t SrcPitch = SrcRowPitch;
if (SrcPitch == 0)
SrcPitch = ur_cast<uint32_t>(Region.width);
if (SrcSlicePitch == 0)
SrcSlicePitch = ur_cast<uint32_t>(Region.height) * SrcPitch;
uint32_t DstOriginX = ur_cast<uint32_t>(DstOrigin.x);
uint32_t DstOriginY = ur_cast<uint32_t>(DstOrigin.y);
uint32_t DstOriginZ = ur_cast<uint32_t>(DstOrigin.z);
uint32_t DstPitch = DstRowPitch;
if (DstPitch == 0)
DstPitch = ur_cast<uint32_t>(Region.width);
if (DstSlicePitch == 0)
DstSlicePitch = ur_cast<uint32_t>(Region.height) * DstPitch;
uint32_t Width = ur_cast<uint32_t>(Region.width);
uint32_t Height = ur_cast<uint32_t>(Region.height);
uint32_t Depth = ur_cast<uint32_t>(Region.depth);
const ze_copy_region_t ZeSrcRegion = {SrcOriginX, SrcOriginY, SrcOriginZ,
Width, Height, Depth};
const ze_copy_region_t ZeDstRegion = {DstOriginX, DstOriginY, DstOriginZ,
Width, Height, Depth};
std::vector<ze_event_handle_t> ZeEventList;
ze_event_handle_t ZeLaunchEvent = nullptr;
UR_CALL(createSyncPointAndGetZeEvents(
CommandType, CommandBuffer, NumSyncPointsInWaitList, SyncPointWaitList,
false, RetSyncPoint, ZeEventList, ZeLaunchEvent));
ze_command_list_handle_t ZeCommandList =
CommandBuffer->chooseCommandList(PreferCopyEngine);
ZE2UR_CALL(zeCommandListAppendMemoryCopyRegion,
(ZeCommandList, Dst, &ZeDstRegion, DstPitch, DstSlicePitch, Src,
&ZeSrcRegion, SrcPitch, SrcSlicePitch, ZeLaunchEvent,
ZeEventList.size(), getPointerFromVector(ZeEventList)));
return UR_RESULT_SUCCESS;
}
// Helper function for enqueuing memory fills.
ur_result_t enqueueCommandBufferFillHelper(
ur_command_t CommandType, ur_exp_command_buffer_handle_t CommandBuffer,
void *Ptr, const void *Pattern, size_t PatternSize, size_t Size,
uint32_t NumSyncPointsInWaitList,
const ur_exp_command_buffer_sync_point_t *SyncPointWaitList,
ur_exp_command_buffer_sync_point_t *RetSyncPoint) {
// Pattern size must be a power of two.
UR_ASSERT((PatternSize > 0) && ((PatternSize & (PatternSize - 1)) == 0),
UR_RESULT_ERROR_INVALID_VALUE);
std::vector<ze_event_handle_t> ZeEventList;
ze_event_handle_t ZeLaunchEvent = nullptr;
UR_CALL(createSyncPointAndGetZeEvents(
CommandType, CommandBuffer, NumSyncPointsInWaitList, SyncPointWaitList,
true, RetSyncPoint, ZeEventList, ZeLaunchEvent));
bool PreferCopyEngine;
UR_CALL(
preferCopyEngineForFill(CommandBuffer, PatternSize, PreferCopyEngine));
ze_command_list_handle_t ZeCommandList =
CommandBuffer->chooseCommandList(PreferCopyEngine);
ZE2UR_CALL(zeCommandListAppendMemoryFill,
(ZeCommandList, Ptr, Pattern, PatternSize, Size, ZeLaunchEvent,
ZeEventList.size(), getPointerFromVector(ZeEventList)));
return UR_RESULT_SUCCESS;
}
} // namespace
ur_exp_command_buffer_handle_t_::ur_exp_command_buffer_handle_t_(
ur_context_handle_t Context, ur_device_handle_t Device,
ze_command_list_handle_t CommandList,
ze_command_list_handle_t CommandListTranslated,
ze_command_list_handle_t CommandListResetEvents,
ze_command_list_handle_t CopyCommandList,
ur_event_handle_t ExecutionFinishedEvent, ur_event_handle_t WaitEvent,
ur_event_handle_t AllResetEvent, ur_event_handle_t CopyFinishedEvent,
ur_event_handle_t ComputeFinishedEvent,
const ur_exp_command_buffer_desc_t *Desc, const bool IsInOrderCmdList,
const bool UseImmediateAppendPath)
: Context(Context), Device(Device), ZeComputeCommandList(CommandList),
ZeComputeCommandListTranslated(CommandListTranslated),
ZeCommandListResetEvents(CommandListResetEvents),
ZeCopyCommandList(CopyCommandList),
ExecutionFinishedEvent(ExecutionFinishedEvent), WaitEvent(WaitEvent),
AllResetEvent(AllResetEvent), CopyFinishedEvent(CopyFinishedEvent),
ComputeFinishedEvent(ComputeFinishedEvent), ZeFencesMap(),
ZeActiveFence(nullptr), SyncPoints(), NextSyncPoint(0),
IsUpdatable(Desc ? Desc->isUpdatable : false),
IsProfilingEnabled(Desc ? Desc->enableProfiling : false),
IsInOrderCmdList(IsInOrderCmdList),
UseImmediateAppendPath(UseImmediateAppendPath) {
ur::level_zero::urContextRetain(Context);
ur::level_zero::urDeviceRetain(Device);
}
void ur_exp_command_buffer_handle_t_::cleanupCommandBufferResources() {
// Release the memory allocated to the Context stored in the command_buffer
ur::level_zero::urContextRelease(Context);
// Release the device
ur::level_zero::urDeviceRelease(Device);
// Release the memory allocated to the CommandList stored in the
// command_buffer
if (ZeComputeCommandList) {
ZE_CALL_NOCHECK(zeCommandListDestroy, (ZeComputeCommandList));
}
if (useCopyEngine() && ZeCopyCommandList) {
ZE_CALL_NOCHECK(zeCommandListDestroy, (ZeCopyCommandList));
}
// Release the memory allocated to the CommandListResetEvents stored in the
// command_buffer
if (ZeCommandListResetEvents) {
ZE_CALL_NOCHECK(zeCommandListDestroy, (ZeCommandListResetEvents));
}
// Release additional events used by the command_buffer.
if (ExecutionFinishedEvent) {
CleanupCompletedEvent(ExecutionFinishedEvent, false /*QueueLocked*/,
false /*SetEventCompleted*/);
urEventReleaseInternal(ExecutionFinishedEvent);
}
if (WaitEvent) {
CleanupCompletedEvent(WaitEvent, false /*QueueLocked*/,
false /*SetEventCompleted*/);
urEventReleaseInternal(WaitEvent);
}
if (AllResetEvent) {
CleanupCompletedEvent(AllResetEvent, false /*QueueLocked*/,
false /*SetEventCompleted*/);
urEventReleaseInternal(AllResetEvent);
}
if (CopyFinishedEvent) {
CleanupCompletedEvent(CopyFinishedEvent, false /*QueueLocked*/,
false /*SetEventCompleted*/);
urEventReleaseInternal(CopyFinishedEvent);
}
if (ComputeFinishedEvent) {
CleanupCompletedEvent(ComputeFinishedEvent, false /*QueueLocked*/,
false /*SetEventCompleted*/);
urEventReleaseInternal(ComputeFinishedEvent);
}
if (CurrentSubmissionEvent) {
urEventReleaseInternal(CurrentSubmissionEvent);
}
// Release events added to the command_buffer
for (auto &Sync : SyncPoints) {
auto &Event = Sync.second;
CleanupCompletedEvent(Event, false /*QueueLocked*/,
false /*SetEventCompleted*/);
urEventReleaseInternal(Event);
}
// Release fences allocated to command-buffer
for (auto &ZeFencePair : ZeFencesMap) {
auto &ZeFence = ZeFencePair.second;
ZE_CALL_NOCHECK(zeFenceDestroy, (ZeFence));
}
auto ReleaseIndirectMem = [](ur_kernel_handle_t Kernel) {
if (IndirectAccessTrackingEnabled) {
// urKernelRelease is called by CleanupCompletedEvent(Event) as soon as
// kernel execution has finished. This is the place where we need to
// release memory allocations. If kernel is not in use (not submitted by
// some other thread) then release referenced memory allocations. As a
// result, memory can be deallocated and context can be removed from
// container in the platform. That's why we need to lock a mutex here.
ur_platform_handle_t Platform = Kernel->Program->Context->getPlatform();
std::scoped_lock<ur_shared_mutex> ContextsLock(Platform->ContextsMutex);
if (--Kernel->SubmissionsCount == 0) {
// Kernel is not submitted for execution, release referenced memory
// allocations.
for (auto &MemAlloc : Kernel->MemAllocs) {
// std::pair<void *const, MemAllocRecord> *, Hash
USMFreeHelper(MemAlloc->second.Context, MemAlloc->first,
MemAlloc->second.OwnNativeHandle);
}
Kernel->MemAllocs.clear();
}
}
};
for (auto &AssociatedKernel : KernelsList) {
ReleaseIndirectMem(AssociatedKernel);
ur::level_zero::urKernelRelease(AssociatedKernel);
}
}
void ur_exp_command_buffer_handle_t_::registerSyncPoint(
ur_exp_command_buffer_sync_point_t SyncPoint, ur_event_handle_t Event) {
SyncPoints[SyncPoint] = Event;
NextSyncPoint++;
ZeEventsList.push_back(Event->ZeEvent);
}
ze_command_list_handle_t
ur_exp_command_buffer_handle_t_::chooseCommandList(bool PreferCopyEngine) {
if (PreferCopyEngine && this->useCopyEngine() && !this->IsInOrderCmdList) {
// We indicate that ZeCopyCommandList contains commands to be submitted.
this->MCopyCommandListEmpty = false;
return this->ZeCopyCommandList;
}
return this->ZeComputeCommandList;
}
ur_result_t ur_exp_command_buffer_handle_t_::getFenceForQueue(
ze_command_queue_handle_t &ZeCommandQueue, ze_fence_handle_t &ZeFence) {
// If we already have created a fence for this queue, first reset then reuse
// it, otherwise create a new fence.
auto ZeWorkloadFenceForQueue = this->ZeFencesMap.find(ZeCommandQueue);
if (ZeWorkloadFenceForQueue == this->ZeFencesMap.end()) {
ZeStruct<ze_fence_desc_t> ZeFenceDesc;
ZE2UR_CALL(zeFenceCreate, (ZeCommandQueue, &ZeFenceDesc, &ZeFence));
this->ZeFencesMap.insert({{ZeCommandQueue, ZeFence}});
} else {
ZeFence = ZeWorkloadFenceForQueue->second;
ZE2UR_CALL(zeFenceReset, (ZeFence));
}
this->ZeActiveFence = ZeFence;
return UR_RESULT_SUCCESS;
}
kernel_command_handle::kernel_command_handle(
ur_exp_command_buffer_handle_t CommandBuffer, ur_kernel_handle_t Kernel,
uint64_t CommandId, uint32_t WorkDim, bool UserDefinedLocalSize,
uint32_t NumKernelAlternatives, ur_kernel_handle_t *KernelAlternatives)
: ur_exp_command_buffer_command_handle_t_(CommandBuffer, CommandId),
WorkDim(WorkDim), UserDefinedLocalSize(UserDefinedLocalSize),
Kernel(Kernel) {
// Add the default kernel to the list of valid kernels
ur::level_zero::urKernelRetain(Kernel);
ValidKernelHandles.insert(Kernel);
// Add alternative kernels if provided
if (KernelAlternatives) {
for (size_t i = 0; i < NumKernelAlternatives; i++) {
ur::level_zero::urKernelRetain(KernelAlternatives[i]);
ValidKernelHandles.insert(KernelAlternatives[i]);
}
}
}
kernel_command_handle::~kernel_command_handle() {
for (const ur_kernel_handle_t &KernelHandle : ValidKernelHandles) {
ur::level_zero::urKernelRelease(KernelHandle);
}
}
namespace ur::level_zero {
/**
* Creates a L0 command list
* @param[in] Context The Context associated with the command-list
* @param[in] Device The Device associated with the command-list
* @param[in] IsInOrder Whether the command-list should be in-order.
* @param[in] IsUpdatable Whether the command-list should be mutable.
* @param[in] IsCopy Whether to use copy-engine for the the new command-list.
* @param[out] CommandList The L0 command-list created by this function.
* @return UR_RESULT_SUCCESS or an error code on failure
*/
ur_result_t createMainCommandList(ur_context_handle_t Context,
ur_device_handle_t Device, bool IsInOrder,
bool IsUpdatable, bool IsCopy,
ze_command_list_handle_t &CommandList) {
auto Type = IsCopy ? ur_device_handle_t_::queue_group_info_t::type::MainCopy
: ur_device_handle_t_::queue_group_info_t::type::Compute;
uint32_t QueueGroupOrdinal = Device->QueueGroup[Type].ZeOrdinal;
ZeStruct<ze_command_list_desc_t> ZeCommandListDesc;
ZeCommandListDesc.commandQueueGroupOrdinal = QueueGroupOrdinal;
// For non-linear graph, dependencies between commands are explicitly enforced
// by sync points when enqueuing. Consequently, relax the command ordering in
// the command list can enable the backend to further optimize the workload
ZeCommandListDesc.flags = IsInOrder ? ZE_COMMAND_LIST_FLAG_IN_ORDER
: ZE_COMMAND_LIST_FLAG_RELAXED_ORDERING;
DEBUG_LOG(ZeCommandListDesc.flags);
ZeStruct<ze_mutable_command_list_exp_desc_t> ZeMutableCommandListDesc;
if (IsUpdatable) {
ZeMutableCommandListDesc.flags = 0;
ZeCommandListDesc.pNext = &ZeMutableCommandListDesc;
}
ZE2UR_CALL(zeCommandListCreate, (Context->ZeContext, Device->ZeDevice,
&ZeCommandListDesc, &CommandList));
return UR_RESULT_SUCCESS;
}
/**
* Checks whether the command-buffer can be constructed using in order
* command-lists.
* @param[in] Context The Context associated with the command-buffer.
* @param[in] CommandBufferDesc The description of the command-buffer.
* @return Returns true if in order command-lists can be enabled.
*/
bool canBeInOrder(ur_context_handle_t Context,
const ur_exp_command_buffer_desc_t *CommandBufferDesc) {
const char *UrRet = std::getenv("UR_L0_USE_DRIVER_INORDER_LISTS");
// In-order command-lists are not available in old driver version.
bool DriverInOrderRequested = UrRet ? std::atoi(UrRet) != 0 : false;
bool CompatibleDriver = Context->getPlatform()->isDriverVersionNewerOrSimilar(
1, 3, L0_DRIVER_INORDER_MIN_VERSION);
bool CanUseDriverInOrderLists = CompatibleDriver && DriverInOrderRequested;
return CanUseDriverInOrderLists ? CommandBufferDesc->isInOrder : false;
}
/**
* Append the initial barriers to the Compute and Copy command-lists.
* @param CommandBuffer The CommandBuffer
* @return UR_RESULT_SUCCESS or an error code on failure.
*/
ur_result_t appendExecutionWaits(ur_exp_command_buffer_handle_t CommandBuffer) {
std::vector<ze_event_handle_t> PrecondEvents;
if (CommandBuffer->ZeCommandListResetEvents) {
PrecondEvents.push_back(CommandBuffer->AllResetEvent->ZeEvent);
}
if (!CommandBuffer->UseImmediateAppendPath) {
PrecondEvents.push_back(CommandBuffer->WaitEvent->ZeEvent);
}
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeComputeCommandList, nullptr,
PrecondEvents.size(), PrecondEvents.data()));
if (CommandBuffer->ZeCopyCommandList) {
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeCopyCommandList, nullptr, PrecondEvents.size(),
PrecondEvents.data()));
}
return UR_RESULT_SUCCESS;
}
ur_result_t
urCommandBufferCreateExp(ur_context_handle_t Context, ur_device_handle_t Device,
const ur_exp_command_buffer_desc_t *CommandBufferDesc,
ur_exp_command_buffer_handle_t *CommandBuffer) {
bool IsInOrder = canBeInOrder(Context, CommandBufferDesc);
bool EnableProfiling = CommandBufferDesc->enableProfiling && !IsInOrder;
bool IsUpdatable = CommandBufferDesc->isUpdatable;
bool ImmediateAppendPath = checkImmediateAppendSupport(Context, Device);
const bool WaitEventPath = !ImmediateAppendPath;
bool UseCounterBasedEvents = checkCounterBasedEventsSupport(Device) &&
IsInOrder && ImmediateAppendPath;
if (IsUpdatable) {
UR_ASSERT(Context->getPlatform()->ZeMutableCmdListExt.Supported,
UR_RESULT_ERROR_UNSUPPORTED_FEATURE);
}
ze_command_list_handle_t ZeComputeCommandList = nullptr;
ze_command_list_handle_t ZeCopyCommandList = nullptr;
ze_command_list_handle_t ZeCommandListResetEvents = nullptr;
ze_command_list_handle_t ZeComputeCommandListTranslated = nullptr;
UR_CALL(createMainCommandList(Context, Device, IsInOrder, IsUpdatable, false,
ZeComputeCommandList));
// Create a list for copy commands. Note that to simplify the implementation,
// the current implementation only uses the main copy engine and does not use
// the link engine even if available.
if (Device->hasMainCopyEngine()) {
UR_CALL(createMainCommandList(Context, Device, false, false, true,
ZeCopyCommandList));
}
ZE2UR_CALL(zelLoaderTranslateHandle,
(ZEL_HANDLE_COMMAND_LIST, ZeComputeCommandList,
(void **)&ZeComputeCommandListTranslated));
// The CopyFinishedEvent and ComputeFinishedEvent are needed only when using
// the ImmediateAppend Path.
ur_event_handle_t CopyFinishedEvent = nullptr;
ur_event_handle_t ComputeFinishedEvent = nullptr;
if (ImmediateAppendPath) {
if (Device->hasMainCopyEngine()) {
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false, false,
&CopyFinishedEvent, UseCounterBasedEvents,
!EnableProfiling,
false /*InterruptBasedEventEnabled*/));
}
if (EnableProfiling) {
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false /*IsMultiDevice*/,
false /*HostVisible*/, &ComputeFinishedEvent,
UseCounterBasedEvents, !EnableProfiling,
false /*InterruptBasedEventEnabled*/));
}
}
// The WaitEvent is needed only when using WaitEvent Path.
ur_event_handle_t WaitEvent = nullptr;
if (WaitEventPath) {
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false /*IsMultiDevice*/,
false /*HostVisible*/, &WaitEvent,
false /*CounterBasedEventEnabled*/, !EnableProfiling,
false /*InterruptBasedEventEnabled*/));
}
// Create ZeCommandListResetEvents only if counter-based events are not being
// used. Using counter-based events means that there is no need to reset any
// events between executions. Counter-based events can only be enabled on the
// ImmediateAppend Path.
ur_event_handle_t AllResetEvent = nullptr;
ur_event_handle_t ExecutionFinishedEvent = nullptr;
if (!UseCounterBasedEvents) {
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false /*IsMultiDevice*/,
false /*HostVisible*/, &AllResetEvent,
false /*CounterBasedEventEnabled*/, !EnableProfiling,
false /*InterruptBasedEventEnabled*/));
UR_CALL(createMainCommandList(Context, Device, false, false, false,
ZeCommandListResetEvents));
// The ExecutionFinishedEvent is only waited on by ZeCommandListResetEvents.
UR_CALL(EventCreate(Context, nullptr /*Queue*/, false /*IsMultiDevice*/,
false /*HostVisible*/, &ExecutionFinishedEvent,
false /*CounterBasedEventEnabled*/, !EnableProfiling,
false /*InterruptBased*/));
}
try {
*CommandBuffer = new ur_exp_command_buffer_handle_t_(
Context, Device, ZeComputeCommandList, ZeComputeCommandListTranslated,
ZeCommandListResetEvents, ZeCopyCommandList, ExecutionFinishedEvent,
WaitEvent, AllResetEvent, CopyFinishedEvent, ComputeFinishedEvent,
CommandBufferDesc, IsInOrder, ImmediateAppendPath);
} catch (const std::bad_alloc &) {
return UR_RESULT_ERROR_OUT_OF_HOST_MEMORY;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
UR_CALL(appendExecutionWaits(*CommandBuffer));
return UR_RESULT_SUCCESS;
}
ur_result_t
urCommandBufferRetainExp(ur_exp_command_buffer_handle_t CommandBuffer) {
CommandBuffer->RefCount.increment();
return UR_RESULT_SUCCESS;
}
ur_result_t
urCommandBufferReleaseExp(ur_exp_command_buffer_handle_t CommandBuffer) {
if (!CommandBuffer->RefCount.decrementAndTest())
return UR_RESULT_SUCCESS;
CommandBuffer->cleanupCommandBufferResources();
delete CommandBuffer;
return UR_RESULT_SUCCESS;
}
/* Finalizes the command-buffer so that it can later be enqueued using
* enqueueImmediateAppendPath() which uses the
* zeCommandListImmediateAppendCommandListsExp API. */
ur_result_t
finalizeImmediateAppendPath(ur_exp_command_buffer_handle_t CommandBuffer) {
// Wait for the Copy Queue to finish at the end of the compute command list.
if (!CommandBuffer->MCopyCommandListEmpty) {
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeCopyCommandList,
CommandBuffer->CopyFinishedEvent->ZeEvent, 0, nullptr));
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeComputeCommandList, nullptr, 1,
&CommandBuffer->CopyFinishedEvent->ZeEvent));
}
if (CommandBuffer->ZeCommandListResetEvents) {
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeCommandListResetEvents, nullptr, 1,
&CommandBuffer->ExecutionFinishedEvent->ZeEvent));
// Reset the L0 events we use for command-buffer sync-points to the
// non-signaled state. This is required for multiple submissions.
for (auto &Event : CommandBuffer->ZeEventsList) {
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeCommandListResetEvents, Event));
}
if (!CommandBuffer->MCopyCommandListEmpty) {
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeCommandListResetEvents,
CommandBuffer->CopyFinishedEvent->ZeEvent));
}
// Only the profiling command-list has a wait on the ExecutionFinishedEvent
if (CommandBuffer->IsProfilingEnabled) {
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeCommandListResetEvents,
CommandBuffer->ComputeFinishedEvent->ZeEvent));
}
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeCommandListResetEvents,
CommandBuffer->ExecutionFinishedEvent->ZeEvent));
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeCommandListResetEvents,
CommandBuffer->AllResetEvent->ZeEvent, 0, nullptr));
// Reset the all-reset-event for the UR command-buffer that is signaled
// when all events of the main command-list have been reset.
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeComputeCommandList,
CommandBuffer->AllResetEvent->ZeEvent));
// All the events are reset by default. So signal the all reset event for
// the first run of the command-buffer
ZE2UR_CALL(zeEventHostSignal, (CommandBuffer->AllResetEvent->ZeEvent));
}
return UR_RESULT_SUCCESS;
}
/* Finalizes the command-buffer so that it can later be enqueued using
* enqueueWaitEventPath() which uses the zeCommandQueueExecuteCommandLists API.
*/
ur_result_t
finalizeWaitEventPath(ur_exp_command_buffer_handle_t CommandBuffer) {
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeCommandListResetEvents,
CommandBuffer->ExecutionFinishedEvent->ZeEvent));
if (CommandBuffer->IsInOrderCmdList) {
ZE2UR_CALL(zeCommandListAppendSignalEvent,
(CommandBuffer->ZeComputeCommandList,
CommandBuffer->ExecutionFinishedEvent->ZeEvent));
} else {
// Reset the L0 events we use for command-buffer sync-points to the
// non-signaled state. This is required for multiple submissions.
for (auto &Event : CommandBuffer->ZeEventsList) {
ZE2UR_CALL(zeCommandListAppendEventReset,
(CommandBuffer->ZeCommandListResetEvents, Event));
}
// Wait for all the user added commands to complete, and signal the
// command-buffer signal-event when they are done.
ZE2UR_CALL(zeCommandListAppendBarrier,
(CommandBuffer->ZeComputeCommandList,
CommandBuffer->ExecutionFinishedEvent->ZeEvent,
CommandBuffer->ZeEventsList.size(),
CommandBuffer->ZeEventsList.data()));
}
ZE2UR_CALL(zeCommandListAppendSignalEvent,
(CommandBuffer->ZeCommandListResetEvents,
CommandBuffer->AllResetEvent->ZeEvent));
return UR_RESULT_SUCCESS;
}
ur_result_t
urCommandBufferFinalizeExp(ur_exp_command_buffer_handle_t CommandBuffer) {
UR_ASSERT(CommandBuffer, UR_RESULT_ERROR_INVALID_NULL_POINTER);
UR_ASSERT(!CommandBuffer->IsFinalized, UR_RESULT_ERROR_INVALID_OPERATION);
// It is not allowed to append to command list from multiple threads.
std::scoped_lock<ur_shared_mutex> Guard(CommandBuffer->Mutex);
if (CommandBuffer->UseImmediateAppendPath) {
UR_CALL(finalizeImmediateAppendPath(CommandBuffer));
} else {
UR_CALL(finalizeWaitEventPath(CommandBuffer));
}
// Close the command lists and have them ready for dispatch.
ZE2UR_CALL(zeCommandListClose, (CommandBuffer->ZeComputeCommandList));
if (CommandBuffer->ZeCommandListResetEvents) {
ZE2UR_CALL(zeCommandListClose, (CommandBuffer->ZeCommandListResetEvents));
}
if (CommandBuffer->useCopyEngine()) {
ZE2UR_CALL(zeCommandListClose, (CommandBuffer->ZeCopyCommandList));
}
CommandBuffer->IsFinalized = true;
return UR_RESULT_SUCCESS;
}
/**
* Sets the kernel arguments for a kernel command that will be appended to the
* command-buffer.
* @param[in] Device The Device associated with the command-buffer where the
* kernel command will be appended.
* @param[in,out] Arguments stored in the ur_kernel_handle_t object to be set
* on the /p ZeKernel object.
* @param[in] ZeKernel The handle to the Level-Zero kernel that will be
* appended.
* @return UR_RESULT_SUCCESS or an error code on failure
*/
ur_result_t setKernelPendingArguments(
ur_device_handle_t Device,
std::vector<ur_kernel_handle_t_::ArgumentInfo> &PendingArguments,
ze_kernel_handle_t ZeKernel) {
// If there are any pending arguments set them now.
for (auto &Arg : PendingArguments) {
// The ArgValue may be a NULL pointer in which case a NULL value is used for
// the kernel argument declared as a pointer to global or constant memory.
char **ZeHandlePtr = nullptr;
if (Arg.Value) {
UR_CALL(Arg.Value->getZeHandlePtr(ZeHandlePtr, Arg.AccessMode, Device,
nullptr, 0u));
}
ZE2UR_CALL(zeKernelSetArgumentValue,
(ZeKernel, Arg.Index, Arg.Size, ZeHandlePtr));
}
PendingArguments.clear();
return UR_RESULT_SUCCESS;
}
/**
* Creates a new command handle to use in future updates to the command-buffer.
* @param[in] CommandBuffer The CommandBuffer associated with the new command.
* @param[in] Kernel The Kernel associated with the new command.
* @param[in] WorkDim Dimensions of the kernel associated with the new command.
* @param[in] LocalWorkSize LocalWorkSize of the kernel associated with the new
* command.
* @param[out] Command The handle to the new command.
* @return UR_RESULT_SUCCESS or an error code on failure
*/
ur_result_t
createCommandHandle(ur_exp_command_buffer_handle_t CommandBuffer,
ur_kernel_handle_t Kernel, uint32_t WorkDim,
const size_t *LocalWorkSize, uint32_t NumKernelAlternatives,
ur_kernel_handle_t *KernelAlternatives,
ur_exp_command_buffer_command_handle_t *Command) {
assert(CommandBuffer->IsUpdatable);
// If command-buffer is updatable then get command id which is going to be
// used if command is updated in the future. This
// zeCommandListGetNextCommandIdExp can be called only if the command is
// updatable.
uint64_t CommandId = 0;
ZeStruct<ze_mutable_command_id_exp_desc_t> ZeMutableCommandDesc;
ZeMutableCommandDesc.flags = ZE_MUTABLE_COMMAND_EXP_FLAG_KERNEL_ARGUMENTS |
ZE_MUTABLE_COMMAND_EXP_FLAG_GROUP_COUNT |
ZE_MUTABLE_COMMAND_EXP_FLAG_GROUP_SIZE |
ZE_MUTABLE_COMMAND_EXP_FLAG_GLOBAL_OFFSET;
auto Platform = CommandBuffer->Context->getPlatform();
auto ZeDevice = CommandBuffer->Device->ZeDevice;
ze_command_list_handle_t ZeCommandList =
CommandBuffer->ZeComputeCommandListTranslated;
if (Platform->ZeMutableCmdListExt.LoaderExtension) {
ZeCommandList = CommandBuffer->ZeComputeCommandList;
}
if (NumKernelAlternatives > 0) {
ZeMutableCommandDesc.flags |=
ZE_MUTABLE_COMMAND_EXP_FLAG_KERNEL_INSTRUCTION;
std::vector<ze_kernel_handle_t> KernelHandles(NumKernelAlternatives + 1,
nullptr);
ze_kernel_handle_t ZeMainKernel{};
UR_CALL(getZeKernel(ZeDevice, Kernel, &ZeMainKernel));
if (Platform->ZeMutableCmdListExt.LoaderExtension) {
KernelHandles[0] = ZeMainKernel;
} else {
// If the L0 loader is not aware of the MCL extension, the main kernel
// handle needs to be translated.
ZE2UR_CALL(zelLoaderTranslateHandle,
(ZEL_HANDLE_KERNEL, ZeMainKernel, (void **)&KernelHandles[0]));
}
for (size_t i = 0; i < NumKernelAlternatives; i++) {
ze_kernel_handle_t ZeAltKernel{};
UR_CALL(getZeKernel(ZeDevice, KernelAlternatives[i], &ZeAltKernel));
if (Platform->ZeMutableCmdListExt.LoaderExtension) {
KernelHandles[i + 1] = ZeAltKernel;
} else {
// If the L0 loader is not aware of the MCL extension, the kernel
// alternatives need to be translated.
ZE2UR_CALL(zelLoaderTranslateHandle, (ZEL_HANDLE_KERNEL, ZeAltKernel,
(void **)&KernelHandles[i + 1]));
}
}
ZE2UR_CALL(Platform->ZeMutableCmdListExt
.zexCommandListGetNextCommandIdWithKernelsExp,
(ZeCommandList, &ZeMutableCommandDesc, NumKernelAlternatives + 1,
KernelHandles.data(), &CommandId));
} else {
ZE2UR_CALL(Platform->ZeMutableCmdListExt.zexCommandListGetNextCommandIdExp,
(ZeCommandList, &ZeMutableCommandDesc, &CommandId));
}
DEBUG_LOG(CommandId);
try {
auto NewCommand = std::make_unique<kernel_command_handle>(
CommandBuffer, Kernel, CommandId, WorkDim, LocalWorkSize != nullptr,
NumKernelAlternatives, KernelAlternatives);
*Command = NewCommand.get();
CommandBuffer->CommandHandles.push_back(std::move(NewCommand));
} catch (const std::bad_alloc &) {
return UR_RESULT_ERROR_OUT_OF_HOST_MEMORY;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}