forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqueue.cpp
2526 lines (2247 loc) · 99 KB
/
queue.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--------- queue.cpp - Level Zero Adapter -----------------------------===//
//
// Copyright (C) 2023 Intel Corporation
//
// Part of the Unified-Runtime Project, under the Apache License v2.0 with LLVM
// Exceptions. See LICENSE.TXT
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include <algorithm>
#include <climits>
#include <cstdint>
#include <optional>
#include <string.h>
#include <vector>
#include "adapter.hpp"
#include "common.hpp"
#include "event.hpp"
#include "queue.hpp"
#include "ur_interface_loader.hpp"
#include "ur_level_zero.hpp"
#include "ur_util.hpp"
#include "ze_api.h"
// Hard limit for the event completion batches.
static const uint64_t CompletionBatchesMax = [] {
// Default value chosen empirically to maximize the number of asynchronous
// in-flight operations and avoid excessive synchronous waits.
return getenv_to_unsigned("UR_L0_IMMEDIATE_COMMANDLISTS_BATCH_MAX")
.value_or(10);
}();
static const uint64_t CompletionEventsPerBatch = [] {
// The number of events to accumulate in each batch prior to waiting for
// completion.
return getenv_to_unsigned("UR_L0_IMMEDIATE_COMMANDLISTS_EVENTS_PER_BATCH")
.value_or(256);
}();
ur_completion_batch::ur_completion_batch()
: barrierEvent(nullptr), st(EMPTY), numEvents(0) {}
ur_completion_batch::~ur_completion_batch() {
if (barrierEvent)
urEventReleaseInternal(barrierEvent);
}
bool ur_completion_batch::isFull() {
assert(st == ACCUMULATING);
return numEvents >= CompletionEventsPerBatch;
}
void ur_completion_batch::append() {
assert(st == ACCUMULATING);
numEvents++;
}
ur_result_t ur_completion_batch::reset() {
st = EMPTY;
numEvents = 0;
// we reuse the UR event handle but reset the internal level-zero one
if (barrierEvent)
ZE2UR_CALL(zeEventHostReset, (barrierEvent->ZeEvent));
return UR_RESULT_SUCCESS;
}
void ur_completion_batch::use() {
assert(st == EMPTY);
st = ACCUMULATING;
}
ur_completion_batch::state ur_completion_batch::getState() { return st; }
ur_completion_batch::state ur_completion_batch::queryState() {
if (st == SEALED) {
checkComplete();
}
return st;
}
bool ur_completion_batch::checkComplete() {
assert(st == COMPLETED || st == SEALED);
if (st == COMPLETED)
return true;
auto zeResult = ZE_CALL_NOCHECK(zeEventQueryStatus, (barrierEvent->ZeEvent));
if (zeResult == ZE_RESULT_SUCCESS) {
st = COMPLETED;
}
return st == COMPLETED;
}
ur_result_t ur_completion_batch::seal(ur_queue_handle_t queue,
ze_command_list_handle_t cmdlist) {
assert(st == ACCUMULATING);
if (!barrierEvent) {
UR_CALL(EventCreate(
queue->Context, queue, false /*IsMultiDevice*/, true /*HostVisible*/,
&barrierEvent, false /*CounterBasedEventEnabled*/,
false /*ForceDisableProfiling*/, false /*InterruptBasedEventEnabled*/));
}
// Instead of collecting all the batched events, we simply issue a global
// barrier for all prior events on the command list. This is simpler and
// showed to be faster in practice.
ZE2UR_CALL(zeCommandListAppendBarrier,
(cmdlist, barrierEvent->ZeEvent, 0, nullptr));
st = SEALED;
return UR_RESULT_SUCCESS;
}
void ur_completion_batches::append(ur_event_handle_t event) {
active->append();
event->completionBatch = active;
}
void ur_completion_batches::moveCompletedEvents(
ur_completion_batch_it it, std::vector<ur_event_handle_t> &events,
std::vector<ur_event_handle_t> &EventListToCleanup) {
// This works by tagging all events belonging to a batch, and then removing
// all events in a vector with the tag (iterator) of the active batch.
// This could be optimized to remove a specific range of entries if we had a
// guarantee that all the appended events in the vector remain there in the
// same order. Unfortunately that is not simple to enforce.
// TODO: An even better approach would be to split the EventList vector into
// smaller batch-sized ones, but that would require a significant refactor.
auto end = std::remove_if(events.begin(), events.end(), [&](auto &event) {
if (event->completionBatch == it) {
EventListToCleanup.push_back(event);
return true;
} else {
return false;
}
});
events.erase(end, events.end());
}
ur_result_t ur_completion_batches::cleanup(
std::vector<ur_event_handle_t> &events,
std::vector<ur_event_handle_t> &EventListToCleanup) {
bool cleaned = false;
while (!sealed.empty()) {
auto oldest_sealed = sealed.front();
if (oldest_sealed->queryState() == ur_completion_batch::COMPLETED) {
sealed.pop();
moveCompletedEvents(oldest_sealed, events, EventListToCleanup);
UR_CALL(oldest_sealed->reset());
cleaned = true;
} else {
break;
}
}
return cleaned ? UR_RESULT_SUCCESS : UR_RESULT_ERROR_OUT_OF_RESOURCES;
}
std::optional<ur_completion_batch_it>
ur_completion_batches::findFirstEmptyBatchOrCreate() {
for (auto it = batches.begin(); it != batches.end(); ++it) {
if (it->getState() == ur_completion_batch::EMPTY) {
return it;
}
}
// try creating a new batch if allowed by the limit.
if (batches.size() < CompletionBatchesMax) {
return batches.emplace(batches.end());
}
return std::nullopt;
}
ur_completion_batches::ur_completion_batches() {
// Batches are created lazily on-demand. Start with just one.
active = batches.emplace(batches.begin());
active->use();
}
ur_result_t ur_completion_batches::tryCleanup(
ur_queue_handle_t queue, ze_command_list_handle_t cmdlist,
std::vector<ur_event_handle_t> &events,
std::vector<ur_event_handle_t> &EventListToCleanup) {
cleanup(events, EventListToCleanup);
if (active->isFull()) {
auto next_batch = findFirstEmptyBatchOrCreate();
if (!next_batch) {
return UR_RESULT_ERROR_OUT_OF_RESOURCES; // EWOULDBLOCK
}
UR_CALL(active->seal(queue, cmdlist));
sealed.push(active);
active = *next_batch;
active->use();
}
return UR_RESULT_SUCCESS;
}
void ur_completion_batches::forceReset() {
for (auto &b : batches) {
b.reset();
}
while (!sealed.empty()) {
sealed.pop();
}
active = batches.begin();
active->use();
}
/// @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.
ur_result_t CleanupEventsInImmCmdLists(ur_queue_handle_t UrQueue,
bool QueueLocked, bool QueueSynced,
ur_event_handle_t CompletedEvent) {
// Handle only immediate command lists here.
if (!UrQueue || !UrQueue->UsingImmCmdLists)
return UR_RESULT_SUCCESS;
ur_event_handle_t_ *UrCompletedEvent =
reinterpret_cast<ur_event_handle_t_ *>(CompletedEvent);
std::vector<ur_event_handle_t> EventListToCleanup;
{
std::unique_lock<ur_shared_mutex> QueueLock(UrQueue->Mutex,
std::defer_lock);
if (!QueueLocked)
QueueLock.lock();
// If queue is locked and fully synchronized then cleanup all events.
// If queue is not locked then by this time there may be new submitted
// commands so we can't do full cleanup.
if (QueueLocked &&
(QueueSynced || (UrQueue->isInOrderQueue() &&
(reinterpret_cast<ur_event_handle_t>(
UrCompletedEvent) == UrQueue->LastCommandEvent ||
!UrQueue->LastCommandEvent)))) {
UrQueue->LastCommandEvent = nullptr;
for (auto &&It = UrQueue->CommandListMap.begin();
It != UrQueue->CommandListMap.end(); ++It) {
UR_CALL(UrQueue->resetCommandList(It, true, EventListToCleanup,
false /* CheckStatus */));
}
} else if (UrQueue->isInOrderQueue() && UrCompletedEvent) {
// If the queue is in-order and we have information about completed event
// then cleanup all events in the command list preceding to CompletedEvent
// including itself.
// Check that the comleted event has associated command list.
if (!(UrCompletedEvent->CommandList &&
UrCompletedEvent->CommandList.value() !=
UrQueue->CommandListMap.end()))
return UR_RESULT_SUCCESS;
auto &CmdListEvents =
UrCompletedEvent->CommandList.value()->second.EventList;
auto CompletedEventIt = std::find(CmdListEvents.begin(),
CmdListEvents.end(), UrCompletedEvent);
if (CompletedEventIt != CmdListEvents.end()) {
// We can cleanup all events prior to the completed event in this
// command list and completed event itself.
// TODO: we can potentially cleanup more events here by finding
// completed events on another command lists, but it is currently not
// implemented.
std::move(std::begin(CmdListEvents), CompletedEventIt + 1,
std::back_inserter(EventListToCleanup));
CmdListEvents.erase(CmdListEvents.begin(), CompletedEventIt + 1);
}
} else {
// Fallback to resetCommandList over all command lists.
for (auto &&It = UrQueue->CommandListMap.begin();
It != UrQueue->CommandListMap.end(); ++It) {
UR_CALL(UrQueue->resetCommandList(It, true, EventListToCleanup,
true /* CheckStatus */));
}
}
}
UR_CALL(CleanupEventListFromResetCmdList(EventListToCleanup, QueueLocked));
return UR_RESULT_SUCCESS;
}
/// @brief Reset signalled command lists in the queue and put them to the cache
/// of command lists. Also cleanup events associated with signalled command
/// lists. Queue must be locked by the caller for modification.
/// @param Queue Queue where we look for signalled command lists and cleanup
/// events.
/// @return PI_SUCCESS if successful, PI error code otherwise.
ur_result_t resetCommandLists(ur_queue_handle_t Queue) {
// Handle immediate command lists here, they don't need to be reset and we
// only need to cleanup events.
if (Queue->UsingImmCmdLists) {
UR_CALL(CleanupEventsInImmCmdLists(Queue, true /*QueueLocked*/,
false /*QueueSynced*/,
nullptr /*CompletedEvent*/));
return UR_RESULT_SUCCESS;
}
// We need events to be cleaned up out of scope where queue is locked to avoid
// nested locks, because event cleanup requires event to be locked. Nested
// locks are hard to control and can cause deadlocks if mutexes are locked in
// different order.
std::vector<ur_event_handle_t> EventListToCleanup;
// We check for command lists that have been already signalled, but have not
// been added to the available list yet. Each command list has a fence
// associated which tracks if a command list has completed dispatch of its
// commands and is ready for reuse. If a command list is found to have been
// signalled, then the command list & fence are reset and command list is
// returned to the command list cache. All events associated with command
// list are cleaned up if command list was reset.
for (auto &&it = Queue->CommandListMap.begin();
it != Queue->CommandListMap.end(); ++it) {
// Immediate commandlists don't use a fence and are handled separately
// above.
assert(it->second.ZeFence != nullptr);
// It is possible that the fence was already noted as signalled and
// reset. In that case the ZeFenceInUse flag will be false.
if (it->second.ZeFenceInUse) {
ze_result_t ZeResult =
ZE_CALL_NOCHECK(zeFenceQueryStatus, (it->second.ZeFence));
if (ZeResult == ZE_RESULT_SUCCESS)
UR_CALL(Queue->resetCommandList(it, true, EventListToCleanup));
}
}
CleanupEventListFromResetCmdList(EventListToCleanup, true /*locked*/);
return UR_RESULT_SUCCESS;
}
namespace ur::level_zero {
ur_result_t urQueueGetInfo(
/// [in] handle of the queue object
ur_queue_handle_t Queue,
/// [in] name of the queue property to query
ur_queue_info_t ParamName,
/// [in] size in bytes of the queue property value provided
size_t ParamValueSize,
/// [out] value of the queue property
void *ParamValue,
/// [out] size in bytes returned in queue property value
size_t *ParamValueSizeRet) {
std::shared_lock<ur_shared_mutex> Lock(Queue->Mutex);
UrReturnHelper ReturnValue(ParamValueSize, ParamValue, ParamValueSizeRet);
// TODO: consider support for queue properties and size
switch ((uint32_t)ParamName) { // cast to avoid warnings on EXT enum values
case UR_QUEUE_INFO_CONTEXT:
return ReturnValue(Queue->Context);
case UR_QUEUE_INFO_DEVICE:
return ReturnValue(Queue->Device);
case UR_QUEUE_INFO_REFERENCE_COUNT:
return ReturnValue(uint32_t{Queue->RefCount.load()});
case UR_QUEUE_INFO_FLAGS:
return ReturnValue(Queue->Properties);
case UR_QUEUE_INFO_SIZE:
case UR_QUEUE_INFO_DEVICE_DEFAULT:
return UR_RESULT_ERROR_UNSUPPORTED_ENUMERATION;
case UR_QUEUE_INFO_EMPTY: {
// We can exit early if we have in-order queue.
if (Queue->isInOrderQueue()) {
if (!Queue->LastCommandEvent)
return ReturnValue(true);
// We can check status of the event only if it isn't discarded otherwise
// it may be reset (because we are free to reuse such events) and
// zeEventQueryStatus will hang.
// TODO: use more robust way to check that ZeEvent is not owned by
// LastCommandEvent.
if (!Queue->LastCommandEvent->IsDiscarded) {
ze_result_t ZeResult = ZE_CALL_NOCHECK(
zeEventQueryStatus, (Queue->LastCommandEvent->ZeEvent));
if (ZeResult == ZE_RESULT_NOT_READY) {
return ReturnValue(false);
} else if (ZeResult != ZE_RESULT_SUCCESS) {
return ze2urResult(ZeResult);
}
return ReturnValue(true);
}
// For immediate command lists we have to check status of the event
// because immediate command lists are not associated with level zero
// queue. Conservatively return false in this case because last event is
// discarded and we can't check its status.
if (Queue->UsingImmCmdLists)
return ReturnValue(false);
}
// If we have any open command list which is not empty then return false
// because it means that there are commands which are not even submitted for
// execution yet.
using IsCopy = bool;
if (Queue->hasOpenCommandList(IsCopy{true}) ||
Queue->hasOpenCommandList(IsCopy{false}))
return ReturnValue(false);
for (const auto &QueueMap :
{Queue->ComputeQueueGroupsByTID, Queue->CopyQueueGroupsByTID}) {
for (const auto &QueueGroup : QueueMap) {
if (Queue->UsingImmCmdLists) {
// Immediate command lists are not associated with any Level Zero
// queue, that's why we have to check status of events in each
// immediate command list. Start checking from the end and exit early
// if some event is not completed.
for (const auto &ImmCmdList : QueueGroup.second.ImmCmdLists) {
if (ImmCmdList == Queue->CommandListMap.end())
continue;
const auto &EventList = ImmCmdList->second.EventList;
for (auto It = EventList.crbegin(); It != EventList.crend(); It++) {
ze_result_t ZeResult =
ZE_CALL_NOCHECK(zeEventQueryStatus, ((*It)->ZeEvent));
if (ZeResult == ZE_RESULT_NOT_READY) {
return ReturnValue(false);
} else if (ZeResult != ZE_RESULT_SUCCESS) {
return ze2urResult(ZeResult);
}
}
}
} else {
for (const auto &ZeQueue : QueueGroup.second.ZeQueues) {
if (!ZeQueue)
continue;
// Provide 0 as the timeout parameter to immediately get the status
// of the Level Zero queue.
ze_result_t ZeResult = ZE_CALL_NOCHECK(zeCommandQueueSynchronize,
(ZeQueue, /* timeout */ 0));
if (ZeResult == ZE_RESULT_NOT_READY) {
return ReturnValue(false);
} else if (ZeResult != ZE_RESULT_SUCCESS) {
return ze2urResult(ZeResult);
}
}
}
}
}
return ReturnValue(true);
}
default:
logger::error(
"Unsupported ParamName in urQueueGetInfo: ParamName=ParamName={}(0x{})",
ParamName, logger::toHex(ParamName));
return UR_RESULT_ERROR_INVALID_ENUMERATION;
}
return UR_RESULT_SUCCESS;
}
// 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 *UrRet = std::getenv("UR_L0_EAGER_INIT");
const char *PiRet = std::getenv("SYCL_EAGER_INIT");
const char *EagerInit = UrRet ? UrRet : (PiRet ? PiRet : nullptr);
return EagerInit ? std::atoi(EagerInit) != 0 : false;
}();
ur_result_t urQueueCreate(
/// [in] handle of the context object
ur_context_handle_t Context,
/// [in] handle of the device object
ur_device_handle_t Device,
/// [in] specifies a list of queue properties and their corresponding
/// values. Each property name is immediately followed by the
/// corresponding desired value. The list is terminated with a 0. If a
/// property value is not specified, then its default value will be
/// used.
const ur_queue_properties_t *Props,
/// [out] pointer to handle of queue object created
ur_queue_handle_t *Queue) {
ur_queue_flags_t Flags{};
if (Props) {
Flags = Props->flags;
}
int ForceComputeIndex = -1; // Use default/round-robin.
if (Props) {
if (Props->pNext) {
const ur_base_properties_t *extendedDesc =
reinterpret_cast<const ur_base_properties_t *>(Props->pNext);
if (extendedDesc->stype == UR_STRUCTURE_TYPE_QUEUE_INDEX_PROPERTIES) {
const ur_queue_index_properties_t *IndexProperties =
reinterpret_cast<const ur_queue_index_properties_t *>(extendedDesc);
ForceComputeIndex = IndexProperties->computeIndex;
}
}
}
UR_ASSERT(Context->isValidDevice(Device), UR_RESULT_ERROR_INVALID_DEVICE);
// Create placeholder queues in the compute queue group.
// Actual L0 queues will be created at first use.
std::vector<ze_command_queue_handle_t> ZeComputeCommandQueues(
Device->QueueGroup[ur_queue_handle_t_::queue_type::Compute]
.ZeProperties.numQueues,
nullptr);
// Create placeholder queues in the copy queue group (main and link
// native groups are combined into one group).
// Actual L0 queues will be created at first use.
size_t NumCopyGroups = 0;
if (Device->hasMainCopyEngine()) {
NumCopyGroups +=
Device->QueueGroup[ur_queue_handle_t_::queue_type::MainCopy]
.ZeProperties.numQueues;
}
if (Device->hasLinkCopyEngine()) {
NumCopyGroups +=
Device->QueueGroup[ur_queue_handle_t_::queue_type::LinkCopy]
.ZeProperties.numQueues;
}
std::vector<ze_command_queue_handle_t> ZeCopyCommandQueues(NumCopyGroups,
nullptr);
try {
*Queue =
new ur_queue_handle_t_(ZeComputeCommandQueues, ZeCopyCommandQueues,
Context, Device, true, Flags, ForceComputeIndex);
} catch (const std::bad_alloc &) {
return UR_RESULT_ERROR_OUT_OF_HOST_MEMORY;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
// Do eager initialization of Level Zero handles on request.
if (doEagerInit) {
auto Q = *Queue;
// Creates said number of command-lists.
auto warmupQueueGroup = [Q](bool UseCopyEngine,
uint32_t RepeatCount) -> ur_result_t {
ur_command_list_ptr_t CommandList;
while (RepeatCount--) {
if (Q->UsingImmCmdLists) {
CommandList = Q->getQueueGroup(UseCopyEngine).getImmCmdList();
} else {
// Heuristically create some number of regular command-list to reuse.
for (int I = 0; I < 10; ++I) {
UR_CALL(Q->createCommandList(UseCopyEngine, CommandList));
// Immediately return them to the cache of available command-lists.
std::vector<ur_event_handle_t> EventsUnused;
UR_CALL(Q->resetCommandList(CommandList, true /* MakeAvailable */,
EventsUnused));
}
}
}
return UR_RESULT_SUCCESS;
};
// Create as many command-lists as there are queues in the group.
// With this the underlying round-robin logic would initialize all
// native queues, and create command-lists and their fences.
// At this point only the thread creating the queue will have associated
// command-lists. Other threads have not accessed the queue yet. So we can
// only warmup the initial thread's command-lists.
const auto &QueueGroup = Q->ComputeQueueGroupsByTID.get();
UR_CALL(warmupQueueGroup(false, QueueGroup.UpperIndex -
QueueGroup.LowerIndex + 1));
if (Q->useCopyEngine()) {
const auto &QueueGroup = Q->CopyQueueGroupsByTID.get();
UR_CALL(warmupQueueGroup(true, QueueGroup.UpperIndex -
QueueGroup.LowerIndex + 1));
}
// TODO: warmup event pools. Both host-visible and device-only.
}
return UR_RESULT_SUCCESS;
}
ur_result_t urQueueRetain(
/// [in] handle of the queue object to get access
ur_queue_handle_t Queue) {
{
std::scoped_lock<ur_shared_mutex> Lock(Queue->Mutex);
Queue->RefCountExternal++;
}
Queue->RefCount.increment();
return UR_RESULT_SUCCESS;
}
ur_result_t urQueueRelease(
/// [in] handle of the queue object to release
ur_queue_handle_t Queue) {
std::vector<ur_event_handle_t> EventListToCleanup;
{
std::scoped_lock<ur_shared_mutex> Lock(Queue->Mutex);
if ((--Queue->RefCountExternal) != 0) {
// When an External Reference exists one still needs to decrement the
// internal reference count. When the External Reference count == 0, then
// cleanup of the queue begins and the final decrement of the internal
// reference count is completed.
static_cast<void>(Queue->RefCount.decrementAndTest());
return UR_RESULT_SUCCESS;
}
Queue->Context->AsyncPool.cleanupPoolsForQueue(Queue);
// When external reference count goes to zero it is still possible
// that internal references still exists, e.g. command-lists that
// are not yet completed. So do full queue synchronization here
// and perform proper cleanup.
//
// It is possible to get to here and still have an open command list
// if no wait or finish ever occurred for this queue.
auto Res = Queue->executeAllOpenCommandLists();
// Make sure all commands get executed.
if (Res == UR_RESULT_SUCCESS)
UR_CALL(Queue->synchronize());
// Destroy all the fences created associated with this queue.
for (auto it = Queue->CommandListMap.begin();
it != Queue->CommandListMap.end(); ++it) {
// This fence wasn't yet signalled when we polled it for recycling
// the command-list, so need to release the command-list too.
// For immediate commandlists we don't need to do an L0 reset of the
// commandlist but do need to do event cleanup which is also in the
// resetCommandList function.
// If the fence is a nullptr we are using immediate commandlists,
// otherwise regular commandlists which use a fence.
if (it->second.ZeFence == nullptr || it->second.ZeFenceInUse) {
// Destroy completions batches if they are being used. This needs
// to happen prior to resetCommandList so that all events are
// checked.
it->second.completions.reset();
Queue->resetCommandList(it, true, EventListToCleanup);
}
// TODO: remove "if" when the problem is fixed in the level zero
// runtime. Destroy only if a queue is healthy. Destroying a fence may
// cause a hang otherwise.
// If the fence is a nullptr we are using immediate commandlists.
if (Queue->Healthy && it->second.ZeFence != nullptr) {
auto ZeResult = ZE_CALL_NOCHECK(zeFenceDestroy, (it->second.ZeFence));
// Gracefully handle the case that L0 was already unloaded.
if (ZeResult && ZeResult != ZE_RESULT_ERROR_UNINITIALIZED)
return ze2urResult(ZeResult);
}
if (Queue->UsingImmCmdLists && Queue->OwnZeCommandQueue) {
std::scoped_lock<ur_mutex> Lock(
Queue->Context->ZeCommandListCacheMutex);
const ur_command_list_info_t &MapEntry = it->second;
if (MapEntry.CanReuse) {
// Add commandlist to the cache for future use.
// It will be deleted when the context is destroyed.
auto &ZeCommandListCache =
MapEntry.isCopy(Queue)
? Queue->Context
->ZeCopyCommandListCache[Queue->Device->ZeDevice]
: Queue->Context
->ZeComputeCommandListCache[Queue->Device->ZeDevice];
struct l0_command_list_cache_info ListInfo;
ListInfo.ZeQueueDesc = it->second.ZeQueueDesc;
ListInfo.InOrderList = it->second.IsInOrderList;
ListInfo.IsImmediate = it->second.IsImmediate;
ZeCommandListCache.push_back({it->first, ListInfo});
} else {
// A non-reusable comamnd list that came from a make_queue call is
// destroyed since it cannot be recycled.
ze_command_list_handle_t ZeCommandList = it->first;
if (ZeCommandList) {
ZE2UR_CALL(zeCommandListDestroy, (ZeCommandList));
}
}
}
}
Queue->CommandListMap.clear();
}
for (auto &Event : EventListToCleanup) {
// We don't need to synchronize the events since the queue
// synchronized above already does that.
{
std::scoped_lock<ur_shared_mutex> EventLock(Event->Mutex);
Event->Completed = true;
}
UR_CALL(CleanupCompletedEvent(Event, false /*QueueLocked*/,
false /*SetEventCompleted*/));
// This event was removed from the command list, so decrement ref count
// (it was incremented when they were added to the command list).
UR_CALL(urEventReleaseInternal(reinterpret_cast<ur_event_handle_t>(Event)));
}
UR_CALL(urQueueReleaseInternal(Queue));
return UR_RESULT_SUCCESS;
}
ur_result_t urQueueGetNativeHandle(
/// [in] handle of the queue.
ur_queue_handle_t Queue, ur_queue_native_desc_t *Desc,
/// [out] a pointer to the native handle of the queue.
ur_native_handle_t *NativeQueue) {
// Lock automatically releases when this goes out of scope.
std::shared_lock<ur_shared_mutex> lock(Queue->Mutex);
int32_t NativeHandleDesc{};
// Get handle to this thread's queue group.
auto &QueueGroup = Queue->getQueueGroup(false /*compute*/);
if (Queue->UsingImmCmdLists) {
auto ZeCmdList = ur_cast<ze_command_list_handle_t *>(NativeQueue);
// Extract the Level Zero command list handle from the given PI queue
*ZeCmdList = QueueGroup.getImmCmdList()->first;
// TODO: How to pass this up in the urQueueGetNativeHandle interface?
NativeHandleDesc = true;
} else {
auto ZeQueue = ur_cast<ze_command_queue_handle_t *>(NativeQueue);
// Extract a Level Zero compute queue handle from the given PI queue
auto &QueueGroup = Queue->getQueueGroup(false /*compute*/);
uint32_t QueueGroupOrdinalUnused;
*ZeQueue = QueueGroup.getZeQueue(&QueueGroupOrdinalUnused);
// TODO: How to pass this up in the urQueueGetNativeHandle interface?
NativeHandleDesc = false;
}
if (Desc && Desc->pNativeData)
*(reinterpret_cast<int32_t *>((Desc->pNativeData))) = NativeHandleDesc;
return UR_RESULT_SUCCESS;
}
ur_result_t urQueueCreateWithNativeHandle(
/// [in] the native handle of the queue.
ur_native_handle_t NativeQueue,
/// [in] handle of the context object
ur_context_handle_t Context,
ur_device_handle_t Device, ///
const ur_queue_native_properties_t
*NativeProperties, ///
/// [out] pointer to the handle of the queue object
/// created.
ur_queue_handle_t *RetQueue) {
bool OwnNativeHandle = false;
ur_queue_flags_t Flags{};
int32_t NativeHandleDesc{};
if (NativeProperties) {
OwnNativeHandle = NativeProperties->isNativeHandleOwned;
void *pNext = NativeProperties->pNext;
while (pNext) {
const ur_base_properties_t *extendedProperties =
reinterpret_cast<const ur_base_properties_t *>(pNext);
if (extendedProperties->stype == UR_STRUCTURE_TYPE_QUEUE_PROPERTIES) {
const ur_queue_properties_t *UrProperties =
reinterpret_cast<const ur_queue_properties_t *>(extendedProperties);
Flags = UrProperties->flags;
} else if (extendedProperties->stype ==
UR_STRUCTURE_TYPE_QUEUE_NATIVE_DESC) {
const ur_queue_native_desc_t *UrNativeDesc =
reinterpret_cast<const ur_queue_native_desc_t *>(
extendedProperties);
if (UrNativeDesc->pNativeData)
NativeHandleDesc =
*(reinterpret_cast<int32_t *>((UrNativeDesc->pNativeData)));
}
pNext = extendedProperties->pNext;
}
}
// Get the device handle from first device in the platform
// Maybe this is not completely correct.
uint32_t NumEntries = 1;
ur_platform_handle_t Platform{};
ur_adapter_handle_t AdapterHandle = GlobalAdapter;
UR_CALL(ur::level_zero::urPlatformGet(&AdapterHandle, 1, NumEntries,
&Platform, nullptr));
ur_device_handle_t UrDevice = Device;
if (UrDevice == nullptr) {
UR_CALL(ur::level_zero::urDeviceGet(Platform, UR_DEVICE_TYPE_GPU,
NumEntries, &UrDevice, nullptr));
}
// The NativeHandleDesc has value if if the native handle is an immediate
// command list.
if (NativeHandleDesc == 1) {
std::vector<ze_command_queue_handle_t> ComputeQueues{nullptr};
std::vector<ze_command_queue_handle_t> CopyQueues;
try {
ur_queue_handle_t_ *Queue = new ur_queue_handle_t_(
ComputeQueues, CopyQueues, Context, UrDevice, OwnNativeHandle, Flags);
*RetQueue = reinterpret_cast<ur_queue_handle_t>(Queue);
(*RetQueue)->IsInteropNativeHandle = true;
} catch (const std::bad_alloc &) {
return UR_RESULT_ERROR_OUT_OF_RESOURCES;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
auto &InitialGroup = (*RetQueue)->ComputeQueueGroupsByTID.begin()->second;
InitialGroup.setImmCmdList(*RetQueue,
ur_cast<ze_command_list_handle_t>(NativeQueue));
} else {
auto ZeQueue = ur_cast<ze_command_queue_handle_t>(NativeQueue);
// Assume this is the "0" index queue in the compute command-group.
std::vector<ze_command_queue_handle_t> ZeQueues{ZeQueue};
// TODO: see what we can do to correctly initialize PI queue for
// compute vs. copy Level-Zero queue. Currently we will send
// all commands to the "ZeQueue".
std::vector<ze_command_queue_handle_t> ZeroCopyQueues;
try {
ur_queue_handle_t_ *Queue = new ur_queue_handle_t_(
ZeQueues, ZeroCopyQueues, Context, UrDevice, OwnNativeHandle, Flags);
*RetQueue = reinterpret_cast<ur_queue_handle_t>(Queue);
} catch (const std::bad_alloc &) {
return UR_RESULT_ERROR_OUT_OF_RESOURCES;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
}
(*RetQueue)->UsingImmCmdLists = (NativeHandleDesc == 1);
return UR_RESULT_SUCCESS;
}
ur_result_t urQueueFinish(
/// [in] handle of the queue to be finished.
ur_queue_handle_t Queue) {
if (Queue->UsingImmCmdLists) {
// Lock automatically releases when this goes out of scope.
std::scoped_lock<ur_shared_mutex> Lock(Queue->Mutex);
UR_CALL(Queue->synchronize());
} else {
std::unique_lock<ur_shared_mutex> Lock(Queue->Mutex);
std::vector<ze_command_queue_handle_t> ZeQueues;
// execute any command list that may still be open.
UR_CALL(Queue->executeAllOpenCommandLists());
// Make a copy of queues to sync and release the lock.
for (auto &QueueMap :
{Queue->ComputeQueueGroupsByTID, Queue->CopyQueueGroupsByTID})
for (auto &QueueGroup : QueueMap)
std::copy(QueueGroup.second.ZeQueues.begin(),
QueueGroup.second.ZeQueues.end(),
std::back_inserter(ZeQueues));
// Remember the last command's event.
auto LastCommandEvent = Queue->LastCommandEvent;
// Don't hold a lock to the queue's mutex while waiting.
// This allows continue working with the queue from other threads.
// TODO: this currently exhibits some issues in the driver, so
// we control this with an env var. Remove this control when
// we settle one way or the other.
const char *UrRet = std::getenv("UR_L0_QUEUE_FINISH_HOLD_LOCK");
const char *PiRet =
std::getenv("SYCL_PI_LEVEL_ZERO_QUEUE_FINISH_HOLD_LOCK");
static bool HoldLock =
UrRet ? std::stoi(UrRet) : (PiRet ? std::stoi(PiRet) : 0);
if (!HoldLock) {
Lock.unlock();
}
for (auto &ZeQueue : ZeQueues) {
if (ZeQueue)
ZE2UR_CALL(zeHostSynchronize, (ZeQueue));
}
// Prevent unneeded already finished events to show up in the wait list.
// We can only do so if nothing else was submitted to the queue
// while we were synchronizing it.
if (!HoldLock) {
std::scoped_lock<ur_shared_mutex> Lock(Queue->Mutex);
if (LastCommandEvent == Queue->LastCommandEvent) {
Queue->LastCommandEvent = nullptr;
}
} else {
Queue->LastCommandEvent = nullptr;
}
}
// Reset signalled command lists and return them back to the cache of
// available command lists. Events in the immediate command lists are cleaned
// up in synchronize().
if (!Queue->UsingImmCmdLists) {
std::unique_lock<ur_shared_mutex> Lock(Queue->Mutex);
resetCommandLists(Queue);
}
Queue->Context->AsyncPool.cleanupPoolsForQueue(Queue);
return UR_RESULT_SUCCESS;
}
ur_result_t urQueueFlush(
/// [in] handle of the queue to be flushed.
ur_queue_handle_t Queue) {
std::scoped_lock<ur_shared_mutex> Lock(Queue->Mutex);
return Queue->executeAllOpenCommandLists();
}
ur_result_t urEnqueueKernelLaunchCustomExp(
ur_queue_handle_t hQueue, ur_kernel_handle_t hKernel, uint32_t workDim,
const size_t *pGlobalWorkOffset, const size_t *pGlobalWorkSize,
const size_t *pLocalWorkSize, uint32_t numPropsInLaunchPropList,
const ur_exp_launch_property_t *launchPropList,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
std::ignore = hQueue;
std::ignore = hKernel;
std::ignore = workDim;
std::ignore = pGlobalWorkOffset;
std::ignore = pGlobalWorkSize;
std::ignore = pLocalWorkSize;
std::ignore = numPropsInLaunchPropList;
std::ignore = launchPropList;
std::ignore = numEventsInWaitList;
std::ignore = phEventWaitList;
std::ignore = phEvent;
logger::error("[UR][L0] {} function not implemented!",
"{} function not implemented!", __FUNCTION__);
return UR_RESULT_ERROR_UNSUPPORTED_FEATURE;
}
} // namespace ur::level_zero
// 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.
uint32_t Size{0};
// If doing dynamic batching, specifies start batch size.
uint32_t DynamicSizeStart{4};
// The maximum size for dynamic batch.
uint32_t DynamicSizeMax{64};
// The step size for dynamic batch increases.
uint32_t DynamicSizeStep{1};
// Thresholds for when increase batch size (number of closed early is small
// and number of closed full is high).
uint32_t NumTimesClosedEarlyThreshold{3};
uint32_t NumTimesClosedFullThreshold{8};
// Tells the starting size of a batch.
uint32_t 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 char *UrRet = nullptr;
const char *PiRet = nullptr;
if (IsCopy) {
UrRet = std::getenv("UR_L0_COPY_BATCH_SIZE");
PiRet = std::getenv("SYCL_PI_LEVEL_ZERO_COPY_BATCH_SIZE");
} else {
UrRet = std::getenv("UR_L0_BATCH_SIZE");
PiRet = std::getenv("SYCL_PI_LEVEL_ZERO_BATCH_SIZE");
}
const char *BatchSizeStr = UrRet ? UrRet : (PiRet ? PiRet : nullptr);
if (BatchSizeStr) {
int32_t 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) {