-
Notifications
You must be signed in to change notification settings - Fork 827
Expand file tree
/
Copy pathpi_level_zero.cpp
More file actions
5650 lines (4848 loc) · 207 KB
/
pi_level_zero.cpp
File metadata and controls
5650 lines (4848 loc) · 207 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
//===-------- pi_level_zero.cpp - Level Zero Plugin --------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===------------------------------------------------------------------===//
/// \file pi_level_zero.cpp
/// Implementation of Level Zero Plugin.
///
/// \ingroup sycl_pi_level_zero
#include "pi_level_zero.hpp"
#include <CL/sycl/detail/spinlock.hpp>
#include <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <memory>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <level_zero/zes_api.h>
#include <level_zero/zet_api.h>
#include "usm_allocator.hpp"
namespace {
// Controls Level Zero calls serialization to w/a Level Zero driver being not MT
// ready. Recognized values (can be used as a bit mask):
enum {
ZeSerializeNone =
0, // no locking or blocking (except when SYCL RT requested blocking)
ZeSerializeLock = 1, // locking around each ZE_CALL
ZeSerializeBlock =
2, // blocking ZE calls, where supported (usually in enqueue commands)
};
static const pi_uint32 ZeSerialize = [] {
const char *SerializeMode = std::getenv("ZE_SERIALIZE");
const pi_uint32 SerializeModeValue =
SerializeMode ? std::atoi(SerializeMode) : 0;
return SerializeModeValue;
}();
// This class encapsulates actions taken along with a call to Level Zero API.
class ZeCall {
private:
// The global mutex that is used for total serialization of Level Zero calls.
static std::mutex GlobalLock;
public:
ZeCall() {
if ((ZeSerialize & ZeSerializeLock) != 0) {
GlobalLock.lock();
}
}
~ZeCall() {
if ((ZeSerialize & ZeSerializeLock) != 0) {
GlobalLock.unlock();
}
}
// The non-static version just calls static one.
ze_result_t doCall(ze_result_t ZeResult, const char *CallStr,
bool TraceError = true);
};
std::mutex ZeCall::GlobalLock;
// Controls Level Zero calls tracing in zePrint.
static bool ZeDebug = false;
// Controls PI level tracing prints.
static bool PrintPiTrace = false;
// Map Level Zero runtime error code to PI error code
static pi_result mapError(ze_result_t ZeResult) {
// TODO: these mapping need to be clarified and synced with the PI API return
// values, which is TBD.
static std::unordered_map<ze_result_t, pi_result> ErrorMapping = {
{ZE_RESULT_SUCCESS, PI_SUCCESS},
{ZE_RESULT_ERROR_DEVICE_LOST, PI_DEVICE_NOT_FOUND},
{ZE_RESULT_ERROR_INSUFFICIENT_PERMISSIONS, PI_INVALID_OPERATION},
{ZE_RESULT_ERROR_NOT_AVAILABLE, PI_INVALID_OPERATION},
{ZE_RESULT_ERROR_UNINITIALIZED, PI_INVALID_PLATFORM},
{ZE_RESULT_ERROR_INVALID_ARGUMENT, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_NULL_POINTER, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_SIZE, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_SIZE, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_ALIGNMENT, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_SYNCHRONIZATION_OBJECT, PI_INVALID_EVENT},
{ZE_RESULT_ERROR_INVALID_ENUMERATION, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_ENUMERATION, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_IMAGE_FORMAT, PI_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_NATIVE_BINARY, PI_INVALID_BINARY},
{ZE_RESULT_ERROR_INVALID_KERNEL_NAME, PI_INVALID_KERNEL_NAME},
{ZE_RESULT_ERROR_INVALID_FUNCTION_NAME, PI_BUILD_PROGRAM_FAILURE},
{ZE_RESULT_ERROR_OVERLAPPING_REGIONS, PI_INVALID_OPERATION},
{ZE_RESULT_ERROR_INVALID_GROUP_SIZE_DIMENSION,
PI_INVALID_WORK_GROUP_SIZE},
{ZE_RESULT_ERROR_MODULE_BUILD_FAILURE, PI_BUILD_PROGRAM_FAILURE}};
auto It = ErrorMapping.find(ZeResult);
if (It == ErrorMapping.end()) {
return PI_ERROR_UNKNOWN;
}
return It->second;
}
// Trace a call to Level-Zero RT
#define ZE_CALL(Call) \
if (auto Result = ZeCall().doCall(Call, #Call, true)) \
return mapError(Result);
#define ZE_CALL_NOCHECK(Call) ZeCall().doCall(Call, #Call, false)
// Trace an internal PI call; returns in case of an error.
#define PI_CALL(Call) \
if (PrintPiTrace) \
fprintf(stderr, "PI ---> %s\n", #Call); \
pi_result Result = (Call); \
if (Result != PI_SUCCESS) \
return Result;
// Controls Level Zero validation layer and parameter validation.
static bool ZeValidationLayer = false;
enum DebugLevel {
ZE_DEBUG_BASIC = 0x1,
ZE_DEBUG_VALIDATION = 0x2,
ZE_DEBUG_ALL = -1
};
static void zePrint(const char *Format, ...) {
if (ZeDebug) {
va_list Args;
va_start(Args, Format);
vfprintf(stderr, Format, Args);
va_end(Args);
}
}
template <typename T, typename Assign>
pi_result getInfoImpl(size_t param_value_size, void *param_value,
size_t *param_value_size_ret, T value, size_t value_size,
Assign &&assign_func) {
if (param_value != nullptr) {
if (param_value_size < value_size) {
return PI_INVALID_VALUE;
}
assign_func(param_value, value, value_size);
}
if (param_value_size_ret != nullptr) {
*param_value_size_ret = value_size;
}
return PI_SUCCESS;
}
template <typename T>
pi_result getInfo(size_t param_value_size, void *param_value,
size_t *param_value_size_ret, T value) {
auto assignment = [](void *param_value, T value, size_t value_size) {
(void)value_size;
*static_cast<T *>(param_value) = value;
};
return getInfoImpl(param_value_size, param_value, param_value_size_ret, value,
sizeof(T), assignment);
}
template <typename T>
pi_result getInfoArray(size_t array_length, size_t param_value_size,
void *param_value, size_t *param_value_size_ret,
T *value) {
return getInfoImpl(param_value_size, param_value, param_value_size_ret, value,
array_length * sizeof(T), memcpy);
}
template <typename T, typename RetType>
pi_result getInfoArray(size_t array_length, size_t param_value_size,
void *param_value, size_t *param_value_size_ret,
T *value) {
if (param_value) {
memset(param_value, 0, param_value_size);
for (uint32_t I = 0; I < array_length; I++)
((RetType *)param_value)[I] = (RetType)value[I];
}
if (param_value_size_ret)
*param_value_size_ret = array_length * sizeof(RetType);
return PI_SUCCESS;
}
template <>
pi_result getInfo<const char *>(size_t param_value_size, void *param_value,
size_t *param_value_size_ret,
const char *value) {
return getInfoArray(strlen(value) + 1, param_value_size, param_value,
param_value_size_ret, value);
}
class ReturnHelper {
public:
ReturnHelper(size_t param_value_size, void *param_value,
size_t *param_value_size_ret)
: param_value_size(param_value_size), param_value(param_value),
param_value_size_ret(param_value_size_ret) {}
template <class T> pi_result operator()(const T &t) {
return getInfo(param_value_size, param_value, param_value_size_ret, t);
}
private:
size_t param_value_size;
void *param_value;
size_t *param_value_size_ret;
};
} // anonymous namespace
// Global variables used in PI_Level_Zero
// Note we only create a simple pointer variables such that C++ RT won't
// deallocate them automatically at the end of the main program.
// The heap memory allocated for these global variables reclaimed only when
// Sycl RT calls piTearDown().
static std::vector<pi_platform> *PiPlatformsCache =
new std::vector<pi_platform>;
static sycl::detail::SpinLock *PiPlatformsCacheMutex =
new sycl::detail::SpinLock;
static bool PiPlatformCachePopulated = false;
// TODO:: In the following 4 methods we may want to distinguish read access vs.
// write (as it is OK for multiple threads to read the map without locking it).
pi_result _pi_mem::addMapping(void *MappedTo, size_t Offset, size_t Size) {
std::lock_guard<std::mutex> Lock(MappingsMutex);
auto Res = Mappings.insert({MappedTo, {Offset, Size}});
// False as the second value in pair means that mapping was not inserted
// because mapping already exists.
if (!Res.second) {
zePrint("piEnqueueMemBufferMap: duplicate mapping detected\n");
return PI_INVALID_VALUE;
}
return PI_SUCCESS;
}
pi_result _pi_mem::removeMapping(void *MappedTo, Mapping &MapInfo) {
std::lock_guard<std::mutex> Lock(MappingsMutex);
auto It = Mappings.find(MappedTo);
if (It == Mappings.end()) {
zePrint("piEnqueueMemUnmap: unknown memory mapping\n");
return PI_INVALID_VALUE;
}
MapInfo = It->second;
Mappings.erase(It);
return PI_SUCCESS;
}
pi_result
_pi_context::getFreeSlotInExistingOrNewPool(ze_event_pool_handle_t &ZePool,
size_t &Index) {
// Maximum number of events that can be present in an event ZePool is captured
// here. Setting it to 256 gave best possible performance for several
// benchmarks.
static const pi_uint32 MaxNumEventsPerPool = [] {
const auto MaxNumEventsPerPoolEnv =
std::getenv("ZE_MAX_NUMBER_OF_EVENTS_PER_EVENT_POOL");
return MaxNumEventsPerPoolEnv ? std::atoi(MaxNumEventsPerPoolEnv) : 256;
}();
if (MaxNumEventsPerPool == 0) {
zePrint("Zero size can't be specified in the "
"ZE_MAX_NUMBER_OF_EVENTS_PER_EVENT_POOL\n");
return PI_INVALID_VALUE;
}
Index = 0;
// Create one event ZePool per MaxNumEventsPerPool events
if ((ZeEventPool == nullptr) ||
(NumEventsAvailableInEventPool[ZeEventPool] == 0)) {
// Creation of the new ZePool with record in NumEventsAvailableInEventPool
// and initialization of the record in NumEventsLiveInEventPool must be done
// atomically. Otherwise it is possible that decrementAliveEventsInPool will
// be called for the record in NumEventsLiveInEventPool before its
std::lock(NumEventsAvailableInEventPoolMutex,
NumEventsLiveInEventPoolMutex);
std::lock_guard<std::mutex> NumEventsAvailableInEventPoolGuard(
NumEventsAvailableInEventPoolMutex, std::adopt_lock);
std::lock_guard<std::mutex> NumEventsLiveInEventPoolGuard(
NumEventsLiveInEventPoolMutex, std::adopt_lock);
ze_event_pool_desc_t ZeEventPoolDesc = {};
ZeEventPoolDesc.stype = ZE_STRUCTURE_TYPE_EVENT_POOL_DESC;
ZeEventPoolDesc.count = MaxNumEventsPerPool;
// Make all events visible on the host.
// TODO: events that are used only on device side APIs can be optimized
// to not be from the host-visible pool.
//
ZeEventPoolDesc.flags =
ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
std::vector<ze_device_handle_t> ZeDevices;
std::for_each(Devices.begin(), Devices.end(),
[&](pi_device &D) { ZeDevices.push_back(D->ZeDevice); });
ZE_CALL(zeEventPoolCreate(ZeContext, &ZeEventPoolDesc, ZeDevices.size(),
&ZeDevices[0], &ZeEventPool));
NumEventsAvailableInEventPool[ZeEventPool] = MaxNumEventsPerPool - 1;
NumEventsLiveInEventPool[ZeEventPool] = MaxNumEventsPerPool;
} else {
std::lock_guard<std::mutex> NumEventsAvailableInEventPoolGuard(
NumEventsAvailableInEventPoolMutex);
Index = MaxNumEventsPerPool - NumEventsAvailableInEventPool[ZeEventPool];
--NumEventsAvailableInEventPool[ZeEventPool];
}
ZePool = ZeEventPool;
return PI_SUCCESS;
}
pi_result
_pi_context::decrementAliveEventsInPool(ze_event_pool_handle_t ZePool) {
std::lock_guard<std::mutex> Lock(NumEventsLiveInEventPoolMutex);
--NumEventsLiveInEventPool[ZePool];
if (NumEventsLiveInEventPool[ZePool] == 0) {
ZE_CALL(zeEventPoolDestroy(ZePool));
}
return PI_SUCCESS;
}
// Some opencl extensions we know are supported by all Level Zero devices.
constexpr char ZE_SUPPORTED_EXTENSIONS[] =
"cl_khr_il_program cl_khr_subgroups cl_intel_subgroups "
"cl_intel_subgroups_short cl_intel_required_subgroup_size ";
// Forward declarations
static pi_result
enqueueMemCopyHelper(pi_command_type CommandType, pi_queue Queue, void *Dst,
pi_bool BlockingWrite, size_t Size, const void *Src,
pi_uint32 NumEventsInWaitList,
const pi_event *EventWaitList, pi_event *Event);
static pi_result enqueueMemCopyRectHelper(
pi_command_type CommandType, pi_queue Queue, void *SrcBuffer,
void *DstBuffer, pi_buff_rect_offset SrcOrigin,
pi_buff_rect_offset DstOrigin, pi_buff_rect_region Region,
size_t SrcRowPitch, size_t SrcSlicePitch, size_t DstRowPitch,
size_t DstSlicePitch, pi_bool Blocking, pi_uint32 NumEventsInWaitList,
const pi_event *EventWaitList, pi_event *Event);
inline void zeParseError(ze_result_t ZeError, std::string &ErrorString) {
switch (ZeError) {
#define ZE_ERRCASE(ERR) \
case ERR: \
ErrorString = "" #ERR; \
break;
ZE_ERRCASE(ZE_RESULT_SUCCESS)
ZE_ERRCASE(ZE_RESULT_NOT_READY)
ZE_ERRCASE(ZE_RESULT_ERROR_DEVICE_LOST)
ZE_ERRCASE(ZE_RESULT_ERROR_OUT_OF_HOST_MEMORY)
ZE_ERRCASE(ZE_RESULT_ERROR_OUT_OF_DEVICE_MEMORY)
ZE_ERRCASE(ZE_RESULT_ERROR_MODULE_BUILD_FAILURE)
ZE_ERRCASE(ZE_RESULT_ERROR_INSUFFICIENT_PERMISSIONS)
ZE_ERRCASE(ZE_RESULT_ERROR_NOT_AVAILABLE)
ZE_ERRCASE(ZE_RESULT_ERROR_UNINITIALIZED)
ZE_ERRCASE(ZE_RESULT_ERROR_UNSUPPORTED_VERSION)
ZE_ERRCASE(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_ARGUMENT)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_NULL_HANDLE)
ZE_ERRCASE(ZE_RESULT_ERROR_HANDLE_OBJECT_IN_USE)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_NULL_POINTER)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_SIZE)
ZE_ERRCASE(ZE_RESULT_ERROR_UNSUPPORTED_SIZE)
ZE_ERRCASE(ZE_RESULT_ERROR_UNSUPPORTED_ALIGNMENT)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_SYNCHRONIZATION_OBJECT)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_ENUMERATION)
ZE_ERRCASE(ZE_RESULT_ERROR_UNSUPPORTED_ENUMERATION)
ZE_ERRCASE(ZE_RESULT_ERROR_UNSUPPORTED_IMAGE_FORMAT)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_NATIVE_BINARY)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_GLOBAL_NAME)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_KERNEL_NAME)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_FUNCTION_NAME)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_GROUP_SIZE_DIMENSION)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_GLOBAL_WIDTH_DIMENSION)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_KERNEL_ARGUMENT_INDEX)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_KERNEL_ARGUMENT_SIZE)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_KERNEL_ATTRIBUTE_VALUE)
ZE_ERRCASE(ZE_RESULT_ERROR_INVALID_COMMAND_LIST_TYPE)
ZE_ERRCASE(ZE_RESULT_ERROR_OVERLAPPING_REGIONS)
ZE_ERRCASE(ZE_RESULT_ERROR_UNKNOWN)
#undef ZE_ERRCASE
default:
assert("Unexpected Error code");
} // switch
}
ze_result_t ZeCall::doCall(ze_result_t ZeResult, const char *CallStr,
bool TraceError) {
zePrint("ZE ---> %s\n", CallStr);
if (ZeResult && TraceError) {
std::string ErrorString;
zeParseError(ZeResult, ErrorString);
zePrint("Error (%s) in %s\n", ErrorString.c_str(), CallStr);
}
return ZeResult;
}
#define PI_ASSERT(condition, error) \
if (!(condition)) \
return error;
// This helper function increments the reference counter of the Queue
// without guarding with a lock.
// It is the caller's responsibility to make sure the lock is acquired
// on the Queue that is passed in.
inline static void piQueueRetainNoLock(pi_queue Queue) { Queue->RefCount++; }
// This helper function creates a pi_event and associate a pi_queue.
// Note that the caller of this function must have acquired lock on the Queue
// that is passed in.
// \param Queue pi_queue to associate with a new event.
// \param Event a pointer to hold the newly created pi_event
// \param CommandType various command type determined by the caller
// \param ZeCommandList the handle to associate with the newly created event
inline static pi_result
createEventAndAssociateQueue(pi_queue Queue, pi_event *Event,
pi_command_type CommandType,
ze_command_list_handle_t ZeCommandList) {
pi_result Res = piEventCreate(Queue->Context, Event);
if (Res != PI_SUCCESS)
return Res;
(*Event)->Queue = Queue;
(*Event)->CommandType = CommandType;
(*Event)->ZeCommandList = ZeCommandList;
// We need to increment the reference counter here to avoid pi_queue
// being released before the associated pi_event is released because
// piEventRelease requires access to the associated pi_queue.
// In piEventRelease, the reference counter of the Queue is decremented
// to release it.
piQueueRetainNoLock(Queue);
return PI_SUCCESS;
}
pi_result _pi_device::initialize() {
uint32_t numQueueGroups = 0;
ZE_CALL(zeDeviceGetCommandQueueGroupProperties(ZeDevice, &numQueueGroups,
nullptr));
if (numQueueGroups == 0) {
return PI_ERROR_UNKNOWN;
}
std::vector<ze_command_queue_group_properties_t> queueProperties(
numQueueGroups);
ZE_CALL(zeDeviceGetCommandQueueGroupProperties(ZeDevice, &numQueueGroups,
queueProperties.data()));
int ComputeGroupIndex = -1;
for (uint32_t i = 0; i < numQueueGroups; i++) {
if (queueProperties[i].flags &
ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE) {
ComputeGroupIndex = i;
break;
}
}
// How is it possible that there are no "compute" capabilities?
if (ComputeGroupIndex < 0) {
return PI_ERROR_UNKNOWN;
}
this->ZeComputeQueueGroupIndex = ComputeGroupIndex;
// Cache device properties
ZeDeviceProperties = {};
ZE_CALL(zeDeviceGetProperties(ZeDevice, &ZeDeviceProperties));
ZeDeviceComputeProperties = {};
ZE_CALL(zeDeviceGetComputeProperties(ZeDevice, &ZeDeviceComputeProperties));
return PI_SUCCESS;
}
pi_result _pi_context::initialize() {
// Create the immediate command list to be used for initializations
// Created as synchronous so level-zero performs implicit synchronization and
// there is no need to query for completion in the plugin
ze_command_queue_desc_t ZeCommandQueueDesc = {};
ZeCommandQueueDesc.ordinal = Devices[0]->ZeComputeQueueGroupIndex;
ZeCommandQueueDesc.index = 0;
ZeCommandQueueDesc.mode = ZE_COMMAND_QUEUE_MODE_SYNCHRONOUS;
ZE_CALL(zeCommandListCreateImmediate(ZeContext, Devices[0]->ZeDevice,
&ZeCommandQueueDesc,
&ZeCommandListInit));
return PI_SUCCESS;
}
pi_result _pi_context::finalize() {
// This function is called when pi_context is deallocated, piContextRelase.
// There could be some memory that may have not been deallocated.
// For example, zeEventPool could be still alive.
std::lock_guard<std::mutex> NumEventsLiveInEventPoolGuard(
NumEventsLiveInEventPoolMutex);
if (ZeEventPool && NumEventsLiveInEventPool[ZeEventPool])
ZE_CALL(zeEventPoolDestroy(ZeEventPool));
// Destroy the command list used for initializations
ZE_CALL(zeCommandListDestroy(ZeCommandListInit));
std::lock_guard<std::mutex> Lock(ZeCommandListCacheMutex);
for (ze_command_list_handle_t &ZeCommandList : ZeCommandListCache) {
if (ZeCommandList)
ZE_CALL(zeCommandListDestroy(ZeCommandList));
}
return PI_SUCCESS;
}
pi_result _pi_queue::resetCommandListFenceEntry(
_pi_queue::command_list_fence_map_t::value_type &MapEntry,
bool MakeAvailable) {
// Fence had been signalled meaning the associated command-list completed.
// Reset the fence and put the command list into a cache for reuse in PI
// calls.
ZE_CALL(zeFenceReset(MapEntry.second.ZeFence));
ZE_CALL(zeCommandListReset(MapEntry.first));
MapEntry.second.InUse = false;
if (MakeAvailable) {
std::lock_guard<std::mutex> lock(this->Context->ZeCommandListCacheMutex);
this->Context->ZeCommandListCache.push_back(MapEntry.first);
}
return PI_SUCCESS;
}
static const pi_uint32 ZeCommandListBatchSize = [] {
// Default value of 0. This specifies to use dynamic batch size adjustment.
pi_uint32 BatchSizeVal = 0;
const auto BatchSizeStr = std::getenv("SYCL_PI_LEVEL_ZERO_BATCH_SIZE");
if (BatchSizeStr) {
pi_int32 BatchSizeStrVal = std::atoi(BatchSizeStr);
// Level Zero may only support a limted number of commands per command
// list. The actual upper limit is not specified by the Level Zero
// Specification. For now we allow an arbitrary upper limit.
// Negative numbers will be silently ignored.
if (BatchSizeStrVal >= 0)
BatchSizeVal = BatchSizeStrVal;
}
return BatchSizeVal;
}();
// Retrieve an available command list to be used in a PI call
// Caller must hold a lock on the Queue passed in.
pi_result _pi_context::getAvailableCommandList(
pi_queue Queue, ze_command_list_handle_t *ZeCommandList,
ze_fence_handle_t *ZeFence, bool AllowBatching) {
// First see if there is an command-list open for batching commands
// for this queue.
if (Queue->ZeOpenCommandList) {
if (AllowBatching) {
*ZeCommandList = Queue->ZeOpenCommandList;
*ZeFence = Queue->ZeOpenCommandListFence;
return PI_SUCCESS;
}
// If this command isn't allowed to be batched, then we need to
// go ahead and execute what is already in the batched list,
// and then go on to process this. On exit from executeOpenCommandList
// ZeOpenCommandList will be nullptr.
if (auto Res = Queue->executeOpenCommandList())
return Res;
}
// Create/Reuse the command list, because in Level Zero commands are added to
// the command lists, and later are then added to the command queue.
// Each command list is paired with an associated fence to track when the
// command list is available for reuse.
_pi_result pi_result = PI_OUT_OF_RESOURCES;
ze_command_list_desc_t ZeCommandListDesc = {};
ZeCommandListDesc.stype = ZE_STRUCTURE_TYPE_COMMAND_LIST_DESC;
ze_fence_desc_t ZeFenceDesc = {};
ZeFenceDesc.stype = ZE_STRUCTURE_TYPE_FENCE_DESC;
// Initally, we need to check if a command list has already been created
// on this device that is available for use. If so, then reuse that
// Level-Zero Command List and Fence for this PI call.
{
// Make sure to acquire the lock before checking the size, or there
// will be a race condition.
std::lock_guard<std::mutex> lock(Queue->Context->ZeCommandListCacheMutex);
if (Queue->Context->ZeCommandListCache.size() > 0) {
*ZeCommandList = Queue->Context->ZeCommandListCache.front();
auto it = Queue->ZeCommandListFenceMap.find(*ZeCommandList);
if (it != Queue->ZeCommandListFenceMap.end()) {
*ZeFence = it->second.ZeFence;
it->second.InUse = true;
} else {
// If there is a command list available on this device, but no
// fence yet associated, then we must create a fence/list
// reference for this Queue. This can happen if two Queues reuse
// a device which did not have the resources freed.
ZE_CALL(zeFenceCreate(Queue->ZeCommandQueue, &ZeFenceDesc, ZeFence));
Queue->ZeCommandListFenceMap[*ZeCommandList] = {*ZeFence, true};
}
Queue->Context->ZeCommandListCache.pop_front();
return PI_SUCCESS;
}
}
// If there are no available command lists in the cache, then we check for
// command lists that have already signalled, but have not been added to the
// available list yet. Each command list has a fence associated which tracks
// if a command list has completed dispatch of its commands and is ready for
// reuse. If a command list is found to have been signalled, then the
// command list & fence are reset and we return.
for (auto &MapEntry : Queue->ZeCommandListFenceMap) {
ze_result_t ZeResult =
ZE_CALL_NOCHECK(zeFenceQueryStatus(MapEntry.second.ZeFence));
if (ZeResult == ZE_RESULT_SUCCESS) {
Queue->resetCommandListFenceEntry(MapEntry, false);
*ZeCommandList = MapEntry.first;
*ZeFence = MapEntry.second.ZeFence;
MapEntry.second.InUse = true;
return PI_SUCCESS;
}
}
// If there are no available command lists nor signalled command lists, then
// we must create another command list if we have not exceed the maximum
// command lists we can create.
// Once created, this command list & fence are added to the command list fence
// map.
if ((*ZeCommandList == nullptr) &&
(Queue->Device->Platform->ZeGlobalCommandListCount <
Queue->Device->Platform->ZeMaxCommandListCache)) {
ZE_CALL(zeCommandListCreate(Queue->Context->ZeContext,
Queue->Device->ZeDevice, &ZeCommandListDesc,
ZeCommandList));
// Increments the total number of command lists created on this platform.
Queue->Device->Platform->ZeGlobalCommandListCount++;
ZE_CALL(zeFenceCreate(Queue->ZeCommandQueue, &ZeFenceDesc, ZeFence));
Queue->ZeCommandListFenceMap.insert(
std::pair<ze_command_list_handle_t, _pi_queue::command_list_fence_t>(
*ZeCommandList, {*ZeFence, false}));
pi_result = PI_SUCCESS;
}
return pi_result;
}
void _pi_queue::adjustBatchSizeForFullBatch() {
// QueueBatchSize of 0 means never allow batching.
if (QueueBatchSize == 0 || !UseDynamicBatching)
return;
NumTimesClosedFull += 1;
// If the number of times the list has been closed early is low, and
// the number of times it has been closed full is high, then raise
// the batching size slowly. Don't raise it if it is already pretty
// high.
if (NumTimesClosedEarly <= 2 && NumTimesClosedFull > 10) {
if (QueueBatchSize < 16) {
QueueBatchSize = QueueBatchSize + 1;
zePrint("Raising QueueBatchSize to %d\n", QueueBatchSize);
}
NumTimesClosedEarly = 0;
NumTimesClosedFull = 0;
}
}
void _pi_queue::adjustBatchSizeForPartialBatch(pi_uint32 PartialBatchSize) {
// QueueBatchSize of 0 means never allow batching.
if (QueueBatchSize == 0 || !UseDynamicBatching)
return;
NumTimesClosedEarly += 1;
// If we are closing early more than about 3x the number of times
// it is closing full, lower the batch size to the value of the
// current open command list. This is trying to quickly get to a
// batch size that will be able to be closed full at least once
// in a while.
if (NumTimesClosedEarly > (NumTimesClosedFull + 1) * 3) {
QueueBatchSize = PartialBatchSize - 1;
if (QueueBatchSize < 1)
QueueBatchSize = 1;
zePrint("Lowering QueueBatchSize to %d\n", QueueBatchSize);
NumTimesClosedEarly = 0;
NumTimesClosedFull = 0;
}
}
pi_result _pi_queue::executeCommandList(ze_command_list_handle_t ZeCommandList,
ze_fence_handle_t ZeFence,
bool IsBlocking,
bool OKToBatchCommand) {
if (OKToBatchCommand && this->isBatchingAllowed()) {
if (this->ZeOpenCommandList != nullptr &&
this->ZeOpenCommandList != ZeCommandList)
die("executeCommandList: ZeOpenCommandList should be equal to"
"null or ZeCommandList");
if (this->ZeOpenCommandListSize + 1 < QueueBatchSize) {
this->ZeOpenCommandList = ZeCommandList;
this->ZeOpenCommandListFence = ZeFence;
// NOTE: we don't know here how many commands are in the ZeCommandList
// but most PI interfaces translate to a single Level-Zero command.
// Some do translate to multiple commands so we may be undercounting
// a bit here, but this is a heuristic, not an exact measure.
//
this->ZeOpenCommandListSize += 1;
return PI_SUCCESS;
}
adjustBatchSizeForFullBatch();
this->ZeOpenCommandList = nullptr;
this->ZeOpenCommandListFence = nullptr;
this->ZeOpenCommandListSize = 0;
}
// Close the command list and have it ready for dispatch.
ZE_CALL(zeCommandListClose(ZeCommandList));
// Offload command list to the GPU for asynchronous execution
ZE_CALL(zeCommandQueueExecuteCommandLists(ZeCommandQueue, 1, &ZeCommandList,
ZeFence));
// Check global control to make every command blocking for debugging.
if (IsBlocking || (ZeSerialize & ZeSerializeBlock) != 0) {
// Wait until command lists attached to the command queue are executed.
ZE_CALL(zeCommandQueueSynchronize(ZeCommandQueue, UINT32_MAX));
}
return PI_SUCCESS;
}
bool _pi_queue::isBatchingAllowed() {
return (this->QueueBatchSize > 0 && ((ZeSerialize & ZeSerializeBlock) == 0));
}
pi_result _pi_queue::executeOpenCommandList() {
// If there are any commands still in the open command list for this
// queue, then close and execute that command list now.
auto OpenList = this->ZeOpenCommandList;
if (OpenList) {
auto OpenListFence = this->ZeOpenCommandListFence;
adjustBatchSizeForPartialBatch(this->ZeOpenCommandListSize);
this->ZeOpenCommandList = nullptr;
this->ZeOpenCommandListFence = nullptr;
this->ZeOpenCommandListSize = 0;
return executeCommandList(OpenList, OpenListFence);
}
return PI_SUCCESS;
}
static const bool FilterEventWaitList = [] {
const char *Ret = std::getenv("SYCL_PI_LEVEL_ZERO_FILTER_EVENT_WAIT_LIST");
const bool RetVal = Ret ? std::stoi(Ret) : 1;
return RetVal;
}();
pi_result _pi_ze_event_list_t::createAndRetainPiZeEventList(
pi_uint32 EventListLength, const pi_event *EventList, pi_queue CurQueue) {
this->Length = 0;
this->ZeEventList = nullptr;
this->PiEventList = nullptr;
if (EventListLength > 0) {
try {
this->ZeEventList = new ze_event_handle_t[EventListLength];
this->PiEventList = new pi_event[EventListLength];
pi_uint32 TmpListLength = 0;
for (pi_uint32 I = 0; I < EventListLength; I++) {
auto ZeEvent = EventList[I]->ZeEvent;
if (FilterEventWaitList) {
auto Res = ZE_CALL_NOCHECK(zeEventQueryStatus(ZeEvent));
if (Res == ZE_RESULT_SUCCESS) {
// Event has already completed, don't put it into the list
continue;
}
}
auto Queue = EventList[I]->Queue;
if (Queue != CurQueue) {
// If the event that is going to be waited on is in a
// different queue, then any open command list in
// that queue must be closed and executed because
// the event being waited on could be for a command
// in the queue's batch.
// Lock automatically releases when this goes out of scope.
std::lock_guard<std::mutex> lock(Queue->PiQueueMutex);
if (auto Res = Queue->executeOpenCommandList())
return Res;
}
this->ZeEventList[TmpListLength] = ZeEvent;
this->PiEventList[TmpListLength] = EventList[I];
TmpListLength += 1;
}
this->Length = TmpListLength;
} catch (...) {
return PI_OUT_OF_HOST_MEMORY;
}
for (pi_uint32 I = 0; I < this->Length; I++) {
PI_CALL(piEventRetain(this->PiEventList[I]));
}
}
return PI_SUCCESS;
}
static void printZeEventList(const _pi_ze_event_list_t &PiZeEventList) {
zePrint(" NumEventsInWaitList %d:", PiZeEventList.Length);
for (pi_uint32 I = 0; I < PiZeEventList.Length; I++) {
zePrint(" %#lx", pi_cast<std::uintptr_t>(PiZeEventList.ZeEventList[I]));
}
zePrint("\n");
}
pi_result _pi_ze_event_list_t::collectEventsForReleaseAndDestroyPiZeEventList(
std::list<pi_event> &EventsToBeReleased) {
// acquire a lock before reading the length and list fields.
// Acquire the lock, copy the needed data locally, and reset
// the fields, then release the lock.
// Only then do we do the actual actions to release and destroy,
// holding the lock for the minimum time necessary.
pi_uint32 LocLength = 0;
ze_event_handle_t *LocZeEventList = nullptr;
pi_event *LocPiEventList = nullptr;
{
// acquire the lock and copy fields locally
// Lock automatically releases when this goes out of scope.
std::lock_guard<std::mutex> lock(this->PiZeEventListMutex);
LocLength = Length;
LocZeEventList = ZeEventList;
LocPiEventList = PiEventList;
Length = 0;
ZeEventList = nullptr;
PiEventList = nullptr;
// release lock by ending scope.
}
for (pi_uint32 I = 0; I < LocLength; I++) {
// Add the event to be released to the list
EventsToBeReleased.push_back(LocPiEventList[I]);
}
if (LocZeEventList != nullptr) {
delete[] LocZeEventList;
}
if (LocPiEventList != nullptr) {
delete[] LocPiEventList;
}
return PI_SUCCESS;
}
extern "C" {
// Forward declarations
decltype(piEventCreate) piEventCreate;
static pi_result compileOrBuild(pi_program Program, pi_uint32 NumDevices,
const pi_device *DeviceList,
const char *Options);
static pi_result copyModule(ze_context_handle_t ZeContext,
ze_device_handle_t ZeDevice,
ze_module_handle_t SrcMod,
ze_module_handle_t *DestMod);
static bool setEnvVar(const char *var, const char *value);
static pi_result populateDeviceCacheIfNeeded(pi_platform Platform);
// Forward declarations for mock implementations of Level Zero APIs that
// do not yet work in the driver.
// TODO: Remove these mock definitions when they work in the driver.
static ze_result_t
zeModuleDynamicLinkMock(uint32_t numModules, ze_module_handle_t *phModules,
ze_module_build_log_handle_t *phLinkLog);
static ze_result_t
zeModuleGetPropertiesMock(ze_module_handle_t hModule,
ze_module_properties_t *pModuleProperties);
static bool isOnlineLinkEnabled();
// End forward declarations for mock Level Zero APIs
// This function will ensure compatibility with both Linux and Windowns for
// setting environment variables.
static bool setEnvVar(const char *name, const char *value) {
#ifdef _WIN32
int Res = _putenv_s(name, value);
#else
int Res = setenv(name, value, 1);
#endif
if (Res != 0) {
zePrint(
"Level Zero plugin was unable to set the environment variable: %s\n",
name);
return false;
}
return true;
}
pi_result piPlatformsGet(pi_uint32 NumEntries, pi_platform *Platforms,
pi_uint32 *NumPlatforms) {
static const char *PiTrace = std::getenv("SYCL_PI_TRACE");
static const int PiTraceValue = PiTrace ? std::stoi(PiTrace) : 0;
if (PiTraceValue == -1) { // Means print all PI traces
PrintPiTrace = true;
}
static const char *DebugMode = std::getenv("ZE_DEBUG");
static const int DebugModeValue = DebugMode ? std::stoi(DebugMode) : 0;
if (DebugModeValue == ZE_DEBUG_ALL) {
ZeDebug = true;
ZeValidationLayer = true;
} else {
if (DebugModeValue & ZE_DEBUG_BASIC)
ZeDebug = true;
if (DebugModeValue & ZE_DEBUG_VALIDATION)
ZeValidationLayer = true;
}
if (NumEntries == 0 && Platforms != nullptr) {
return PI_INVALID_VALUE;
}
if (Platforms == nullptr && NumPlatforms == nullptr) {
return PI_INVALID_VALUE;
}
// Setting these environment variables before running zeInit will enable the
// validation layer in the Level Zero loader.
if (ZeValidationLayer) {
setEnvVar("ZE_ENABLE_VALIDATION_LAYER", "1");
setEnvVar("ZE_ENABLE_PARAMETER_VALIDATION", "1");
}
// Enable SYSMAN support for obtaining the PCI address
// and maximum memory bandwidth.
if (getenv("SYCL_ENABLE_PCI") != nullptr) {
setEnvVar("ZES_ENABLE_SYSMAN", "1");
}
// TODO: We can still safely recover if something goes wrong during the init.
// Implement handling segfault using sigaction.
// We must only initialize the driver once, even if piPlatformsGet() is called
// multiple times. Declaring the return value as "static" ensures it's only
// called once.
static ze_result_t ZeResult = ZE_CALL_NOCHECK(zeInit(ZE_INIT_FLAG_GPU_ONLY));
// Absorb the ZE_RESULT_ERROR_UNINITIALIZED and just return 0 Platforms.
if (ZeResult == ZE_RESULT_ERROR_UNINITIALIZED) {
PI_ASSERT(NumPlatforms != 0, PI_INVALID_VALUE);
*NumPlatforms = 0;
return PI_SUCCESS;
}
if (ZeResult != ZE_RESULT_SUCCESS) {
zePrint("zeInit: Level Zero initialization failure\n");
return mapError(ZeResult);
}
// Cache pi_platforms for reuse in the future
// It solves two problems;
// 1. sycl::platform equality issue; we always return the same pi_platform.
// 2. performance; we can save time by immediately return from cache.
//
const std::lock_guard<sycl::detail::SpinLock> Lock{*PiPlatformsCacheMutex};
if (!PiPlatformCachePopulated) {