-
Notifications
You must be signed in to change notification settings - Fork 769
/
Copy pathenqueue.cpp
1927 lines (1674 loc) · 72.9 KB
/
enqueue.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
//===--------- enqueue.cpp - HIP 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 "enqueue.hpp"
#include "common.hpp"
#include "context.hpp"
#include "event.hpp"
#include "kernel.hpp"
#include "logger/ur_logger.hpp"
#include "memory.hpp"
#include "queue.hpp"
#include "ur_api.h"
#include <ur/ur.hpp>
extern size_t imageElementByteSize(hipArray_Format ArrayFormat);
ur_result_t enqueueEventsWait(ur_queue_handle_t Queue, hipStream_t Stream,
uint32_t NumEventsInWaitList,
const ur_event_handle_t *EventWaitList) {
if (!EventWaitList) {
return UR_RESULT_SUCCESS;
}
try {
UR_CHECK_ERROR(forLatestEvents(
EventWaitList, NumEventsInWaitList,
[Stream, Queue](ur_event_handle_t Event) -> ur_result_t {
ScopedDevice Active(Queue->getDevice());
if (Event->isCompleted() || Event->getStream() == Stream) {
return UR_RESULT_SUCCESS;
} else {
UR_CHECK_ERROR(hipStreamWaitEvent(Stream, Event->get(), 0));
return UR_RESULT_SUCCESS;
}
}));
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
return UR_RESULT_SUCCESS;
}
// Determine local work sizes that result in uniform work groups.
// The default threadsPerBlock only require handling the first work_dim
// dimension.
void guessLocalWorkSize(ur_device_handle_t Device, size_t *ThreadsPerBlock,
const size_t *GlobalWorkSize, const uint32_t WorkDim,
const size_t MaxThreadsPerBlock[3]) {
assert(ThreadsPerBlock != nullptr);
assert(GlobalWorkSize != nullptr);
// FIXME: The below assumes a three dimensional range but this is not
// guaranteed by UR.
size_t GlobalSizeNormalized[3] = {1, 1, 1};
for (uint32_t i = 0; i < WorkDim; i++) {
GlobalSizeNormalized[i] = GlobalWorkSize[i];
}
size_t MaxBlockDim[3];
MaxBlockDim[0] = MaxThreadsPerBlock[0];
MaxBlockDim[1] = Device->getMaxBlockDimY();
MaxBlockDim[2] = Device->getMaxBlockDimZ();
roundToHighestFactorOfGlobalSizeIn3d(ThreadsPerBlock, GlobalSizeNormalized,
MaxBlockDim, MaxThreadsPerBlock[0]);
}
namespace {
ur_result_t setHipMemAdvise(const void *DevPtr, const size_t Size,
ur_usm_advice_flags_t URAdviceFlags,
hipDevice_t Device) {
// Handle unmapped memory advice flags
if (URAdviceFlags &
(UR_USM_ADVICE_FLAG_SET_NON_ATOMIC_MOSTLY |
UR_USM_ADVICE_FLAG_CLEAR_NON_ATOMIC_MOSTLY |
UR_USM_ADVICE_FLAG_BIAS_CACHED | UR_USM_ADVICE_FLAG_BIAS_UNCACHED
#if !defined(__HIP_PLATFORM_AMD__)
| UR_USM_ADVICE_FLAG_SET_NON_COHERENT_MEMORY |
UR_USM_ADVICE_FLAG_CLEAR_NON_COHERENT_MEMORY
#endif
)) {
return UR_RESULT_ERROR_INVALID_ENUMERATION;
}
using ur_to_hip_advice_t = std::pair<ur_usm_advice_flags_t, hipMemoryAdvise>;
#if defined(__HIP_PLATFORM_AMD__)
constexpr size_t DeviceFlagCount = 8;
#else
constexpr size_t DeviceFlagCount = 6;
#endif
static constexpr std::array<ur_to_hip_advice_t, DeviceFlagCount>
URToHIPMemAdviseDeviceFlags{
std::make_pair(UR_USM_ADVICE_FLAG_SET_READ_MOSTLY,
hipMemAdviseSetReadMostly),
std::make_pair(UR_USM_ADVICE_FLAG_CLEAR_READ_MOSTLY,
hipMemAdviseUnsetReadMostly),
std::make_pair(UR_USM_ADVICE_FLAG_SET_PREFERRED_LOCATION,
hipMemAdviseSetPreferredLocation),
std::make_pair(UR_USM_ADVICE_FLAG_CLEAR_PREFERRED_LOCATION,
hipMemAdviseUnsetPreferredLocation),
std::make_pair(UR_USM_ADVICE_FLAG_SET_ACCESSED_BY_DEVICE,
hipMemAdviseSetAccessedBy),
std::make_pair(UR_USM_ADVICE_FLAG_CLEAR_ACCESSED_BY_DEVICE,
hipMemAdviseUnsetAccessedBy),
#if defined(__HIP_PLATFORM_AMD__)
std::make_pair(UR_USM_ADVICE_FLAG_SET_NON_COHERENT_MEMORY,
hipMemAdviseSetCoarseGrain),
std::make_pair(UR_USM_ADVICE_FLAG_CLEAR_NON_COHERENT_MEMORY,
hipMemAdviseUnsetCoarseGrain),
#endif
};
for (const auto &[URAdvice, HIPAdvice] : URToHIPMemAdviseDeviceFlags) {
if (URAdviceFlags & URAdvice) {
UR_CHECK_ERROR(hipMemAdvise(DevPtr, Size, HIPAdvice, Device));
}
}
static constexpr std::array<ur_to_hip_advice_t, 4> URToHIPMemAdviseHostFlags{
std::make_pair(UR_USM_ADVICE_FLAG_SET_PREFERRED_LOCATION_HOST,
hipMemAdviseSetPreferredLocation),
std::make_pair(UR_USM_ADVICE_FLAG_CLEAR_PREFERRED_LOCATION_HOST,
hipMemAdviseUnsetPreferredLocation),
std::make_pair(UR_USM_ADVICE_FLAG_SET_ACCESSED_BY_HOST,
hipMemAdviseSetAccessedBy),
std::make_pair(UR_USM_ADVICE_FLAG_CLEAR_ACCESSED_BY_HOST,
hipMemAdviseUnsetAccessedBy),
};
for (const auto &[URAdvice, HIPAdvice] : URToHIPMemAdviseHostFlags) {
if (URAdviceFlags & URAdvice) {
UR_CHECK_ERROR(hipMemAdvise(DevPtr, Size, HIPAdvice, hipCpuDeviceId));
}
}
return UR_RESULT_SUCCESS;
}
} // namespace
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferWrite(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, bool blockingWrite,
size_t offset, size_t size, const void *pSrc, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
UR_ASSERT(hBuffer->isBuffer(), UR_RESULT_ERROR_INVALID_MEM_OBJECT);
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
hBuffer->setLastQueueWritingToMemObj(hQueue);
try {
ScopedDevice Active(hQueue->getDevice());
hipStream_t HIPStream = hQueue->getNextTransferStream();
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_WRITE, hQueue, HIPStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
UR_CHECK_ERROR(
hipMemcpyHtoDAsync(std::get<BufferMem>(hBuffer->Mem)
.getPtrWithOffset(hQueue->getDevice(), offset),
const_cast<void *>(pSrc), size, HIPStream));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
}
if (blockingWrite) {
UR_CHECK_ERROR(hipStreamSynchronize(HIPStream));
}
if (phEvent) {
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferRead(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, bool blockingRead,
size_t offset, size_t size, void *pDst, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
UR_ASSERT(hBuffer->isBuffer(), UR_RESULT_ERROR_INVALID_MEM_OBJECT);
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
// Note that this entry point may be called on a queue that may not be the
// last queue to write to the MemBuffer, meaning we must perform the copy
// from a different device
if (hBuffer->LastQueueWritingToMemObj &&
hBuffer->LastQueueWritingToMemObj->getDevice() != hQueue->getDevice()) {
hQueue = hBuffer->LastQueueWritingToMemObj;
}
auto Device = hQueue->getDevice();
ScopedDevice Active(Device);
hipStream_t HIPStream = hQueue->getNextTransferStream();
// Use the default stream if copying from another device
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_READ, hQueue, HIPStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
// Copying from the device with latest version of memory, not necessarily
// the device associated with the Queue
UR_CHECK_ERROR(hipMemcpyDtoHAsync(
pDst,
std::get<BufferMem>(hBuffer->Mem).getPtrWithOffset(Device, offset),
size, HIPStream));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
}
if (blockingRead) {
UR_CHECK_ERROR(hipStreamSynchronize(HIPStream));
}
if (phEvent) {
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t err) {
return err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueKernelLaunch(
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 numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
UR_ASSERT(hQueue->getContext() == hKernel->getContext(),
UR_RESULT_ERROR_INVALID_QUEUE);
UR_ASSERT(workDim > 0, UR_RESULT_ERROR_INVALID_WORK_DIMENSION);
UR_ASSERT(workDim < 4, UR_RESULT_ERROR_INVALID_WORK_DIMENSION);
// Early exit for zero size range kernel
if (*pGlobalWorkSize == 0) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
// Set the number of threads per block to the number of threads per warp
// by default unless user has provided a better number
size_t ThreadsPerBlock[3] = {32u, 1u, 1u};
size_t BlocksPerGrid[3] = {1u, 1u, 1u};
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
ur_device_handle_t Dev = hQueue->getDevice();
hipFunction_t HIPFunc = hKernel->get();
UR_CHECK_ERROR(setKernelParams(Dev, workDim, pGlobalWorkOffset,
pGlobalWorkSize, pLocalWorkSize, hKernel,
HIPFunc, ThreadsPerBlock, BlocksPerGrid));
ScopedDevice Active(Dev);
uint32_t StreamToken;
ur_stream_guard Guard;
hipStream_t HIPStream = hQueue->getNextComputeStream(
numEventsInWaitList, phEventWaitList, Guard, &StreamToken);
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
// For memory migration across devices in the same context
if (hQueue->getContext()->Devices.size() > 1) {
for (auto &MemArg : hKernel->Args.MemObjArgs) {
enqueueMigrateMemoryToDeviceIfNeeded(MemArg.Mem, hQueue->getDevice(),
HIPStream);
if (MemArg.AccessFlags &
(UR_MEM_FLAG_READ_WRITE | UR_MEM_FLAG_WRITE_ONLY)) {
MemArg.Mem->setLastQueueWritingToMemObj(hQueue);
}
}
}
auto ArgPointers = hKernel->getArgPointers();
// If migration of mem across buffer is needed, an event must be associated
// with this command, implicitly if phEvent is nullptr
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_KERNEL_LAUNCH, hQueue, HIPStream, StreamToken));
UR_CHECK_ERROR(RetImplEvent->start());
}
UR_CHECK_ERROR(hipModuleLaunchKernel(
HIPFunc, BlocksPerGrid[0], BlocksPerGrid[1], BlocksPerGrid[2],
ThreadsPerBlock[0], ThreadsPerBlock[1], ThreadsPerBlock[2],
hKernel->getLocalSize(), HIPStream, ArgPointers.data(), nullptr));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t err) {
return err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueCooperativeKernelLaunchExp(
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 numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
return urEnqueueKernelLaunch(hQueue, hKernel, workDim, pGlobalWorkOffset,
pGlobalWorkSize, pLocalWorkSize,
numEventsInWaitList, phEventWaitList, phEvent);
}
/// Enqueues a wait on the given queue for all events.
/// See \ref enqueueEventWait
///
/// Currently queues are represented by a single in-order stream, therefore
/// every command is an implicit barrier and so urEnqueueEventWait has the
/// same behavior as urEnqueueEventWaitWithBarrier. So urEnqueueEventWait can
/// just call urEnqueueEventWaitWithBarrier.
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueEventsWait(
ur_queue_handle_t hQueue, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
/// Enqueues a wait on the given queue for all specified events.
/// See \ref enqueueEventWaitWithBarrier
///
/// If the events list is empty, the enqueued wait will wait on all previous
/// events in the queue.
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueEventsWaitWithBarrier(
ur_queue_handle_t hQueue, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
try {
ScopedDevice Active(hQueue->getDevice());
uint32_t StreamToken;
ur_stream_guard Guard;
hipStream_t HIPStream = hQueue->getNextComputeStream(
numEventsInWaitList,
reinterpret_cast<const ur_event_handle_t *>(phEventWaitList), Guard,
&StreamToken);
{
std::lock_guard<std::mutex> Guard(hQueue->BarrierMutex);
if (hQueue->BarrierEvent == nullptr) {
UR_CHECK_ERROR(hipEventCreate(&hQueue->BarrierEvent));
}
if (numEventsInWaitList == 0) { // wait on all work
if (hQueue->BarrierTmpEvent == nullptr) {
UR_CHECK_ERROR(hipEventCreate(&hQueue->BarrierTmpEvent));
}
hQueue->syncStreams(
[HIPStream, TmpEvent = hQueue->BarrierTmpEvent](hipStream_t S) {
if (HIPStream != S) {
UR_CHECK_ERROR(hipEventRecord(TmpEvent, S));
UR_CHECK_ERROR(hipStreamWaitEvent(HIPStream, TmpEvent, 0));
}
});
} else { // wait just on given events
forLatestEvents(
reinterpret_cast<const ur_event_handle_t *>(phEventWaitList),
numEventsInWaitList,
[HIPStream](ur_event_handle_t Event) -> ur_result_t {
if (Event->getQueue()->hasBeenSynchronized(
Event->getComputeStreamToken())) {
return UR_RESULT_SUCCESS;
} else {
UR_CHECK_ERROR(hipStreamWaitEvent(HIPStream, Event->get(), 0));
return UR_RESULT_SUCCESS;
}
});
}
UR_CHECK_ERROR(hipEventRecord(hQueue->BarrierEvent, HIPStream));
for (unsigned int i = 0; i < hQueue->ComputeAppliedBarrier.size(); i++) {
hQueue->ComputeAppliedBarrier[i] = false;
}
for (unsigned int i = 0; i < hQueue->TransferAppliedBarrier.size(); i++) {
hQueue->TransferAppliedBarrier[i] = false;
}
}
if (phEvent) {
*phEvent = ur_event_handle_t_::makeNative(
UR_COMMAND_EVENTS_WAIT_WITH_BARRIER, hQueue, HIPStream, StreamToken);
UR_CHECK_ERROR((*phEvent)->start());
UR_CHECK_ERROR((*phEvent)->record());
}
return UR_RESULT_SUCCESS;
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
}
UR_APIEXPORT ur_result_t urEnqueueEventsWaitWithBarrierExt(
ur_queue_handle_t hQueue, const ur_exp_enqueue_ext_properties_t *,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
return urEnqueueEventsWaitWithBarrier(hQueue, numEventsInWaitList,
phEventWaitList, phEvent);
}
/// General 3D memory copy operation.
/// This function requires the corresponding HIP context to be at the top of
/// the context stack
/// If the source and/or destination is on the device, SrcPtr and/or DstPtr
/// must be a pointer to a hipDevPtr
static ur_result_t commonEnqueueMemBufferCopyRect(
hipStream_t HipStream, ur_rect_region_t Region, const void *SrcPtr,
const hipMemoryType SrcType, ur_rect_offset_t SrcOffset, size_t SrcRowPitch,
size_t SrcSlicePitch, void *DstPtr, const hipMemoryType DstType,
ur_rect_offset_t DstOffset, size_t DstRowPitch, size_t DstSlicePitch) {
assert(SrcType == hipMemoryTypeDevice || SrcType == hipMemoryTypeHost);
assert(DstType == hipMemoryTypeDevice || DstType == hipMemoryTypeHost);
SrcRowPitch = (!SrcRowPitch) ? Region.width : SrcRowPitch;
SrcSlicePitch =
(!SrcSlicePitch) ? (Region.height * SrcRowPitch) : SrcSlicePitch;
DstRowPitch = (!DstRowPitch) ? Region.width : DstRowPitch;
DstSlicePitch =
(!DstSlicePitch) ? (Region.height * DstRowPitch) : DstSlicePitch;
HIP_MEMCPY3D Params;
Params.WidthInBytes = Region.width;
Params.Height = Region.height;
Params.Depth = Region.depth;
Params.srcMemoryType = SrcType;
Params.srcDevice = SrcType == hipMemoryTypeDevice
? *static_cast<const hipDeviceptr_t *>(SrcPtr)
: 0;
Params.srcHost = SrcType == hipMemoryTypeHost ? SrcPtr : nullptr;
Params.srcXInBytes = SrcOffset.x;
Params.srcY = SrcOffset.y;
Params.srcZ = SrcOffset.z;
Params.srcPitch = SrcRowPitch;
Params.srcHeight = SrcSlicePitch / SrcRowPitch;
Params.dstMemoryType = DstType;
Params.dstDevice = DstType == hipMemoryTypeDevice
? *reinterpret_cast<hipDeviceptr_t *>(DstPtr)
: 0;
Params.dstHost = DstType == hipMemoryTypeHost ? DstPtr : nullptr;
Params.dstXInBytes = DstOffset.x;
Params.dstY = DstOffset.y;
Params.dstZ = DstOffset.z;
Params.dstPitch = DstRowPitch;
Params.dstHeight = DstSlicePitch / DstRowPitch;
UR_CHECK_ERROR(hipDrvMemcpy3DAsync(&Params, HipStream));
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferReadRect(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, bool blockingRead,
ur_rect_offset_t bufferOrigin, ur_rect_offset_t hostOrigin,
ur_rect_region_t region, size_t bufferRowPitch, size_t bufferSlicePitch,
size_t hostRowPitch, size_t hostSlicePitch, void *pDst,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
// Note that this entry point may be called on a queue that may not be the
// last queue to write to the MemBuffer, meaning we must perform the copy
// from a different device
if (hBuffer->LastQueueWritingToMemObj &&
hBuffer->LastQueueWritingToMemObj->getDevice() != hQueue->getDevice()) {
hQueue = hBuffer->LastQueueWritingToMemObj;
}
auto Device = hQueue->getDevice();
ScopedDevice Active(Device);
hipStream_t HIPStream = hQueue->getNextTransferStream();
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_READ_RECT, hQueue, HIPStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
void *DevPtr = std::get<BufferMem>(hBuffer->Mem).getVoid(Device);
UR_CHECK_ERROR(commonEnqueueMemBufferCopyRect(
HIPStream, region, &DevPtr, hipMemoryTypeDevice, bufferOrigin,
bufferRowPitch, bufferSlicePitch, pDst, hipMemoryTypeHost, hostOrigin,
hostRowPitch, hostSlicePitch));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
}
if (blockingRead) {
UR_CHECK_ERROR(hipStreamSynchronize(HIPStream));
}
if (phEvent) {
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferWriteRect(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, bool blockingWrite,
ur_rect_offset_t bufferOrigin, ur_rect_offset_t hostOrigin,
ur_rect_region_t region, size_t bufferRowPitch, size_t bufferSlicePitch,
size_t hostRowPitch, size_t hostSlicePitch, void *pSrc,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
void *DevPtr = std::get<BufferMem>(hBuffer->Mem).getVoid(hQueue->getDevice());
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
hBuffer->setLastQueueWritingToMemObj(hQueue);
try {
ScopedDevice Active(hQueue->getDevice());
hipStream_t HIPStream = hQueue->getNextTransferStream();
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_WRITE, hQueue, HIPStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
UR_CHECK_ERROR(commonEnqueueMemBufferCopyRect(
HIPStream, region, pSrc, hipMemoryTypeHost, hostOrigin, hostRowPitch,
hostSlicePitch, &DevPtr, hipMemoryTypeDevice, bufferOrigin,
bufferRowPitch, bufferSlicePitch));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
}
if (blockingWrite) {
UR_CHECK_ERROR(hipStreamSynchronize(HIPStream));
}
if (phEvent) {
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferCopy(
ur_queue_handle_t hQueue, ur_mem_handle_t hBufferSrc,
ur_mem_handle_t hBufferDst, size_t srcOffset, size_t dstOffset, size_t size,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
UR_ASSERT(size + srcOffset <= std::get<BufferMem>(hBufferSrc->Mem).getSize(),
UR_RESULT_ERROR_INVALID_SIZE);
UR_ASSERT(size + dstOffset <= std::get<BufferMem>(hBufferDst->Mem).getSize(),
UR_RESULT_ERROR_INVALID_SIZE);
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
ScopedDevice Active(hQueue->getDevice());
auto Stream = hQueue->getNextTransferStream();
if (phEventWaitList) {
UR_CHECK_ERROR(enqueueEventsWait(hQueue, Stream, numEventsInWaitList,
phEventWaitList));
}
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_COPY, hQueue, Stream));
UR_CHECK_ERROR(RetImplEvent->start());
}
auto Src = std::get<BufferMem>(hBufferSrc->Mem)
.getPtrWithOffset(hQueue->getDevice(), srcOffset);
auto Dst = std::get<BufferMem>(hBufferDst->Mem)
.getPtrWithOffset(hQueue->getDevice(), dstOffset);
UR_CHECK_ERROR(hipMemcpyDtoDAsync(Dst, Src, size, Stream));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferCopyRect(
ur_queue_handle_t hQueue, ur_mem_handle_t hBufferSrc,
ur_mem_handle_t hBufferDst, ur_rect_offset_t srcOrigin,
ur_rect_offset_t dstOrigin, ur_rect_region_t region, size_t srcRowPitch,
size_t srcSlicePitch, size_t dstRowPitch, size_t dstSlicePitch,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
void *SrcPtr =
std::get<BufferMem>(hBufferSrc->Mem).getVoid(hQueue->getDevice());
void *DstPtr =
std::get<BufferMem>(hBufferDst->Mem).getVoid(hQueue->getDevice());
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
try {
ScopedDevice Active(hQueue->getDevice());
hipStream_t HIPStream = hQueue->getNextTransferStream();
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_COPY_RECT, hQueue, HIPStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
UR_CHECK_ERROR(commonEnqueueMemBufferCopyRect(
HIPStream, region, &SrcPtr, hipMemoryTypeDevice, srcOrigin, srcRowPitch,
srcSlicePitch, &DstPtr, hipMemoryTypeDevice, dstOrigin, dstRowPitch,
dstSlicePitch));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
}
return UR_RESULT_SUCCESS;
}
static inline void memsetRemainPattern(hipStream_t Stream, uint32_t PatternSize,
size_t Size, const void *pPattern,
hipDeviceptr_t Ptr,
uint32_t StartOffset) {
// Calculate the number of times the pattern needs to be applied
auto Height = Size / PatternSize;
for (auto step = StartOffset; step < PatternSize; ++step) {
// take 1 byte of the pattern
auto Value = *(static_cast<const uint8_t *>(pPattern) + step);
// offset the pointer to the part of the buffer we want to write to
auto OffsetPtr =
reinterpret_cast<void *>(reinterpret_cast<uint8_t *>(Ptr) + step);
// set all of the pattern chunks
UR_CHECK_ERROR(
hipMemset2DAsync(OffsetPtr, PatternSize, Value, 1u, Height, Stream));
}
}
// HIP has no memset functions that allow setting values more than 4 bytes. UR
// API lets you pass an arbitrary "pattern" to the buffer fill, which can be
// more than 4 bytes. We must break up the pattern into 1 byte values, and set
// the buffer using multiple strided calls. The first 4 patterns are set
// using hipMemsetD32Async then all subsequent 1 byte patterns are set using
// hipMemset2DAsync which is called for each pattern.
ur_result_t commonMemSetLargePattern(hipStream_t Stream, uint32_t PatternSize,
size_t Size, const void *pPattern,
hipDeviceptr_t Ptr) {
// Find the largest supported word size into which the pattern can be divided
auto BackendWordSize = PatternSize % 4u == 0u ? 4u
: PatternSize % 2u == 0u ? 2u
: 1u;
// Calculate the number of patterns
auto NumberOfSteps = PatternSize / BackendWordSize;
// If the pattern is 1 word or the first word is repeated throughout, a fast
// continuous fill can be used without the need for slower strided fills
bool UseOnlyFirstValue{true};
auto checkIfFirstWordRepeats = [&UseOnlyFirstValue,
NumberOfSteps](const auto *pPatternWords) {
for (auto Step{1u}; (Step < NumberOfSteps) && UseOnlyFirstValue; ++Step) {
if (*(pPatternWords + Step) != *pPatternWords) {
UseOnlyFirstValue = false;
}
}
};
// Use a continuous fill for the first word in the pattern because it's faster
// than a strided fill. Then, overwrite the other values in subsequent steps.
switch (BackendWordSize) {
case 4u: {
auto *pPatternWords = static_cast<const uint32_t *>(pPattern);
checkIfFirstWordRepeats(pPatternWords);
UR_CHECK_ERROR(
hipMemsetD32Async(Ptr, *pPatternWords, Size / BackendWordSize, Stream));
break;
}
case 2u: {
auto *pPatternWords = static_cast<const uint16_t *>(pPattern);
checkIfFirstWordRepeats(pPatternWords);
UR_CHECK_ERROR(
hipMemsetD16Async(Ptr, *pPatternWords, Size / BackendWordSize, Stream));
break;
}
default: {
auto *pPatternWords = static_cast<const uint8_t *>(pPattern);
checkIfFirstWordRepeats(pPatternWords);
UR_CHECK_ERROR(
hipMemsetD8Async(Ptr, *pPatternWords, Size / BackendWordSize, Stream));
break;
}
}
if (UseOnlyFirstValue) {
return UR_RESULT_SUCCESS;
}
// There is a bug in ROCm prior to 6.0.0 version which causes hipMemset2D
// to behave incorrectly when acting on host pinned memory.
// In such a case, the memset operation is partially emulated with memcpy.
#if HIP_VERSION_MAJOR < 6
hipPointerAttribute_t ptrAttribs{};
UR_CHECK_ERROR(hipPointerGetAttributes(&ptrAttribs, (const void *)Ptr));
// The hostPointer attribute is non-null also for shared memory allocations.
// To make sure that this workaround only executes for host pinned memory,
// we need to check that isManaged attribute is false.
if (ptrAttribs.hostPointer && !ptrAttribs.isManaged) {
const auto NumOfCopySteps = Size / PatternSize;
const auto Offset = BackendWordSize;
const auto LeftPatternSize = PatternSize - Offset;
const auto OffsetPatternPtr = reinterpret_cast<const void *>(
reinterpret_cast<const uint8_t *>(pPattern) + Offset);
// Loop through the memory area to memset, advancing each time by the
// PatternSize and memcpy the left over pattern bits.
for (uint32_t i = 0; i < NumOfCopySteps; ++i) {
auto OffsetDstPtr = reinterpret_cast<void *>(
reinterpret_cast<uint8_t *>(Ptr) + Offset + i * PatternSize);
UR_CHECK_ERROR(hipMemcpyAsync(OffsetDstPtr, OffsetPatternPtr,
LeftPatternSize, hipMemcpyHostToHost,
Stream));
}
} else {
memsetRemainPattern(Stream, PatternSize, Size, pPattern, Ptr,
BackendWordSize);
}
#else
memsetRemainPattern(Stream, PatternSize, Size, pPattern, Ptr,
BackendWordSize);
#endif
return UR_RESULT_SUCCESS;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemBufferFill(
ur_queue_handle_t hQueue, ur_mem_handle_t hBuffer, const void *pPattern,
size_t patternSize, size_t offset, size_t size,
uint32_t numEventsInWaitList, const ur_event_handle_t *phEventWaitList,
ur_event_handle_t *phEvent) {
UR_ASSERT(size + offset <= std::get<BufferMem>(hBuffer->Mem).getSize(),
UR_RESULT_ERROR_INVALID_SIZE);
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
hBuffer->setLastQueueWritingToMemObj(hQueue);
try {
ScopedDevice Active(hQueue->getDevice());
auto Stream = hQueue->getNextTransferStream();
if (phEventWaitList) {
UR_CHECK_ERROR(enqueueEventsWait(hQueue, Stream, numEventsInWaitList,
phEventWaitList));
}
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_WRITE, hQueue, Stream));
UR_CHECK_ERROR(RetImplEvent->start());
}
auto DstDevice = std::get<BufferMem>(hBuffer->Mem)
.getPtrWithOffset(hQueue->getDevice(), offset);
auto N = size / patternSize;
// pattern size in bytes
switch (patternSize) {
case 1: {
auto Value = *static_cast<const uint8_t *>(pPattern);
UR_CHECK_ERROR(hipMemsetD8Async(DstDevice, Value, N, Stream));
break;
}
case 2: {
auto Value = *static_cast<const uint16_t *>(pPattern);
UR_CHECK_ERROR(hipMemsetD16Async(DstDevice, Value, N, Stream));
break;
}
case 4: {
auto Value = *static_cast<const uint32_t *>(pPattern);
UR_CHECK_ERROR(hipMemsetD32Async(DstDevice, Value, N, Stream));
break;
}
default: {
UR_CHECK_ERROR(commonMemSetLargePattern(Stream, patternSize, size,
pPattern, DstDevice));
break;
}
}
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
} catch (ur_result_t Err) {
return Err;
} catch (...) {
return UR_RESULT_ERROR_UNKNOWN;
}
return UR_RESULT_SUCCESS;
}
/// General ND memory copy operation for images (where N > 1).
/// This function requires the corresponding HIP context to be at the top of
/// the context stack
/// If the source and/or destination is an array, SrcPtr and/or DstPtr
/// must be a pointer to a hipArray
static ur_result_t commonEnqueueMemImageNDCopy(
hipStream_t HipStream, ur_mem_type_t ImgType, const size_t *Region,
const void *SrcPtr, const hipMemoryType SrcType, const size_t *SrcOffset,
void *DstPtr, const hipMemoryType DstType, const size_t *DstOffset) {
UR_ASSERT(SrcType == hipMemoryTypeArray || SrcType == hipMemoryTypeHost,
UR_RESULT_ERROR_INVALID_VALUE);
UR_ASSERT(DstType == hipMemoryTypeArray || DstType == hipMemoryTypeHost,
UR_RESULT_ERROR_INVALID_VALUE);
if (ImgType == UR_MEM_TYPE_IMAGE1D || ImgType == UR_MEM_TYPE_IMAGE2D) {
hip_Memcpy2D CpyDesc;
memset(&CpyDesc, 0, sizeof(CpyDesc));
CpyDesc.srcMemoryType = SrcType;
if (SrcType == hipMemoryTypeArray) {
CpyDesc.srcArray =
reinterpret_cast<hipCUarray>(const_cast<void *>(SrcPtr));
CpyDesc.srcXInBytes = SrcOffset[0];
CpyDesc.srcY = (ImgType == UR_MEM_TYPE_IMAGE1D) ? 0 : SrcOffset[1];
} else {
CpyDesc.srcHost = SrcPtr;
}
CpyDesc.dstMemoryType = DstType;
if (DstType == hipMemoryTypeArray) {
CpyDesc.dstArray =
reinterpret_cast<hipCUarray>(const_cast<void *>(DstPtr));
CpyDesc.dstXInBytes = DstOffset[0];
CpyDesc.dstY = (ImgType == UR_MEM_TYPE_IMAGE1D) ? 0 : DstOffset[1];
} else {
CpyDesc.dstHost = DstPtr;
}
CpyDesc.WidthInBytes = Region[0];
CpyDesc.Height = (ImgType == UR_MEM_TYPE_IMAGE1D) ? 1 : Region[1];
UR_CHECK_ERROR(hipMemcpyParam2DAsync(&CpyDesc, HipStream));
return UR_RESULT_SUCCESS;
}
if (ImgType == UR_MEM_TYPE_IMAGE3D) {
HIP_MEMCPY3D CpyDesc;
memset(&CpyDesc, 0, sizeof(CpyDesc));
CpyDesc.srcMemoryType = SrcType;
if (SrcType == hipMemoryTypeArray) {
CpyDesc.srcArray =
reinterpret_cast<hipCUarray>(const_cast<void *>(SrcPtr));
CpyDesc.srcXInBytes = SrcOffset[0];
CpyDesc.srcY = SrcOffset[1];
CpyDesc.srcZ = SrcOffset[2];
} else {
CpyDesc.srcHost = SrcPtr;
}
CpyDesc.dstMemoryType = DstType;
if (DstType == hipMemoryTypeArray) {
CpyDesc.dstArray = reinterpret_cast<hipCUarray>(DstPtr);
CpyDesc.dstXInBytes = DstOffset[0];
CpyDesc.dstY = DstOffset[1];
CpyDesc.dstZ = DstOffset[2];
} else {
CpyDesc.dstHost = DstPtr;
}
CpyDesc.WidthInBytes = Region[0];
CpyDesc.Height = Region[1];
CpyDesc.Depth = Region[2];
UR_CHECK_ERROR(hipDrvMemcpy3DAsync(&CpyDesc, HipStream));
return UR_RESULT_SUCCESS;
}
return UR_RESULT_ERROR_INVALID_VALUE;
}
UR_APIEXPORT ur_result_t UR_APICALL urEnqueueMemImageRead(
ur_queue_handle_t hQueue, ur_mem_handle_t hImage, bool blockingRead,
ur_rect_offset_t origin, ur_rect_region_t region, size_t, size_t,
void *pDst, uint32_t numEventsInWaitList,
const ur_event_handle_t *phEventWaitList, ur_event_handle_t *phEvent) {
UR_ASSERT(hImage->isImage(), UR_RESULT_ERROR_INVALID_MEM_OBJECT);
try {
// Note that this entry point may be called on a queue that may not be the
// last queue to write to the MemImage, meaning we must perform the copy
// from a different device
if (hImage->LastQueueWritingToMemObj &&
hImage->LastQueueWritingToMemObj->getDevice() != hQueue->getDevice()) {
hQueue = hImage->LastQueueWritingToMemObj;
}
auto Device = hQueue->getDevice();
ScopedDevice Active(Device);
hipStream_t HIPStream = hQueue->getNextTransferStream();
if (phEventWaitList) {
UR_CHECK_ERROR(enqueueEventsWait(hQueue, HIPStream, numEventsInWaitList,
phEventWaitList));
}
hipArray *Array = std::get<SurfaceMem>(hImage->Mem).getArray(Device);
hipArray_Format Format{};
size_t NumChannels{};
UR_CHECK_ERROR(getArrayDesc(Array, Format, NumChannels));
int ElementByteSize = imageElementByteSize(Format);
size_t ByteOffsetX = origin.x * ElementByteSize * NumChannels;
size_t BytesToCopy = ElementByteSize * NumChannels * region.width;
auto ImgType = std::get<SurfaceMem>(hImage->Mem).getImageType();
size_t AdjustedRegion[3] = {BytesToCopy, region.height, region.depth};
size_t SrcOffset[3] = {ByteOffsetX, origin.y, origin.z};
std::unique_ptr<ur_event_handle_t_> RetImplEvent{nullptr};
if (phEvent) {
RetImplEvent =
std::unique_ptr<ur_event_handle_t_>(ur_event_handle_t_::makeNative(
UR_COMMAND_MEM_BUFFER_READ_RECT, hQueue, HIPStream));
UR_CHECK_ERROR(RetImplEvent->start());
}
UR_CHECK_ERROR(commonEnqueueMemImageNDCopy(
HIPStream, ImgType, AdjustedRegion, Array, hipMemoryTypeArray,
SrcOffset, pDst, hipMemoryTypeHost, nullptr));
if (phEvent) {
UR_CHECK_ERROR(RetImplEvent->record());
*phEvent = RetImplEvent.release();
}
if (blockingRead) {
UR_CHECK_ERROR(hipStreamSynchronize(HIPStream));
}
} catch (ur_result_t Err) {
return Err;