-
Notifications
You must be signed in to change notification settings - Fork 829
Expand file tree
/
Copy pathpi_level_zero.cpp
More file actions
executable file
·8663 lines (7544 loc) · 328 KB
/
pi_level_zero.cpp
File metadata and controls
executable file
·8663 lines (7544 loc) · 328 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 piQueueReleaseInternal(pi_queue Queue);
static pi_result EventCreate(pi_context Context, pi_queue Queue,
bool HostVisible, pi_event *RetEvent);
}
// Defined in tracing.cpp
void enableZeTracing();
void disableZeTracing();
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));
}();
// To enable an experimental feature that uses immediate commandlists
// for kernel launches and copies. The default is standard commandlists.
// Setting a value >=1 specifies use of immediate commandlists.
// Note: when immediate commandlists are used then device-only events
// must be either AllHostVisible or OnDemandHostVisibleProxy.
// (See env var SYCL_PI_LEVEL_ZERO_DEVICE_SCOPE_EVENTS).
static const bool UseImmediateCommandLists = [] {
const char *ImmediateFlag =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_IMMEDIATE_COMMANDLISTS");
if (!ImmediateFlag)
return false;
return std::stoi(ImmediateFlag) > 0;
}();
// This is an experimental option that allows the use of multiple command lists
// when submitting barriers. The default is 0.
static const bool UseMultipleCmdlistBarriers = [] {
const char *UseMultipleCmdlistBarriersFlag =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_MULTIPLE_COMMANDLIST_BARRIERS");
if (!UseMultipleCmdlistBarriersFlag)
return false;
return std::stoi(UseMultipleCmdlistBarriersFlag) > 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_ERROR_DEVICE_NOT_FOUND},
{ZE_RESULT_ERROR_INSUFFICIENT_PERMISSIONS, PI_ERROR_INVALID_OPERATION},
{ZE_RESULT_ERROR_NOT_AVAILABLE, PI_ERROR_INVALID_OPERATION},
{ZE_RESULT_ERROR_UNINITIALIZED, PI_ERROR_INVALID_PLATFORM},
{ZE_RESULT_ERROR_INVALID_ARGUMENT, PI_ERROR_INVALID_ARG_VALUE},
{ZE_RESULT_ERROR_INVALID_NULL_POINTER, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_SIZE, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_SIZE, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_ALIGNMENT, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_SYNCHRONIZATION_OBJECT, PI_ERROR_INVALID_EVENT},
{ZE_RESULT_ERROR_INVALID_ENUMERATION, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_ENUMERATION, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_UNSUPPORTED_IMAGE_FORMAT, PI_ERROR_INVALID_VALUE},
{ZE_RESULT_ERROR_INVALID_NATIVE_BINARY, PI_ERROR_INVALID_BINARY},
{ZE_RESULT_ERROR_INVALID_KERNEL_NAME, PI_ERROR_INVALID_KERNEL_NAME},
{ZE_RESULT_ERROR_INVALID_FUNCTION_NAME, PI_ERROR_BUILD_PROGRAM_FAILURE},
{ZE_RESULT_ERROR_OVERLAPPING_REGIONS, PI_ERROR_INVALID_OPERATION},
{ZE_RESULT_ERROR_INVALID_GROUP_SIZE_DIMENSION,
PI_ERROR_INVALID_WORK_GROUP_SIZE},
{ZE_RESULT_ERROR_MODULE_BUILD_FAILURE, PI_ERROR_BUILD_PROGRAM_FAILURE},
{ZE_RESULT_ERROR_OUT_OF_DEVICE_MEMORY, PI_ERROR_OUT_OF_RESOURCES},
{ZE_RESULT_ERROR_OUT_OF_HOST_MEMORY, PI_ERROR_OUT_OF_HOST_MEMORY}};
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, and how.
static const enum EventsScope {
// All events are created host-visible.
AllHostVisible,
// All events are created with device-scope and only when
// host waits them or queries their status that a proxy
// host-visible event is created and set to signal after
// original event signals.
OnDemandHostVisibleProxy,
// All events are created with device-scope and only
// when a batch of commands is submitted for execution a
// last command in that batch is added to signal host-visible
// completion of each command in this batch (the default mode).
LastCommandInBatchHostVisible
} EventsScope = [] {
const auto DeviceEventsStr =
std::getenv("SYCL_PI_LEVEL_ZERO_DEVICE_SCOPE_EVENTS");
auto Default = LastCommandInBatchHostVisible;
switch (DeviceEventsStr ? std::atoi(DeviceEventsStr) : Default) {
case 0:
return AllHostVisible;
case 1:
return OnDemandHostVisibleProxy;
case 2:
return LastCommandInBatchHostVisible;
}
return Default;
}();
// 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 <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_ERROR_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_COMPUTE_ENGINE can be set to an integer (>=0) in
// which case all compute commands will be submitted to the command-queue
// with the given index in the compute command group. If it is instead set
// to negative then all available compute engines may be used.
//
// The default value is "-1".
//
static const std::pair<int, int> getRangeOfAllowedComputeEngines = [] {
const char *EnvVar = std::getenv("SYCL_PI_LEVEL_ZERO_USE_COMPUTE_ENGINE");
// If the environment variable is not set, all available compute engines
// can be used.
if (!EnvVar)
return std::pair<int, int>(0, INT_MAX);
auto EnvVarValue = std::atoi(EnvVar);
if (EnvVarValue >= 0) {
return std::pair<int, int>(EnvVarValue, EnvVarValue);
}
return std::pair<int, int>(0, INT_MAX);
}();
// 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, only index 0 compute engine will be
// used when immediate commandlists are being used. For standard commandlists
// all are used.
if (!EnvVar)
return std::pair<int, int>(0, UseImmediateCommandLists ? 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;
// Flags which tell whether various Level Zero extensions are available.
static bool PiDriverGlobalOffsetExtensionFound = false;
static bool PiDriverModuleProgramExtensionFound = false;
pi_result
_pi_context::getFreeSlotInExistingOrNewPool(ze_event_pool_handle_t &Pool,
size_t &Index, bool HostVisible,
bool ProfilingEnabled) {
// Lock while updating event pool machinery.
std::scoped_lock Lock(ZeEventPoolCacheMutex);
std::list<ze_event_pool_handle_t> *ZePoolCache =
getZeEventPoolCache(HostVisible, ProfilingEnabled);
// 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 = 0;
if (HostVisible)
ZeEventPoolDesc.flags |= ZE_EVENT_POOL_FLAG_HOST_VISIBLE;
if (ProfilingEnabled)
ZeEventPoolDesc.flags |= ZE_EVENT_POOL_FLAG_KERNEL_TIMESTAMP;
zePrint("ze_event_pool_desc_t flags set to: %d\n", ZeEventPoolDesc.flags);
std::vector<ze_device_handle_t> ZeDevices;
std::for_each(Devices.begin(), Devices.end(), [&](const 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) {
std::shared_lock EventLock(Event->Mutex, std::defer_lock);
std::scoped_lock LockAll(ZeEventPoolCacheMutex, EventLock);
if (!Event->ZeEventPool) {
// This must be an interop event created on a users's pool.
// Do nothing.
return PI_SUCCESS;
}
std::list<ze_event_pool_handle_t> *ZePoolCache =
getZeEventPoolCache(Event->isHostVisible(), Event->isProfilingEnabled());
// Put the empty pool to the cache of the pools.
if (NumEventsUnreleasedInEventPool[Event->ZeEventPool] == 0)
die("Invalid event release: event pool doesn't have unreleased events");
if (--NumEventsUnreleasedInEventPool[Event->ZeEventPool] == 0) {
if (ZePoolCache->front() != Event->ZeEventPool) {
ZePoolCache->push_back(Event->ZeEventPool);
}
NumEventsAvailableInEventPool[Event->ZeEventPool] = 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_INVALID_MODULE_UNLINKED)
ZE_ERRCASE(ZE_RESULT_ERROR_UNKNOWN)
#undef ZE_ERRCASE
default:
assert(false && "Unexpected Error code");
} // switch
}
// Global variables for PI_ERROR_PLUGIN_SPECIFIC_ERROR
constexpr size_t MaxMessageSize = 256;
thread_local pi_result ErrorMessageCode = PI_SUCCESS;
thread_local char ErrorMessage[MaxMessageSize];
// Utility function for setting a message and warning
[[maybe_unused]] static void setErrorMessage(const char *message,
pi_result error_code) {
assert(strlen(message) <= MaxMessageSize);
strcpy(ErrorMessage, message);
ErrorMessageCode = error_code;
}
// Returns plugin specific error and warning messages
pi_result piPluginGetLastError(char **message) {
*message = &ErrorMessage[0];
return ErrorMessageCode;
}
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 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
// \param ForceHostVisible tells if the event must be created in
// the host-visible pool
inline static pi_result createEventAndAssociateQueue(
pi_queue Queue, pi_event *Event, pi_command_type CommandType,
pi_command_list_ptr_t CommandList, bool ForceHostVisible = false) {
PI_CALL(EventCreate(Queue->Context, Queue,
ForceHostVisible ? true : EventsScope == AllHostVisible,
Event));
(*Event)->Queue = Queue;
(*Event)->CommandType = CommandType;
// Append this Event to the CommandList, if any
if (CommandList != Queue->CommandListMap.end()) {
CommandList->second.append(*Event);
PI_CALL(piEventRetain(*Event));
}
// 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.
Queue->RefCount.increment();
// 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 CleanupCompletedEvent(Event).
//
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()));
// Initialize ordinal and compute queue group properties
for (uint32_t i = 0; i < numQueueGroups; i++) {
if (QueueGroupProperties[i].flags &
ZE_COMMAND_QUEUE_GROUP_PROPERTY_FLAG_COMPUTE) {
QueueGroup[queue_group_info_t::Compute].ZeOrdinal = i;
QueueGroup[queue_group_info_t::Compute].ZeProperties =
QueueGroupProperties[i];
break;
}
}
// Reinitialize a sub-sub-device with its own ordinal, index and numQueues
// Our sub-sub-device representation is currently [Level-Zero sub-device
// handle + Level-Zero compute group/engine index]. As we have a single queue
// per device, we need to reinitialize numQueues in ZeProperties to be 1.
if (SubSubDeviceOrdinal >= 0) {
QueueGroup[queue_group_info_t::Compute].ZeOrdinal = SubSubDeviceOrdinal;
QueueGroup[queue_group_info_t::Compute].ZeIndex = SubSubDeviceIndex;
QueueGroup[queue_group_info_t::Compute].ZeProperties.numQueues = 1;
} else { // Proceed with initialization for root and sub-device
// How is it possible that there are no "compute" capabilities?
if (QueueGroup[queue_group_info_t::Compute].ZeOrdinal < 0) {
return PI_ERROR_UNKNOWN;
}
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) {
QueueGroup[queue_group_info_t::MainCopy].ZeOrdinal = i;
QueueGroup[queue_group_info_t::MainCopy].ZeProperties =
QueueGroupProperties[i];
} else {
QueueGroup[queue_group_info_t::LinkCopy].ZeOrdinal = i;
QueueGroup[queue_group_info_t::LinkCopy].ZeProperties =
QueueGroupProperties[i];
break;
}
}
}
if (QueueGroup[queue_group_info_t::MainCopy].ZeOrdinal < 0)
zePrint("NOTE: main blitter/copy engine is not available\n");
else
zePrint("NOTE: main blitter/copy engine is available\n");
if (QueueGroup[queue_group_info_t::LinkCopy].ZeOrdinal < 0)
zePrint("NOTE: link blitter/copy engines are not available\n");
else
zePrint("NOTE: link blitter/copy engines are available\n");
}
}
// 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()));
};
ZeDeviceMemoryAccessProperties.Compute =
[ZeDevice](ze_device_memory_access_properties_t &Properties) {
ZE_CALL_NOCHECK(zeDeviceGetMemoryAccessProperties,
(ZeDevice, &Properties));
};
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_device _pi_context::getRootDevice() const {
assert(Devices.size() > 0);
if (Devices.size() == 1)
return Devices[0];
// Check if we have context with subdevices of the same device (context
// may include root device itself as well)
pi_device ContextRootDevice =
Devices[0]->RootDevice ? Devices[0]->RootDevice : Devices[0];
// For context with sub subdevices, the ContextRootDevice might still
// not be the root device.
// Check whether the ContextRootDevice is the subdevice or root device.
if (ContextRootDevice->isSubDevice()) {
ContextRootDevice = ContextRootDevice->RootDevice;
}
for (auto &Device : Devices) {
if ((!Device->RootDevice && Device != ContextRootDevice) ||
(Device->RootDevice && Device->RootDevice != ContextRootDevice)) {
ContextRootDevice = nullptr;
break;
}
}
return ContextRootDevice;
}
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];
// NOTE: we always submit to the "0" index compute engine with immediate
// command list since this is one for context.
ZeStruct<ze_command_queue_desc_t> ZeCommandQueueDesc;
ZeCommandQueueDesc.ordinal =
Device->QueueGroup[_pi_device::queue_group_info_t::Compute].ZeOrdinal;
ZeCommandQueueDesc.index = 0;
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::scoped_lock Lock(ZeEventPoolCacheMutex);
for (auto &ZePoolCache : ZeEventPoolCache) {
for (auto &ZePool : ZePoolCache)
ZE_CALL(zeEventPoolDestroy, (ZePool));
ZePoolCache.clear();
}
}
// Destroy the command list used for initializations
ZE_CALL(zeCommandListDestroy, (ZeCommandListInit));
std::scoped_lock Lock(ZeCommandListCacheMutex);
for (auto &List : ZeComputeCommandListCache) {
for (ze_command_list_handle_t &ZeCommandList : List.second) {
if (ZeCommandList)
ZE_CALL(zeCommandListDestroy, (ZeCommandList));
}
}
for (auto &List : ZeCopyCommandListCache) {
for (ze_command_list_handle_t &ZeCommandList : List.second) {
if (ZeCommandList)
ZE_CALL(zeCommandListDestroy, (ZeCommandList));
}
}
return PI_SUCCESS;
}
bool pi_command_list_info_t::isCopy(pi_queue Queue) const {
return ZeQueueGroupOrdinal !=
(uint32_t)Queue->Device
->QueueGroup[_pi_device::queue_group_info_t::type::Compute]
.ZeOrdinal;
}
bool _pi_queue::isInOrderQueue() const {
// If out-of-order queue property is not set, then this is a in-order queue.
return ((this->Properties & PI_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE) == 0);
}
pi_result
_pi_queue::resetCommandList(pi_command_list_ptr_t CommandList,
bool MakeAvailable,
std::vector<pi_event> &EventListToCleanup) {
bool UseCopyEngine = CommandList->second.isCopy(this);
// Immediate commandlists do not have an associated fence.
if (CommandList->second.ZeFence != nullptr) {
// 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.ZeFenceInUse = false;
}
auto &EventList = CommandList->second.EventList;
// Remember all the events in this command list which needs to be
// released/cleaned up and clear event list associated with command list.
std::move(std::begin(EventList), std::end(EventList),
std::back_inserter(EventListToCleanup));
EventList.clear();
// Standard commandlists move in and out of the cache as they are recycled.
// Immediate commandlists are always available.
if (CommandList->second.ZeFence != nullptr && MakeAvailable) {
std::scoped_lock Lock(this->Context->ZeCommandListCacheMutex);
auto &ZeCommandListCache =
UseCopyEngine
? this->Context->ZeCopyCommandListCache[this->Device->ZeDevice]
: this->Context->ZeComputeCommandListCache[this->Device->ZeDevice];
ZeCommandListCache.push_back(CommandList->first);
}
return PI_SUCCESS;
}
// 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{3};
pi_uint32 NumTimesClosedFullThreshold{8};
// 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;
// Helper function to initialize static variables that holds batch config info
// for compute and copy command batching.
static const zeCommandListBatchConfig ZeCommandListBatchConfig(bool IsCopy) {
zeCommandListBatchConfig Config{}; // default initialize
// Default value of 0. This specifies to use dynamic batch size adjustment.
const auto BatchSizeStr =
(IsCopy) ? std::getenv("SYCL_PI_LEVEL_ZERO_COPY_BATCH_SIZE")
: 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 ":"