forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpi_level_zero.cpp
More file actions
8447 lines (7350 loc) · 324 KB
/
pi_level_zero.cpp
File metadata and controls
8447 lines (7350 loc) · 324 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 <algorithm>
#include <cstdarg>
#include <cstdio>
#include <cstring>
#include <memory>
#include <set>
#include <sstream>
#include <string>
#include <sycl/detail/pi.h>
#include <sycl/detail/spinlock.hpp>
#include <thread>
#include <utility>
#include <zet_api.h>
#include "ur/usm_allocator_config.hpp"
#include "ur_bindings.hpp"
extern "C" {
// Forward declarartions.
static pi_result piQueueReleaseInternal(pi_queue Queue);
static pi_result piEventReleaseInternal(pi_event Event);
static pi_result EventCreate(pi_context Context, pi_queue Queue,
bool HostVisible, pi_event *RetEvent);
}
// Defined in tracing.cpp
void enableZeTracing();
void disableZeTracing();
namespace {
// 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 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 true;
return std::stoi(UseMultipleCmdlistBarriersFlag) > 0;
}();
// This is an experimental option that allows to disable caching of events in
// the context.
static const bool DisableEventsCaching = [] {
const char *DisableEventsCachingFlag =
std::getenv("SYCL_PI_LEVEL_ZERO_DISABLE_EVENTS_CACHING");
if (!DisableEventsCachingFlag)
return false;
return std::stoi(DisableEventsCachingFlag) != 0;
}();
// This is an experimental option that allows reset and reuse of uncompleted
// events in the in-order queue with discard_events property.
static const bool ReuseDiscardedEvents = [] {
const char *ReuseDiscardedEventsFlag =
std::getenv("SYCL_PI_LEVEL_ZERO_REUSE_DISCARDED_EVENTS");
if (!ReuseDiscardedEventsFlag)
return true;
return std::stoi(ReuseDiscardedEventsFlag) > 0;
}();
// 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;
}();
// Due to a bug with 2D memory copy to and from non-USM pointers, this option is
// disabled by default.
static const bool UseMemcpy2DOperations = [] {
const char *UseMemcpy2DOperationsFlag =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_NATIVE_USM_MEMCPY2D");
if (!UseMemcpy2DOperationsFlag)
return false;
return std::stoi(UseMemcpy2DOperationsFlag) > 0;
}();
static usm_settings::USMAllocatorConfig USMAllocatorConfigInstance;
// Map from L0 to PI result.
static inline pi_result mapError(ze_result_t Result) {
return ur2piResult(ze2urResult(Result));
}
// 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); \
}
// Trace an internal PI call; returns in case of an error.
#define PI_CALL(Call) \
{ \
if (PrintTrace) \
fprintf(stderr, "PI ---> %s\n", #Call); \
pi_result Result = (Call); \
if (Result != PI_SUCCESS) \
return Result; \
}
// Controls if we should choose doing eager initialization
// to make it happen on warmup paths and have the reportable
// paths be less likely affected.
//
static bool doEagerInit = [] {
const char *EagerInit = std::getenv("SYCL_EAGER_INIT");
return EagerInit ? std::atoi(EagerInit) != 0 : false;
}();
// 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 (!UrL0Debug) {
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);
}
} // 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 "0".
//
static const std::pair<int, int> getRangeOfAllowedComputeEngines() {
static const char *EnvVar =
std::getenv("SYCL_PI_LEVEL_ZERO_USE_COMPUTE_ENGINE");
// If the environment variable is not set only use "0" CCS for now.
// TODO: allow all CCSs when HW support is complete.
if (!EnvVar)
return std::pair<int, int>(0, 0);
auto EnvVarValue = std::atoi(EnvVar);
if (EnvVarValue >= 0) {
return std::pair<int, int>(EnvVarValue, EnvVarValue);
}
return std::pair<int, int>(0, INT_MAX);
}
pi_platform _pi_context::getPlatform() const { return Devices[0]->Platform; }
bool _pi_context::isValidDevice(pi_device Device) const {
while (Device) {
if (std::find(Devices.begin(), Devices.end(), Device) != Devices.end())
return true;
Device = Device->RootDevice;
}
return 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<pi_mutex> Lock(ZeEventPoolCacheMutex);
std::list<ze_event_pool_handle_t> *ZePoolCache =
getZeEventPoolCache(HostVisible, ProfilingEnabled);
if (!ZePoolCache->empty()) {
if (NumEventsAvailableInEventPool[ZePoolCache->front()] == 0) {
if (DisableEventsCaching) {
// Remove full pool from the cache if events caching is disabled.
ZePoolCache->erase(ZePoolCache->begin());
} else {
// If event caching is enabled then we don't destroy events so there is
// no need to remove pool from the cache and add it back when it has
// available slots. Just keep it in the tail of the cache so that all
// pools can be destroyed during context destruction.
ZePoolCache->push_front(nullptr);
}
}
}
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;
urPrint("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<pi_shared_mutex> EventLock(Event->Mutex, std::defer_lock);
std::scoped_lock<pi_mutex, std::shared_lock<pi_shared_mutex>> 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;
}
// 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);
static pi_result enqueueMemCopyRectHelper(
pi_command_type CommandType, pi_queue Queue, const void *SrcBuffer,
void *DstBuffer, pi_buff_rect_offset SrcOrigin,
pi_buff_rect_offset DstOrigin, pi_buff_rect_region Region,
size_t SrcRowPitch, size_t DstRowPitch, size_t SrcSlicePitch,
size_t DstSlicePitch, pi_bool Blocking, pi_uint32 NumEventsInWaitList,
const pi_event *EventWaitList, pi_event *Event,
bool PreferCopyEngine = false);
bool _pi_queue::doReuseDiscardedEvents() {
return ReuseDiscardedEvents && isInOrderQueue() && isDiscardEvents();
}
pi_result _pi_queue::resetDiscardedEvent(pi_command_list_ptr_t CommandList) {
if (LastCommandEvent && LastCommandEvent->IsDiscarded) {
ZE_CALL(zeCommandListAppendBarrier,
(CommandList->first, nullptr, 1, &(LastCommandEvent->ZeEvent)));
ZE_CALL(zeCommandListAppendEventReset,
(CommandList->first, LastCommandEvent->ZeEvent));
// Create new pi_event but with the same ze_event_handle_t. We are going
// to use this pi_event for the next command with discarded event.
pi_event PiEvent;
try {
PiEvent = new _pi_event(LastCommandEvent->ZeEvent,
LastCommandEvent->ZeEventPool, Context,
PI_COMMAND_TYPE_USER, true);
} catch (const std::bad_alloc &) {
return PI_ERROR_OUT_OF_HOST_MEMORY;
} catch (...) {
return PI_ERROR_UNKNOWN;
}
if (LastCommandEvent->isHostVisible())
PiEvent->HostVisibleEvent = PiEvent;
PI_CALL(addEventToQueueCache(PiEvent));
}
return PI_SUCCESS;
}
// 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 IsInternal tells if the event is internal, i.e. visible in the L0
// plugin only.
// \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 IsInternal = false,
bool ForceHostVisible = false) {
if (!ForceHostVisible)
ForceHostVisible = Queue->Device->ZeEventsScope == AllHostVisible;
// If event is discarded then try to get event from the queue cache.
*Event =
IsInternal ? Queue->getEventFromQueueCache(ForceHostVisible) : nullptr;
if (*Event == nullptr)
PI_CALL(EventCreate(Queue->Context, Queue, ForceHostVisible, Event));
(*Event)->Queue = Queue;
(*Event)->CommandType = CommandType;
(*Event)->IsDiscarded = IsInternal;
(*Event)->CommandList = CommandList;
// Discarded event doesn't own ze_event, it is used by multiple pi_event
// objects. We destroy corresponding ze_event by releasing events from the
// events cache at queue destruction. Event in the cache owns the Level Zero
// event.
if (IsInternal)
(*Event)->OwnZeEvent = false;
// Append this Event to the CommandList, if any
if (CommandList != Queue->CommandListMap.end()) {
CommandList->second.append(*Event);
(*Event)->RefCount.increment();
}
// 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).
// If the event is internal then don't increment the reference count as this
// event will not be waited/released by SYCL RT, so it must be destroyed by
// EventRelease in resetCommandList.
if (!IsInternal)
PI_CALL(piEventRetain(*Event));
return PI_SUCCESS;
}
pi_result _pi_queue::signalEventFromCmdListIfLastEventDiscarded(
pi_command_list_ptr_t CommandList) {
// We signal new event at the end of command list only if we have queue with
// discard_events property and the last command event is discarded.
if (!(doReuseDiscardedEvents() && LastCommandEvent &&
LastCommandEvent->IsDiscarded))
return PI_SUCCESS;
pi_event Event;
PI_CALL(createEventAndAssociateQueue(
this, &Event, PI_COMMAND_TYPE_USER, CommandList,
/* IsDiscarded */ false, /* ForceHostVisible */ false))
PI_CALL(piEventReleaseInternal(Event));
LastCommandEvent = Event;
ZE_CALL(zeCommandListAppendSignalEvent, (CommandList->first, Event->ZeEvent));
return PI_SUCCESS;
}
pi_event _pi_queue::getEventFromQueueCache(bool HostVisible) {
auto Cache = HostVisible ? &EventCaches[0] : &EventCaches[1];
// If we don't have any events, return nullptr.
// If we have only a single event then it was used by the last command and we
// can't use it now because we have to enforce round robin between two events.
if (Cache->size() < 2)
return nullptr;
// If there are two events then return an event from the beginning of the list
// since event of the last command is added to the end of the list.
auto It = Cache->begin();
pi_event RetEvent = *It;
Cache->erase(It);
return RetEvent;
}
pi_result _pi_queue::addEventToQueueCache(pi_event Event) {
auto Cache = Event->isHostVisible() ? &EventCaches[0] : &EventCaches[1];
Cache->emplace_back(Event);
return PI_SUCCESS;
}
// Get value of the threshold for number of events in immediate command lists.
// If number of events in the immediate command list exceeds this threshold then
// cleanup process for those events is executed.
static const size_t ImmCmdListsEventCleanupThreshold = [] {
const char *ImmCmdListsEventCleanupThresholdStr = std::getenv(
"SYCL_PI_LEVEL_ZERO_IMMEDIATE_COMMANDLISTS_EVENT_CLEANUP_THRESHOLD");
static constexpr int Default = 20;
if (!ImmCmdListsEventCleanupThresholdStr)
return Default;
int Threshold = std::atoi(ImmCmdListsEventCleanupThresholdStr);
// Basically disable threshold if negative value is provided.
if (Threshold < 0)
return INT_MAX;
return Threshold;
}();
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() {
// Helper lambda to create various USM allocators for a device.
// Note that the CCS devices and their respective subdevices share a
// common ze_device_handle and therefore, also share USM allocators.
auto createUSMAllocators = [this](pi_device Device) {
SharedMemAllocContexts.emplace(
std::piecewise_construct, std::make_tuple(Device->ZeDevice),
std::make_tuple(
std::unique_ptr<SystemMemory>(
new USMSharedMemoryAlloc(this, Device)),
USMAllocatorConfigInstance.Configs[usm_settings::MemType::Shared]));
SharedReadOnlyMemAllocContexts.emplace(
std::piecewise_construct, std::make_tuple(Device->ZeDevice),
std::make_tuple(std::unique_ptr<SystemMemory>(
new USMSharedReadOnlyMemoryAlloc(this, Device)),
USMAllocatorConfigInstance
.Configs[usm_settings::MemType::SharedReadOnly]));
DeviceMemAllocContexts.emplace(
std::piecewise_construct, std::make_tuple(Device->ZeDevice),
std::make_tuple(
std::unique_ptr<SystemMemory>(
new USMDeviceMemoryAlloc(this, Device)),
USMAllocatorConfigInstance.Configs[usm_settings::MemType::Device]));
};
// Recursive helper to call createUSMAllocators for all sub-devices
std::function<void(pi_device)> createUSMAllocatorsRecursive;
createUSMAllocatorsRecursive =
[createUSMAllocators,
&createUSMAllocatorsRecursive](pi_device Device) -> void {
createUSMAllocators(Device);
for (auto &SubDevice : Device->SubDevices)
createUSMAllocatorsRecursive(SubDevice);
};
// Create USM allocator context for each pair (device, context).
//
for (auto &Device : Devices) {
createUSMAllocatorsRecursive(Device);
}
// Create USM allocator context for host. Device and Shared USM allocations
// are device-specific. Host allocations are not device-dependent therefore
// we don't need a map with device as key.
HostMemAllocContext = std::make_unique<USMAllocContext>(
std::unique_ptr<SystemMemory>(new USMHostMemoryAlloc(this)),
USMAllocatorConfigInstance.Configs[usm_settings::MemType::Host]);
// We may allocate memory to this root device so create allocators.
if (SingleRootDevice &&
DeviceMemAllocContexts.find(SingleRootDevice->ZeDevice) ==
DeviceMemAllocContexts.end()) {
createUSMAllocators(SingleRootDevice);
}
// 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: we use Device[0] here as the single immediate command-list
// for buffer creation and migration. Initialization is in
// in sync and is always performed to Devices[0] as well but
// D2D migartion, if no P2P, is broken since it should use
// immediate command-list for the specfic devices, and this single one.
//
pi_device Device = SingleRootDevice ? SingleRootDevice : Devices[0];
// Prefer to use copy engine for initialization copies,
// if available and allowed (main copy engine with index 0).
ZeStruct<ze_command_queue_desc_t> ZeCommandQueueDesc;
const auto &Range = getRangeOfAllowedCopyEngines((ur_device_handle_t)Device);
ZeCommandQueueDesc.ordinal =
Device->QueueGroup[_pi_device::queue_group_info_t::Compute].ZeOrdinal;
if (Range.first >= 0 &&
Device->QueueGroup[_pi_device::queue_group_info_t::MainCopy].ZeOrdinal !=
-1)
ZeCommandQueueDesc.ordinal =
Device->QueueGroup[_pi_device::queue_group_info_t::MainCopy].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 and event pool caches would be still alive.
if (!DisableEventsCaching) {
std::scoped_lock<pi_mutex> Lock(EventCacheMutex);
for (auto &EventCache : EventCaches) {
for (auto &Event : EventCache) {
ZE_CALL(zeEventDestroy, (Event->ZeEvent));
delete Event;
}
EventCache.clear();
}
}
{
std::scoped_lock<pi_mutex> 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<pi_mutex> 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_FLAG_OUT_OF_ORDER_EXEC_MODE_ENABLE) ==
0);
}
bool _pi_queue::isDiscardEvents() const {
return ((this->Properties & PI_EXT_ONEAPI_QUEUE_FLAG_DISCARD_EVENTS) != 0);
}
bool _pi_queue::isPriorityLow() const {
return ((this->Properties & PI_EXT_ONEAPI_QUEUE_FLAG_PRIORITY_LOW) != 0);
}
bool _pi_queue::isPriorityHigh() const {
return ((this->Properties & PI_EXT_ONEAPI_QUEUE_FLAG_PRIORITY_HIGH) != 0);
}
pi_result _pi_queue::resetCommandList(pi_command_list_ptr_t CommandList,
bool MakeAvailable,
std::vector<pi_event> &EventListToCleanup,
bool CheckStatus) {
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;
CommandList->second.IsClosed = false;
}
auto &EventList = CommandList->second.EventList;
// Check if standard commandlist or fully synced in-order queue.
// If one of those conditions is met then we are sure that all events are
// completed so we don't need to check event status.
if (!CheckStatus || CommandList->second.ZeFence != nullptr ||
(isInOrderQueue() && !LastCommandEvent)) {
// 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();
} else if (!isDiscardEvents()) {
// For immediate commandlist reset only those events that have signalled.
// If events in the queue are discarded then we can't check their status.
for (auto it = EventList.begin(); it != EventList.end();) {
std::scoped_lock<pi_shared_mutex> EventLock((*it)->Mutex);
ze_result_t ZeResult =
(*it)->Completed
? ZE_RESULT_SUCCESS
: ZE_CALL_NOCHECK(zeEventQueryStatus, ((*it)->ZeEvent));
// Break early as soon as we found first incomplete event because next
// events are submitted even later. We are not trying to find all
// completed events here because it may be costly. I.e. we are checking
// only elements which are most likely completed because they were
// submitted earlier. It is guaranteed that all events will be eventually
// cleaned up at queue sync/release.
if (ZeResult == ZE_RESULT_NOT_READY)
break;
if (ZeResult != ZE_RESULT_SUCCESS)
return mapError(ZeResult);
EventListToCleanup.push_back(std::move((*it)));
it = EventList.erase(it);
}
}
// 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<pi_mutex> 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.
struct zeCommandListBatchConfig {
// 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; }
};
// 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 ":"
pi_uint32 Val;
try {
Val = std::stoi(BatchConfig.substr(Pos));
} catch (...) {
if (IsCopy)
urPrint(
"SYCL_PI_LEVEL_ZERO_COPY_BATCH_SIZE: failed to parse value\n");
else
urPrint("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");
}
if (IsCopy)
urPrint("SYCL_PI_LEVEL_ZERO_COPY_BATCH_SIZE: dynamic batch param "
"#%d: %d\n",
(int)Ord, (int)Val);
else
urPrint(
"SYCL_PI_LEVEL_ZERO_BATCH_SIZE: dynamic batch param #%d: %d\n",
(int)Ord, (int)Val);
};
} else {
// Negative batch sizes are silently ignored.
if (IsCopy)
urPrint("SYCL_PI_LEVEL_ZERO_COPY_BATCH_SIZE: ignored negative value\n");
else
urPrint("SYCL_PI_LEVEL_ZERO_BATCH_SIZE: ignored negative value\n");
}
}
return Config;
}
// Static variable that holds batch config info for compute command batching.
static const zeCommandListBatchConfig ZeCommandListBatchComputeConfig = [] {
using IsCopy = bool;
return ZeCommandListBatchConfig(IsCopy{false});
}();
// Static variable that holds batch config info for copy command batching.
static const zeCommandListBatchConfig ZeCommandListBatchCopyConfig = [] {
using IsCopy = bool;
return ZeCommandListBatchConfig(IsCopy{true});
}();
_pi_queue::_pi_queue(std::vector<ze_command_queue_handle_t> &ComputeQueues,
std::vector<ze_command_queue_handle_t> &CopyQueues,
pi_context Context, pi_device Device,
bool OwnZeCommandQueue,
pi_queue_properties PiQueueProperties,
int ForceComputeIndex)
: Context{Context}, Device{Device}, OwnZeCommandQueue{OwnZeCommandQueue},
Properties(PiQueueProperties) {
// Compute group initialization.
// First, see if the queue's device allows for round-robin or it is
// fixed to one particular compute CCS (it is so for sub-sub-devices).
auto &ComputeQueueGroupInfo = Device->QueueGroup[queue_type::Compute];
pi_queue_group_t ComputeQueueGroup{this, queue_type::Compute};
ComputeQueueGroup.ZeQueues = ComputeQueues;
// Create space to hold immediate commandlists corresponding to the
// ZeQueues
if (Device->ImmCommandListUsed) {
ComputeQueueGroup.ImmCmdLists = std::vector<pi_command_list_ptr_t>(
ComputeQueueGroup.ZeQueues.size(), CommandListMap.end());
}
if (ComputeQueueGroupInfo.ZeIndex >= 0) {
// Sub-sub-device
// sycl::ext::intel::property::queue::compute_index works with any
// backend/device by allowing single zero index if multiple compute CCSes
// are not supported. Sub-sub-device falls into the same bucket.
assert(ForceComputeIndex <= 0);
ComputeQueueGroup.LowerIndex = ComputeQueueGroupInfo.ZeIndex;
ComputeQueueGroup.UpperIndex = ComputeQueueGroupInfo.ZeIndex;
ComputeQueueGroup.NextIndex = ComputeQueueGroupInfo.ZeIndex;
} else if (ForceComputeIndex >= 0) {
ComputeQueueGroup.LowerIndex = ForceComputeIndex;
ComputeQueueGroup.UpperIndex = ForceComputeIndex;
ComputeQueueGroup.NextIndex = ForceComputeIndex;
} else {
// Set-up to round-robin across allowed range of engines.
uint32_t FilterLowerIndex = getRangeOfAllowedComputeEngines().first;
uint32_t FilterUpperIndex = getRangeOfAllowedComputeEngines().second;
FilterUpperIndex = std::min((size_t)FilterUpperIndex,
FilterLowerIndex + ComputeQueues.size() - 1);
if (FilterLowerIndex <= FilterUpperIndex) {
ComputeQueueGroup.LowerIndex = FilterLowerIndex;
ComputeQueueGroup.UpperIndex = FilterUpperIndex;
ComputeQueueGroup.NextIndex = ComputeQueueGroup.LowerIndex;
} else {
die("No compute queue available/allowed.");
}
}
if (Device->ImmCommandListUsed) {
// Create space to hold immediate commandlists corresponding to the
// ZeQueues
ComputeQueueGroup.ImmCmdLists = std::vector<pi_command_list_ptr_t>(
ComputeQueueGroup.ZeQueues.size(), CommandListMap.end());
}
// Thread id will be used to create separate queue groups per thread.
auto TID = std::this_thread::get_id();
ComputeQueueGroupsByTID.insert({TID, ComputeQueueGroup});
// Copy group initialization.
pi_queue_group_t CopyQueueGroup{this, queue_type::MainCopy};
const auto &Range = getRangeOfAllowedCopyEngines((ur_device_handle_t)Device);
if (Range.first < 0 || Range.second < 0) {
// We are asked not to use copy engines, just do nothing.
// Leave CopyQueueGroup.ZeQueues empty, and it won't be used.
} else {
uint32_t FilterLowerIndex = Range.first;
uint32_t FilterUpperIndex = Range.second;
FilterUpperIndex = std::min((size_t)FilterUpperIndex,
FilterLowerIndex + CopyQueues.size() - 1);
if (FilterLowerIndex <= FilterUpperIndex) {
CopyQueueGroup.ZeQueues = CopyQueues;
CopyQueueGroup.LowerIndex = FilterLowerIndex;
CopyQueueGroup.UpperIndex = FilterUpperIndex;
CopyQueueGroup.NextIndex = CopyQueueGroup.LowerIndex;
// Create space to hold immediate commandlists corresponding to the
// ZeQueues
if (Device->ImmCommandListUsed) {
CopyQueueGroup.ImmCmdLists = std::vector<pi_command_list_ptr_t>(
CopyQueueGroup.ZeQueues.size(), CommandListMap.end());
}
}
}
CopyQueueGroupsByTID.insert({TID, CopyQueueGroup});
// Initialize compute/copy command batches.
ComputeCommandBatch.OpenCommandList = CommandListMap.end();
CopyCommandBatch.OpenCommandList = CommandListMap.end();
ComputeCommandBatch.QueueBatchSize =
ZeCommandListBatchComputeConfig.startSize();
CopyCommandBatch.QueueBatchSize = ZeCommandListBatchCopyConfig.startSize();
}
static pi_result CleanupCompletedEvent(pi_event Event,
bool QueueLocked = false);
// Helper function to perform the necessary cleanup of the events from reset cmd
// list.
static pi_result
CleanupEventListFromResetCmdList(std::vector<pi_event> &EventListToCleanup,
bool QueueLocked = false) {
for (auto &Event : EventListToCleanup) {
// We don't need to synchronize the events since the fence associated with
// the command list was synchronized.
{
std::scoped_lock<pi_shared_mutex> EventLock(Event->Mutex);
Event->Completed = true;
}
PI_CALL(CleanupCompletedEvent(Event, QueueLocked));
// This event was removed from the command list, so decrement ref count
// (it was incremented when they were added to the command list).
PI_CALL(piEventReleaseInternal(Event));
}
return PI_SUCCESS;
}
/// @brief Cleanup events in the immediate lists of the queue.
/// @param Queue Queue where events need to be cleaned up.
/// @param QueueLocked Indicates if the queue mutex is locked by caller.
/// @param QueueSynced 'true' if queue was synchronized before the
/// call and no other commands were submitted after synchronization, 'false'
/// otherwise.
/// @param CompletedEvent Hint providing an event which was synchronized before
/// the call, in case of in-order queue it allows to cleanup all preceding
/// events.
/// @return PI_SUCCESS if successful, PI error code otherwise.
static pi_result CleanupEventsInImmCmdLists(pi_queue Queue,
bool QueueLocked = false,
bool QueueSynced = false,
pi_event CompletedEvent = nullptr) {
// Handle only immediate command lists here.
if (!Queue || !Queue->Device->ImmCommandListUsed)
return PI_SUCCESS;
std::vector<pi_event> EventListToCleanup;
{
std::unique_lock<pi_shared_mutex> QueueLock(Queue->Mutex, std::defer_lock);
if (!QueueLocked)