-
Notifications
You must be signed in to change notification settings - Fork 827
Expand file tree
/
Copy pathpi_level_zero.cpp
More file actions
7411 lines (6422 loc) · 275 KB
/
pi_level_zero.cpp
File metadata and controls
7411 lines (6422 loc) · 275 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 <set>
#include <sstream>
#include <string>
#include <thread>
#include <utility>
#include <level_zero/zet_api.h>
#include "usm_allocator.hpp"
extern "C" {
// Forward declarartions.
static pi_result EventRelease(pi_event Event, pi_queue LockedQueue);
static pi_result QueueRelease(pi_queue Queue, pi_queue LockedQueue);
}
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 is an experimental option to test performance of device to device copy
// operations on copy engines (versus compute engine)
static const bool UseCopyEngineForD2DCopy = [] {
const char *CopyEngineForD2DCopy =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_COPY_ENGINE_FOR_D2D_COPY");
return (CopyEngineForD2DCopy && (std::stoi(CopyEngineForD2DCopy) != 0));
}();
// This is an experimental option that allows the use of copy engine, if
// available in the device, in Level Zero plugin for copy operations submitted
// to an in-order queue. The default is 1.
static const bool UseCopyEngineForInOrderQueue = [] {
const char *CopyEngineForInOrderQueue =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_COPY_ENGINE_FOR_IN_ORDER_QUEUE");
return (!CopyEngineForInOrderQueue ||
(std::stoi(CopyEngineForInOrderQueue) != 0));
}();
// 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 *ZeName,
const char *ZeArgs, bool TraceError = true);
};
std::mutex ZeCall::GlobalLock;
// Controls PI level tracing prints.
static bool PrintPiTrace = false;
// Controls support of the indirect access kernels and deferred memory release.
static const bool IndirectAccessTrackingEnabled = [] {
return std::getenv("SYCL_PI_LEVEL_ZERO_TRACK_INDIRECT_ACCESS_MEMORY") !=
nullptr;
}();
// 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;
}
// This will count the calls to Level-Zero
static std::map<const char *, int> *ZeCallCount = nullptr;
// Trace a call to Level-Zero RT
#define ZE_CALL(ZeName, ZeArgs) \
{ \
ze_result_t ZeResult = ZeName ZeArgs; \
if (auto Result = ZeCall().doCall(ZeResult, #ZeName, #ZeArgs, true)) \
return mapError(Result); \
}
#define ZE_CALL_NOCHECK(ZeName, ZeArgs) \
ZeCall().doCall(ZeName ZeArgs, #ZeName, #ZeArgs, 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; \
}
enum DebugLevel {
ZE_DEBUG_NONE = 0x0,
ZE_DEBUG_BASIC = 0x1,
ZE_DEBUG_VALIDATION = 0x2,
ZE_DEBUG_CALL_COUNT = 0x4,
ZE_DEBUG_ALL = -1
};
// Controls Level Zero calls tracing.
static const int ZeDebug = [] {
const char *DebugMode = std::getenv("ZE_DEBUG");
return DebugMode ? std::atoi(DebugMode) : ZE_DEBUG_NONE;
}();
static void zePrint(const char *Format, ...) {
if (ZeDebug & ZE_DEBUG_BASIC) {
va_list Args;
va_start(Args, Format);
vfprintf(stderr, Format, Args);
va_end(Args);
}
}
// Controls whether device-scope events are used.
static const bool ZeAllHostVisibleEvents = [] {
const auto DeviceEventsStr =
std::getenv("SYCL_PI_LEVEL_ZERO_DEVICE_SCOPE_EVENTS");
bool result = (DeviceEventsStr ? (std::atoi(DeviceEventsStr) == 0) : true);
return result;
}();
// 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");
pi_uint32 Result =
MaxNumEventsPerPoolEnv ? std::atoi(MaxNumEventsPerPoolEnv) : 256;
if (Result <= 0)
Result = 256;
return Result;
}();
// Helper function to implement zeHostSynchronize.
// The behavior is to avoid infinite wait during host sync under ZE_DEBUG.
// This allows for a much more responsive debugging of hangs.
//
template <typename T, typename Func>
ze_result_t zeHostSynchronizeImpl(Func Api, T Handle) {
if (!ZeDebug) {
return Api(Handle, UINT64_MAX);
}
ze_result_t R;
while ((R = Api(Handle, 1000)) == ZE_RESULT_NOT_READY)
;
return R;
}
// Template function to do various types of host synchronizations.
// This is intended to be used instead of direct calls to specific
// Level-Zero synchronization APIs.
//
template <typename T> ze_result_t zeHostSynchronize(T Handle);
template <> ze_result_t zeHostSynchronize(ze_event_handle_t Handle) {
return zeHostSynchronizeImpl(zeEventHostSynchronize, Handle);
}
template <> ze_result_t zeHostSynchronize(ze_command_queue_handle_t Handle) {
return zeHostSynchronizeImpl(zeCommandQueueSynchronize, Handle);
}
template <> ze_result_t zeHostSynchronize(ze_fence_handle_t Handle) {
return zeHostSynchronizeImpl(zeFenceHostSynchronize, Handle);
}
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
// SYCL_PI_LEVEL_ZERO_USE_COPY_ENGINE can be set to an integer value, or
// a pair of integer values of the form "lower_index:upper_index".
// Here, the indices point to copy engines in a list of all available copy
// engines.
// This functions returns this pair of indices.
// If the user specifies only a single integer, a value of 0 indicates that
// the copy engines will not be used at all. A value of 1 indicates that all
// available copy engines can be used.
static const std::pair<int, int> getRangeOfAllowedCopyEngines = [] {
const char *EnvVar = std::getenv("SYCL_PI_LEVEL_ZERO_USE_COPY_ENGINE");
// If the environment variable is not set, all available copy engines can be
// used.
if (!EnvVar)
return std::pair<int, int>(0, INT_MAX);
std::string CopyEngineRange = EnvVar;
// Environment variable can be a single integer or a pair of integers
// separated by ":"
auto pos = CopyEngineRange.find(":");
if (pos == std::string::npos) {
bool UseCopyEngine = (std::stoi(CopyEngineRange) != 0);
if (UseCopyEngine)
return std::pair<int, int>(0, INT_MAX); // All copy engines can be used.
return std::pair<int, int>(-1, -1); // No copy engines will be used.
}
int LowerCopyEngineIndex = std::stoi(CopyEngineRange.substr(0, pos));
int UpperCopyEngineIndex = std::stoi(CopyEngineRange.substr(pos + 1));
if ((LowerCopyEngineIndex > UpperCopyEngineIndex) ||
(LowerCopyEngineIndex < -1) || (UpperCopyEngineIndex < -1)) {
zePrint("SYCL_PI_LEVEL_ZERO_USE_COPY_ENGINE: invalid value provided, "
"default set.\n");
LowerCopyEngineIndex = 0;
UpperCopyEngineIndex = INT_MAX;
}
return std::pair<int, int>(LowerCopyEngineIndex, UpperCopyEngineIndex);
}();
static const bool CopyEngineRequested = [] {
int LowerCopyQueueIndex = getRangeOfAllowedCopyEngines.first;
int UpperCopyQueueIndex = getRangeOfAllowedCopyEngines.second;
return ((LowerCopyQueueIndex != -1) || (UpperCopyQueueIndex != -1));
}();
// 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;
// Keeps track if the global offset extension is found
static bool PiDriverGlobalOffsetExtensionFound = 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 &Pool,
size_t &Index, bool HostVisible) {
// Lock while updating event pool machinery.
std::lock_guard<std::mutex> Lock(ZeEventPoolCacheMutex);
// Setup for host-visible pool as needed.
ze_event_pool_flag_t ZePoolFlag = {};
std::list<ze_event_pool_handle_t> *ZePoolCache;
if (ZeAllHostVisibleEvents) {
ZePoolFlag = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
ZePoolCache = &ZeEventPoolCache;
} else if (HostVisible) {
ZePoolFlag = ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
ZePoolCache = &ZeHostVisibleEventPoolCache;
} else {
ZePoolCache = &ZeEventPoolCache;
}
// Remove full pool from the cache.
if (!ZePoolCache->empty()) {
if (NumEventsAvailableInEventPool[ZePoolCache->front()] == 0) {
ZePoolCache->erase(ZePoolCache->begin());
}
}
if (ZePoolCache->empty()) {
ZePoolCache->push_back(nullptr);
}
// We shall be adding an event to the front pool.
ze_event_pool_handle_t *ZePool = &ZePoolCache->front();
Index = 0;
// Create one event ZePool per MaxNumEventsPerPool events
if (*ZePool == nullptr) {
ZeStruct<ze_event_pool_desc_t> ZeEventPoolDesc;
ZeEventPoolDesc.count = MaxNumEventsPerPool;
ZeEventPoolDesc.flags = ZePoolFlag | 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], ZePool));
NumEventsAvailableInEventPool[*ZePool] = MaxNumEventsPerPool - 1;
NumEventsUnreleasedInEventPool[*ZePool] = 1;
} else {
Index = MaxNumEventsPerPool - NumEventsAvailableInEventPool[*ZePool];
--NumEventsAvailableInEventPool[*ZePool];
++NumEventsUnreleasedInEventPool[*ZePool];
}
Pool = *ZePool;
return PI_SUCCESS;
}
pi_result _pi_context::decrementUnreleasedEventsInPool(pi_event Event) {
if (!Event->ZeEventPool) {
// This must be an interop event created on a users's pool.
// Do nothing.
return PI_SUCCESS;
}
// Put the empty pool to the cache of the pools.
std::lock_guard<std::mutex> Lock(ZeEventPoolCacheMutex);
if (NumEventsUnreleasedInEventPool[Event->ZeEventPool] == 0)
die("Invalid event release: event pool doesn't have unreleased events");
if (--NumEventsUnreleasedInEventPool[Event->ZeEventPool] == 0) {
if (ZeEventPoolCache.front() != Event->ZeEventPool) {
ZeEventPoolCache.push_back(Event->ZeEventPool);
}
NumEventsAvailableInEventPool[Event->ZeEventPool] = MaxNumEventsPerPool;
}
if (Event->ZeHostVisibleEventPool) {
if (NumEventsUnreleasedInEventPool[Event->ZeEventPool] == 0)
die("Invalid host visible event release: host visible event pool doesn't "
"have unreleased events");
if (--NumEventsUnreleasedInEventPool[Event->ZeHostVisibleEventPool] == 0) {
if (ZeHostVisibleEventPoolCache.front() !=
Event->ZeHostVisibleEventPool) {
ZeHostVisibleEventPoolCache.push_back(Event->ZeHostVisibleEventPool);
}
NumEventsAvailableInEventPool[Event->ZeHostVisibleEventPool] =
MaxNumEventsPerPool;
}
}
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,
bool PreferCopyEngine = false);
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,
bool PreferCopyEngine = false);
inline void zeParseError(ze_result_t ZeError, const char *&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(false && "Unexpected Error code");
} // switch
}
ze_result_t ZeCall::doCall(ze_result_t ZeResult, const char *ZeName,
const char *ZeArgs, bool TraceError) {
zePrint("ZE ---> %s%s\n", ZeName, ZeArgs);
if (ZeDebug & ZE_DEBUG_CALL_COUNT) {
++(*ZeCallCount)[ZeName];
}
if (ZeResult && TraceError) {
const char *ErrorString = "Unknown";
zeParseError(ZeResult, ErrorString);
zePrint("Error (%s) in %s\n", ErrorString, ZeName);
}
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 CommandList is the command list where the event is added
inline static pi_result
createEventAndAssociateQueue(pi_queue Queue, pi_event *Event,
pi_command_type CommandType,
pi_command_list_ptr_t CommandList) {
pi_result Res = piEventCreate(Queue->Context, Event);
if (Res != PI_SUCCESS)
return Res;
(*Event)->Queue = Queue;
(*Event)->CommandType = CommandType;
// Append this Event to the CommandList, if any
if (CommandList != Queue->CommandListMap.end()) {
(*Event)->ZeCommandList = CommandList->first;
CommandList->second.append(*Event);
PI_CALL(piEventRetain(*Event));
} else {
(*Event)->ZeCommandList = nullptr;
}
// 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);
// SYCL RT does not track completion of the events, so it could
// release a PI event as soon as that's not being waited in the app.
// But we have to ensure that the event is not destroyed before
// it is really signalled, so retain it explicitly here and
// release in Event->cleanup().
//
PI_CALL(piEventRetain(*Event));
return PI_SUCCESS;
}
pi_result _pi_device::initialize(int SubSubDeviceOrdinal,
int SubSubDeviceIndex) {
uint32_t numQueueGroups = 0;
ZE_CALL(zeDeviceGetCommandQueueGroupProperties,
(ZeDevice, &numQueueGroups, nullptr));
if (numQueueGroups == 0) {
return PI_ERROR_UNKNOWN;
}
zePrint("NOTE: Number of queue groups = %d\n", numQueueGroups);
std::vector<ZeStruct<ze_command_queue_group_properties_t>>
QueueGroupProperties(numQueueGroups);
ZE_CALL(zeDeviceGetCommandQueueGroupProperties,
(ZeDevice, &numQueueGroups, QueueGroupProperties.data()));
int ComputeGroupIndex = -1;
// Initialize a sub-sub-device with its own ordinal and index
if (SubSubDeviceOrdinal >= 0) {
ComputeGroupIndex = SubSubDeviceOrdinal;
ZeComputeEngineIndex = SubSubDeviceIndex;
} else { // This is a root or a sub-device
for (uint32_t i = 0; i < numQueueGroups; i++) {
if (QueueGroupProperties[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;
}
// The index for a root or a sub-device is always 0.
ZeComputeEngineIndex = 0;
int MainCopyGroupIndex = -1;
int LinkCopyGroupIndex = -1;
if (CopyEngineRequested) {
for (uint32_t i = 0; i < numQueueGroups; i++) {
if (((QueueGroupProperties[i].flags &
ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE) == 0) &&
(QueueGroupProperties[i].flags &
ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COPY)) {
if (QueueGroupProperties[i].numQueues == 1)
MainCopyGroupIndex = i;
else {
LinkCopyGroupIndex = i;
break;
}
}
}
if (MainCopyGroupIndex < 0)
zePrint("NOTE: main blitter/copy engine is not available\n");
else
zePrint("NOTE: main blitter/copy engine is available\n");
if (LinkCopyGroupIndex < 0)
zePrint("NOTE: link blitter/copy engines are not available\n");
else
zePrint("NOTE: link blitter/copy engines are available\n");
}
ZeMainCopyQueueGroupIndex = MainCopyGroupIndex;
if (MainCopyGroupIndex >= 0) {
ZeMainCopyQueueGroupProperties = QueueGroupProperties[MainCopyGroupIndex];
}
ZeLinkCopyQueueGroupIndex = LinkCopyGroupIndex;
if (LinkCopyGroupIndex >= 0) {
ZeLinkCopyQueueGroupProperties = QueueGroupProperties[LinkCopyGroupIndex];
}
}
ZeComputeQueueGroupIndex = ComputeGroupIndex;
ZeComputeQueueGroupProperties = QueueGroupProperties[ComputeGroupIndex];
// Maintain various device properties cache.
// Note that we just describe here how to compute the data.
// The real initialization is upon first access.
//
auto ZeDevice = this->ZeDevice;
ZeDeviceProperties.Compute = [ZeDevice](ze_device_properties_t &Properties) {
ZE_CALL_NOCHECK(zeDeviceGetProperties, (ZeDevice, &Properties));
};
ZeDeviceComputeProperties.Compute =
[ZeDevice](ze_device_compute_properties_t &Properties) {
ZE_CALL_NOCHECK(zeDeviceGetComputeProperties, (ZeDevice, &Properties));
};
ZeDeviceImageProperties.Compute =
[ZeDevice](ze_device_image_properties_t &Properties) {
ZE_CALL_NOCHECK(zeDeviceGetImageProperties, (ZeDevice, &Properties));
};
ZeDeviceModuleProperties.Compute =
[ZeDevice](ze_device_module_properties_t &Properties) {
ZE_CALL_NOCHECK(zeDeviceGetModuleProperties, (ZeDevice, &Properties));
};
ZeDeviceMemoryProperties.Compute =
[ZeDevice](
std::vector<ZeStruct<ze_device_memory_properties_t>> &Properties) {
uint32_t Count = 0;
ZE_CALL_NOCHECK(zeDeviceGetMemoryProperties,
(ZeDevice, &Count, nullptr));
Properties.resize(Count);
ZE_CALL_NOCHECK(zeDeviceGetMemoryProperties,
(ZeDevice, &Count, Properties.data()));
};
ZeDeviceCacheProperties.Compute =
[ZeDevice](ze_device_cache_properties_t &Properties) {
// TODO: Since v1.0 there can be multiple cache properties.
// For now remember the first one, if any.
uint32_t Count = 0;
ZE_CALL_NOCHECK(zeDeviceGetCacheProperties,
(ZeDevice, &Count, nullptr));
if (Count > 0)
Count = 1;
ZE_CALL_NOCHECK(zeDeviceGetCacheProperties,
(ZeDevice, &Count, &Properties));
};
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
//
// TODO: get rid of using Devices[0] for the context with multiple
// root-devices. We should somehow make the data initialized on all devices.
pi_device Device = SingleRootDevice ? SingleRootDevice : Devices[0];
ZeStruct<ze_command_queue_desc_t> ZeCommandQueueDesc;
ZeCommandQueueDesc.ordinal = Device->ZeComputeQueueGroupIndex;
ZeCommandQueueDesc.index = Device->ZeComputeEngineIndex;
ZeCommandQueueDesc.mode = ZE_COMMAND_QUEUE_MODE_SYNCHRONOUS;
ZE_CALL(
zeCommandListCreateImmediate,
(ZeContext, Device->ZeDevice, &ZeCommandQueueDesc, &ZeCommandListInit));
return PI_SUCCESS;
}
pi_result _pi_context::finalize() {
// This function is called when pi_context is deallocated, piContextRelease.
// There could be some memory that may have not been deallocated.
// For example, event pool caches would be still alive.
{
std::lock_guard<std::mutex> Lock(ZeEventPoolCacheMutex);
for (auto &ZePool : ZeEventPoolCache)
ZE_CALL(zeEventPoolDestroy, (ZePool));
for (auto &ZePool : ZeHostVisibleEventPoolCache)
ZE_CALL(zeEventPoolDestroy, (ZePool));
ZeEventPoolCache.clear();
ZeHostVisibleEventPoolCache.clear();
}
// 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 : ZeComputeCommandListCache) {
if (ZeCommandList)
ZE_CALL(zeCommandListDestroy, (ZeCommandList));
}
for (ze_command_list_handle_t &ZeCommandList : ZeCopyCommandListCache) {
if (ZeCommandList)
ZE_CALL(zeCommandListDestroy, (ZeCommandList));
}
// Adjust the number of command lists created on this platform.
auto Platform = Devices[0]->Platform;
Platform->ZeGlobalCommandListCount -= ZeComputeCommandListCache.size();
Platform->ZeGlobalCommandListCount -= ZeCopyCommandListCache.size();
return PI_SUCCESS;
}
bool _pi_queue::isInOrderQueue() const {
// If out-of-order queue property is not set, then this is a in-order queue.
return ((this->PiQueueProperties & PI_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) ==
0);
}
pi_result _pi_queue::resetCommandList(pi_command_list_ptr_t CommandList,
bool MakeAvailable) {
bool UseCopyEngine = CommandList->second.isCopy();
auto &ZeCommandListCache = (UseCopyEngine)
? this->Context->ZeCopyCommandListCache
: this->Context->ZeComputeCommandListCache;
// 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, (CommandList->second.ZeFence));
ZE_CALL(zeCommandListReset, (CommandList->first));
CommandList->second.InUse = false;
// Finally release/cleanup all the events in this command list.
// Note, we don't need to synchronize the events since the fence
// synchronized above already does that.
auto &EventList = CommandList->second.EventList;
for (auto &Event : EventList) {
if (!Event->CleanedUp) {
Event->cleanup(this);
}
Event->ZeCommandList = nullptr;
PI_CALL(EventRelease(Event, this));
}
EventList.clear();
if (MakeAvailable) {
std::lock_guard<std::mutex> lock(this->Context->ZeCommandListCacheMutex);
ZeCommandListCache.push_back(CommandList->first);
}
return PI_SUCCESS;
}
// Maximum Number of Command Lists that can be created.
// This Value is initialized to 20000, but can be changed by the user
// thru the environment variable SYCL_PI_LEVEL_ZERO_MAX_COMMAND_LIST_CACHE
// ie SYCL_PI_LEVEL_ZERO_MAX_COMMAND_LIST_CACHE =10000.
static const int ZeMaxCommandListCacheSize = [] {
const char *CommandListCacheSize =
std::getenv("SYCL_PI_LEVEL_ZERO_MAX_COMMAND_LIST_CACHE");
pi_uint32 CommandListCacheSizeValue;
try {
CommandListCacheSizeValue =
CommandListCacheSize ? std::stoi(CommandListCacheSize) : 20000;
} catch (std::exception const &) {
zePrint(
"SYCL_PI_LEVEL_ZERO_MAX_COMMAND_LIST_CACHE: invalid value provided, "
"default set.\n");
CommandListCacheSizeValue = 20000;
}
return CommandListCacheSizeValue;
}();
// Configuration of the command-list batching.
typedef struct CommandListBatchConfig {
// Default value of 0. This specifies to use dynamic batch size adjustment.
// Other values will try to collect specified amount of commands.
pi_uint32 Size{0};
// If doing dynamic batching, specifies start batch size.
pi_uint32 DynamicSizeStart{4};
// The maximum size for dynamic batch.
pi_uint32 DynamicSizeMax{64};
// The step size for dynamic batch increases.
pi_uint32 DynamicSizeStep{1};
// Thresholds for when increase batch size (number of closed early is small
// and number of closed full is high).
pi_uint32 NumTimesClosedEarlyThreshold{2};
pi_uint32 NumTimesClosedFullThreshold{10};
// Tells the starting size of a batch.
pi_uint32 startSize() const { return Size > 0 ? Size : DynamicSizeStart; }
// Tells is we are doing dynamic batch size adjustment.
bool dynamic() const { return Size == 0; }
} zeCommandListBatchConfig;
static const zeCommandListBatchConfig ZeCommandListBatch = [] {
zeCommandListBatchConfig Config{}; // default initialize
// Default value of 0. This specifies to use dynamic batch size adjustment.
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.
if (BatchSizeStrVal > 0) {
Config.Size = BatchSizeStrVal;
} else if (BatchSizeStrVal == 0) {
Config.Size = 0;
// We are requested to do dynamic batching. Collect specifics, if any.
// The extended format supported is ":" separated values.
//
// NOTE: these extra settings are experimental and are intended to
// be used only for finding a better default heuristic.
//
std::string BatchConfig(BatchSizeStr);
size_t Ord = 0;
size_t Pos = 0;
while (true) {
if (++Ord > 5)
break;
Pos = BatchConfig.find(":", Pos);
if (Pos == std::string::npos)
break;
++Pos; // past the ":"
pi_uint32 Val;
try {
Val = std::stoi(BatchConfig.substr(Pos));
} catch (...) {
zePrint("SYCL_PI_LEVEL_ZERO_BATCH_SIZE: failed to parse value\n");
break;
}
switch (Ord) {
case 1:
Config.DynamicSizeStart = Val;
break;
case 2:
Config.DynamicSizeMax = Val;
break;
case 3:
Config.DynamicSizeStep = Val;
break;
case 4:
Config.NumTimesClosedEarlyThreshold = Val;
break;
case 5:
Config.NumTimesClosedFullThreshold = Val;
break;
default:
die("Unexpected batch config");
}
zePrint("SYCL_PI_LEVEL_ZERO_BATCH_SIZE: dynamic batch param #%d: %d\n",
(int)Ord, (int)Val);
};
} else {
// Negative batch sizes are silently ignored.
zePrint("SYCL_PI_LEVEL_ZERO_BATCH_SIZE: ignored negative value\n");
}
}
return Config;
}();
// 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, pi_command_list_ptr_t &CommandList, bool PreferCopyEngine,
bool AllowBatching) {
// First see if there is an command-list open for batching commands
// for this queue.
if (Queue->hasOpenCommandList()) {
// TODO: Batching of copy commands will be supported.
if (AllowBatching && !PreferCopyEngine) {
CommandList = Queue->OpenCommandList;
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
// OpenCommandList will be invalidated.
if (auto Res = Queue->executeOpenCommandList())
return Res;
}
bool UseCopyEngine =
(!(Queue->isInOrderQueue()) || UseCopyEngineForInOrderQueue) &&
PreferCopyEngine && Queue->Device->hasCopyEngine();
// 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.