forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpi_cuda.cpp
More file actions
3681 lines (3175 loc) · 126 KB
/
Copy pathpi_cuda.cpp
File metadata and controls
3681 lines (3175 loc) · 126 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_cuda.cpp - CUDA 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_cuda.cpp
/// Implementation of CUDA Plugin.
///
/// \ingroup sycl_pi_cuda
#include <CL/sycl/backend/cuda.hpp>
#include <CL/sycl/detail/pi.hpp>
#include <pi_cuda.hpp>
#include <algorithm>
#include <cassert>
#include <cuda.h>
#include <cuda_device_runtime_api.h>
#include <limits>
#include <memory>
#include <mutex>
#include <regex>
namespace {
std::string getCudaVersionString() {
int driver_version = 0;
cuDriverGetVersion(&driver_version);
// The version is returned as (1000 major + 10 minor).
std::stringstream stream;
stream << "CUDA " << driver_version / 1000 << "."
<< driver_version % 1000 / 10;
return stream.str();
}
pi_result map_error(CUresult result) {
switch (result) {
case CUDA_SUCCESS:
return PI_SUCCESS;
case CUDA_ERROR_NOT_PERMITTED:
return PI_INVALID_OPERATION;
case CUDA_ERROR_INVALID_CONTEXT:
return PI_INVALID_CONTEXT;
case CUDA_ERROR_INVALID_DEVICE:
return PI_INVALID_DEVICE;
case CUDA_ERROR_INVALID_VALUE:
return PI_INVALID_VALUE;
case CUDA_ERROR_OUT_OF_MEMORY:
return PI_OUT_OF_HOST_MEMORY;
case CUDA_ERROR_LAUNCH_OUT_OF_RESOURCES:
return PI_OUT_OF_RESOURCES;
default:
return PI_ERROR_UNKNOWN;
}
}
inline void assign_result(pi_result *ptr, pi_result value) noexcept {
if (ptr) {
*ptr = value;
}
}
// Iterates over the event wait list, returns correct pi_result error codes.
// Invokes the callback for each event in the wait list. The callback must take
// a single pi_event argument and return a pi_result.
template <typename Func>
pi_result forEachEvent(const pi_event *event_wait_list,
std::size_t num_events_in_wait_list, Func &&f) {
if (event_wait_list == nullptr || num_events_in_wait_list == 0) {
return PI_INVALID_EVENT_WAIT_LIST;
}
for (size_t i = 0; i < num_events_in_wait_list; i++) {
auto event = event_wait_list[i];
if (event == nullptr) {
return PI_INVALID_EVENT_WAIT_LIST;
}
auto result = f(event);
if (result != PI_SUCCESS) {
return result;
}
}
return PI_SUCCESS;
}
/// Converts CUDA error into PI error codes, and outputs error information
/// to stderr.
/// If PI_CUDA_ABORT env variable is defined, it aborts directly instead of
/// throwing the error. This is intended for debugging purposes.
/// \return PI_SUCCESS if \param result was CUDA_SUCCESS.
/// \throw pi_error exception (integer) if input was not success.
///
pi_result check_error(CUresult result, const char *function, int line,
const char *file) {
if (result == CUDA_SUCCESS) {
return PI_SUCCESS;
}
const char *errorString = nullptr;
const char *errorName = nullptr;
cuGetErrorName(result, &errorName);
cuGetErrorString(result, &errorString);
std::cerr << "\nPI CUDA ERROR:"
<< "\n\tValue: " << result
<< "\n\tName: " << errorName
<< "\n\tDescription: " << errorString
<< "\n\tFunction: " << function
<< "\n\tSource Location: " << file << ":" << line << "\n"
<< std::endl;
if(std::getenv("PI_CUDA_ABORT") != nullptr)
{
std::abort();
}
throw map_error(result);
}
/// \cond NODOXY
#define PI_CHECK_ERROR(result) \
check_error(result, __func__, __LINE__, __FILE__)
/// RAII type to guarantee recovering original CUDA context
/// Scoped context is used across all PI CUDA plugin implementation
/// to activate the PI Context on the current thread, matching the
/// CUDA driver semantics where the context used for the CUDA Driver
/// API is the one active on the thread.
/// The implementation tries to avoid replacing the CUcontext if it cans
class ScopedContext {
pi_context placedContext_;
CUcontext original_;
bool needToRecover_;
public:
ScopedContext(pi_context ctxt) : placedContext_{ctxt}, needToRecover_{false} {
if (!placedContext_) {
throw PI_INVALID_CONTEXT;
}
CUcontext desired = placedContext_->get();
PI_CHECK_ERROR(cuCtxGetCurrent(&original_));
if (original_ != desired) {
// Sets the desired context as the active one for the thread
PI_CHECK_ERROR(cuCtxSetCurrent(desired));
if (original_ == nullptr && ctxt->is_primary()) {
// No context is installed and the suggested context is primary
// This is the most common case. We can activate the context in the
// thread and leave it there until all the PI context referring to the
// same underlying CUDA primary context are destroyed. This emulates
// the behaviour of the CUDA runtime api, and avoids costly context
// switches. No action is required on this side of the if.
} else {
needToRecover_ = true;
}
}
}
~ScopedContext() {
if (needToRecover_) {
PI_CHECK_ERROR(cuCtxSetCurrent(original_));
}
}
};
/// \cond NODOXY
template <typename T, typename Assign>
pi_result getInfoImpl(size_t param_value_size, void *param_value,
size_t *param_value_size_ret, T value, size_t value_size,
Assign &&assign_func) {
if (param_value != nullptr) {
if (param_value_size < value_size) {
return PI_INVALID_VALUE;
}
assign_func(param_value, value, value_size);
}
if (param_value_size_ret != nullptr) {
*param_value_size_ret = value_size;
}
return PI_SUCCESS;
}
template <typename T>
pi_result getInfo(size_t param_value_size, void *param_value,
size_t *param_value_size_ret, T value) {
auto assignment = [](void *param_value, T value, size_t value_size) {
*static_cast<T *>(param_value) = value;
};
return getInfoImpl(param_value_size, param_value, param_value_size_ret, value,
sizeof(T), assignment);
}
template <typename T>
pi_result getInfoArray(size_t array_length, size_t param_value_size,
void *param_value, size_t *param_value_size_ret,
T *value) {
return getInfoImpl(param_value_size, param_value, param_value_size_ret, value,
array_length * sizeof(T), memcpy);
}
template <>
pi_result getInfo<const char *>(size_t param_value_size, void *param_value,
size_t *param_value_size_ret,
const char *value) {
return getInfoArray(strlen(value) + 1, param_value_size, param_value,
param_value_size_ret, value);
}
int getAttribute(pi_device device, CUdevice_attribute attribute) {
int value;
cl::sycl::detail::pi::assertion(
cuDeviceGetAttribute(&value, attribute, device->get()) == CUDA_SUCCESS);
return value;
}
/// \endcond
} // anonymous namespace
/// ------ Error handling, matching OpenCL plugin semantics.
namespace cl {
namespace sycl {
namespace detail {
namespace pi {
// Report error and no return (keeps compiler from printing warnings).
// TODO: Probably change that to throw a catchable exception,
// but for now it is useful to see every failure.
//
[[noreturn]] void die(const char *Message) {
std::cerr << "pi_die: " << Message << std::endl;
std::terminate();
}
void assertion(bool Condition, const char *Message) {
if (!Condition)
die(Message);
}
} // namespace pi
} // namespace detail
} // namespace sycl
} // namespace cl
//--------------
// PI object implementation
extern "C" {
// Required in a number of functions, so forward declare here
pi_result cuda_piEnqueueEventsWait(pi_queue command_queue,
pi_uint32 num_events_in_wait_list,
const pi_event *event_wait_list,
pi_event *event);
pi_result cuda_piEventRelease(pi_event event);
pi_result cuda_piEventRetain(pi_event event);
} // extern "C"
/// \endcond
_pi_event::_pi_event(pi_command_type type, pi_context context, pi_queue queue)
: commandType_{type}, refCount_{1}, isCompleted_{false}, isRecorded_{false},
isStarted_{false}, evEnd_{nullptr}, evStart_{nullptr}, evQueued_{nullptr},
queue_{queue}, context_{context} {
if (is_native_event()) {
PI_CHECK_ERROR(cuEventCreate(&evEnd_, CU_EVENT_DEFAULT));
if (queue_->properties_ & PI_QUEUE_PROFILING_ENABLE) {
PI_CHECK_ERROR(cuEventCreate(&evQueued_, CU_EVENT_DEFAULT));
PI_CHECK_ERROR(cuEventCreate(&evStart_, CU_EVENT_DEFAULT));
}
}
if (queue_ != nullptr) {
cuda_piQueueRetain(queue_);
}
cuda_piContextRetain(context_);
}
_pi_event::~_pi_event() {
if (queue_ != nullptr) {
cuda_piQueueRelease(queue_);
}
cuda_piContextRelease(context_);
}
pi_result _pi_event::start() {
assert(!is_started());
pi_result result;
try {
if (is_native_event() && queue_->properties_ & PI_QUEUE_PROFILING_ENABLE) {
// NOTE: This relies on the default stream to be unused.
result = PI_CHECK_ERROR(cuEventRecord(evQueued_, 0));
result = PI_CHECK_ERROR(cuEventRecord(evStart_, queue_->get()));
}
} catch (pi_result error) {
result = error;
}
isStarted_ = true;
// let observers know that the event is "submitted"
trigger_callback(get_execution_status());
return result;
}
pi_uint64 _pi_event::get_queued_time() const {
float miliSeconds = 0.0f;
assert(is_started());
PI_CHECK_ERROR(
cuEventElapsedTime(&miliSeconds, context_->evBase_, evQueued_));
return static_cast<pi_uint64>(miliSeconds * 1.0e6);
}
pi_uint64 _pi_event::get_start_time() const {
float miliSeconds = 0.0f;
assert(is_started());
PI_CHECK_ERROR(cuEventElapsedTime(&miliSeconds, context_->evBase_, evStart_));
return static_cast<pi_uint64>(miliSeconds * 1.0e6);
}
pi_uint64 _pi_event::get_end_time() const {
float miliSeconds = 0.0f;
assert(is_started() && is_recorded());
PI_CHECK_ERROR(cuEventElapsedTime(&miliSeconds, context_->evBase_, evEnd_));
return static_cast<pi_uint64>(miliSeconds * 1.0e6);
}
pi_result _pi_event::record() {
if (is_recorded()) {
return PI_INVALID_EVENT;
}
pi_result result = PI_INVALID_OPERATION;
if (is_native_event()) {
if (!queue_) {
return PI_INVALID_QUEUE;
}
CUstream cuStream = queue_->get();
try {
result = PI_CHECK_ERROR(cuEventRecord(evEnd_, cuStream));
result = cuda_piEventRetain(this);
try {
result = PI_CHECK_ERROR(cuLaunchHostFunc(
cuStream,
[](void *userData) {
pi_event event = reinterpret_cast<pi_event>(userData);
event->set_event_complete();
cuda_piEventRelease(event);
},
this));
} catch (...) {
// If host function fails to enqueue we must release the event here
result = cuda_piEventRelease(this);
throw;
}
} catch (pi_result error) {
result = error;
}
} else {
result = PI_SUCCESS;
}
if (result == PI_SUCCESS) {
isRecorded_ = true;
}
return result;
}
pi_result _pi_event::wait() {
pi_result retErr;
if (is_native_event()) {
try {
retErr = PI_CHECK_ERROR(cuEventSynchronize(evEnd_));
isCompleted_ = true;
} catch (pi_result error) {
retErr = error;
}
} else {
while (!is_completed()) {
// wait for user event to complete
}
retErr = PI_SUCCESS;
}
auto is_success = retErr == PI_SUCCESS;
auto status = is_success ? get_execution_status() : pi_int32(retErr);
trigger_callback(status);
return retErr;
}
// makes all future work submitted to queue wait for all work captured in event.
pi_result enqueueEventWait(pi_queue queue, pi_event event) {
if (event->is_native_event()) {
// for native events, the cuStreamWaitEvent call is used.
// This makes all future work submitted to stream wait for all
// work captured in event.
return PI_CHECK_ERROR(cuStreamWaitEvent(queue->get(), event->get(), 0));
} else {
// for user events, we enqueue a callback. When invoked, the
// callback will block until the user event is marked as
// completed.
static auto user_wait_func = [](void *user_data) {
// The host function must not make any CUDA API calls.
auto event = static_cast<pi_event>(user_data);
// busy wait for user event to complete
event->wait();
// this function does not need the event to be kept alive
// anymore
cuda_piEventRelease(event);
};
// retain event to ensure it is still alive when the
// user_wait_func callback is invoked
cuda_piEventRetain(event);
return PI_CHECK_ERROR(cuLaunchHostFunc(queue->get(), user_wait_func, event));
}
}
_pi_program::_pi_program(pi_context ctxt)
: module_{nullptr}, source_{}, sourceLength_{0}
, refCount_{1}, context_{ctxt}
{
cuda_piContextRetain(context_);
}
_pi_program::~_pi_program() {
cuda_piContextRelease(context_);
}
pi_result _pi_program::create_from_source(const char *source, size_t length) {
source_ = source;
sourceLength_ = length;
return PI_SUCCESS;
}
pi_result _pi_program::build_program(const char *build_options) {
this->buildOptions_ = build_options;
constexpr const unsigned int numberOfOptions = 4u;
CUjit_option options[numberOfOptions];
void *optionVals[numberOfOptions];
// Pass a buffer for info messages
options[0] = CU_JIT_INFO_LOG_BUFFER;
optionVals[0] = (void *)infoLog_;
// Pass the size of the info buffer
options[1] = CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES;
optionVals[1] = (void *)(long)MAX_LOG_SIZE;
// Pass a buffer for error message
options[2] = CU_JIT_ERROR_LOG_BUFFER;
optionVals[2] = (void *)errorLog_;
// Pass the size of the error buffer
options[3] = CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES;
optionVals[3] = (void *)(long)MAX_LOG_SIZE;
auto result = PI_CHECK_ERROR(cuModuleLoadDataEx(
&module_, static_cast<const void *>(source_), numberOfOptions, options,
optionVals));
const auto success = (result == PI_SUCCESS);
buildStatus_ =
success ? PI_PROGRAM_BUILD_STATUS_SUCCESS : PI_PROGRAM_BUILD_STATUS_ERROR;
// If no exception, result is correct
return success ? PI_SUCCESS : PI_BUILD_PROGRAM_FAILURE;
}
/// Finds kernel names by searching for entry points in the PTX source, as the
/// CUDA driver API doesn't expose an operation for this.
/// Note: This is currently only being used by the SYCL program class for the
/// has_kernel method, so an alternative would be to move the has_kernel
/// query to PI and use cuModuleGetFunction to check for a kernel.
std::string getKernelNames(pi_program program) {
std::string source(program->source_,
program->source_ + program->sourceLength_);
std::regex entries_pattern(".entry\\s+([^\\([:s:]]*)");
std::string names("");
std::smatch match;
bool first_match = true;
while (std::regex_search(source, match, entries_pattern)) {
assert(match.size() == 2);
names += first_match ? "" : ";";
names += match[1]; // Second element is the group.
source = match.suffix().str();
first_match = false;
}
return names;
}
/// RAII object that calls the reference count release function on the held PI
/// object on destruction.
///
/// The `dismiss` function stops the release from happening on destruction.
template <typename T> class ReleaseGuard {
private:
T Captive;
static pi_result callRelease(pi_device Captive) {
return cuda_piDeviceRelease(Captive);
}
static pi_result callRelease(pi_context Captive) {
return cuda_piContextRelease(Captive);
}
static pi_result callRelease(pi_mem Captive) {
return cuda_piMemRelease(Captive);
}
static pi_result callRelease(pi_program Captive) {
return cuda_piProgramRelease(Captive);
}
static pi_result callRelease(pi_kernel Captive) {
return cuda_piKernelRelease(Captive);
}
static pi_result callRelease(pi_queue Captive) {
return cuda_piQueueRelease(Captive);
}
static pi_result callRelease(pi_event Captive) {
return cuda_piEventRelease(Captive);
}
public:
ReleaseGuard() = delete;
/// Obj can be `nullptr`.
explicit ReleaseGuard(T Obj) : Captive(Obj) {}
ReleaseGuard(ReleaseGuard &&Other) noexcept : Captive(Other.Captive) {
Other.Captive = nullptr;
}
ReleaseGuard(const ReleaseGuard &) = delete;
/// Calls the related PI object release function if the object held is not
/// `nullptr` or if `dismiss` has not been called.
~ReleaseGuard() {
if (Captive != nullptr) {
pi_result ret = callRelease(Captive);
if (ret != PI_SUCCESS) {
// A reported CUDA error is either an implementation or an asynchronous
// CUDA error for which it is unclear if the function that reported it
// succeeded or not. Either way, the state of the program is compromised
// and likely unrecoverable.
cl::sycl::detail::pi::die("Unrecoverable program state reached in cuda_piMemRelease");
}
}
}
ReleaseGuard &operator=(const ReleaseGuard &) = delete;
ReleaseGuard &operator=(ReleaseGuard &&Other) {
Captive = Other.Captive;
Other.Captive = nullptr;
return *this;
}
/// End the guard and do not release the reference count of the held
/// PI object.
void dismiss() { Captive = nullptr; }
};
//-- PI API implementation
extern "C" {
/// Obtains the CUDA platform.
/// There is only one CUDA platform, and contains all devices on the system.
/// Triggers the CUDA Driver initialization (cuInit) the first time, so this
/// must be the first PI API called.
///
pi_result cuda_piPlatformsGet(pi_uint32 num_entries, pi_platform *platforms,
pi_uint32 *num_platforms) {
try {
static std::once_flag initFlag;
static pi_uint32 numPlatforms = 1;
static _pi_platform platformId;
if (num_entries == 0 and platforms != nullptr) {
return PI_INVALID_VALUE;
}
if (platforms == nullptr and num_platforms == nullptr) {
return PI_INVALID_VALUE;
}
pi_result err = PI_SUCCESS;
std::call_once(
initFlag,
[](pi_result &err) {
if (cuInit(0) != CUDA_SUCCESS) {
numPlatforms = 0;
return;
}
int numDevices = 0;
err = PI_CHECK_ERROR(cuDeviceGetCount(&numDevices));
if (numDevices == 0) {
numPlatforms = 0;
return;
}
try {
platformId.devices_.reserve(numDevices);
for (int i = 0; i < numDevices; ++i) {
CUdevice device;
err = PI_CHECK_ERROR(cuDeviceGet(&device, i));
platformId.devices_.emplace_back(
new _pi_device{device, &platformId});
}
} catch (const std::bad_alloc &) {
// Signal out-of-memory situation
platformId.devices_.clear();
err = PI_OUT_OF_HOST_MEMORY;
} catch (...) {
// Clear and rethrow to allow retry
platformId.devices_.clear();
throw;
}
},
err);
if (num_platforms != nullptr) {
*num_platforms = numPlatforms;
}
if (platforms != nullptr) {
*platforms = &platformId;
}
return err;
} catch (pi_result err) {
return err;
} catch (...) {
return PI_OUT_OF_RESOURCES;
}
}
pi_result cuda_piPlatformGetInfo(pi_platform platform,
pi_platform_info param_name,
size_t param_value_size, void *param_value,
size_t *param_value_size_ret) {
assert(platform != nullptr);
switch (param_name) {
case PI_PLATFORM_INFO_NAME:
return getInfo(param_value_size, param_value, param_value_size_ret,
"NVIDIA CUDA");
case PI_PLATFORM_INFO_VENDOR:
return getInfo(param_value_size, param_value, param_value_size_ret,
"NVIDIA Corporation");
case PI_PLATFORM_INFO_PROFILE:
return getInfo(param_value_size, param_value, param_value_size_ret,
"FULL PROFILE");
case PI_PLATFORM_INFO_VERSION: {
auto version = getCudaVersionString();
return getInfo(param_value_size, param_value, param_value_size_ret,
version.c_str());
}
case PI_PLATFORM_INFO_EXTENSIONS: {
return getInfo(param_value_size, param_value, param_value_size_ret, "");
}
default:
PI_HANDLE_UNKNOWN_PARAM_NAME(param_name);
}
cl::sycl::detail::pi::die("Platform info request not implemented");
return {};
}
/// \TODO Not implemented
pi_result cuda_piextDeviceConvert(pi_device *device, void **handle) {
cl::sycl::detail::pi::die("cuda_piextDeviceConvert not implemented");
return {};
}
/// \param devices List of devices available on the system
/// \param num_devices Number of elements in the list of devices
/// Requesting a non-GPU device triggers an error, all PI CUDA devices
/// are GPUs.
///
pi_result cuda_piDevicesGet(pi_platform platform, pi_device_type device_type,
pi_uint32 num_entries, pi_device *devices,
pi_uint32 *num_devices) {
pi_result err = PI_SUCCESS;
const bool askingForGPU = (device_type & PI_DEVICE_TYPE_GPU);
size_t numDevices = askingForGPU ? platform->devices_.size() : 0;
try {
if (num_devices) {
*num_devices = numDevices;
}
if (askingForGPU && devices) {
for (size_t i = 0; i < std::min(size_t(num_entries), numDevices); ++i) {
devices[i] = platform->devices_[i].get();
}
}
return err;
} catch (pi_result err) {
return err;
} catch (...) {
return PI_OUT_OF_RESOURCES;
}
}
/// \return PI_SUCCESS if the function is executed successfully
/// CUDA devices are always root devices so retain always returns success.
pi_result cuda_piDeviceRetain(pi_device device) {
return PI_SUCCESS;
}
pi_result cuda_piContextGetInfo(pi_context context, pi_context_info param_name,
size_t param_value_size, void *param_value,
size_t *param_value_size_ret) {
switch (param_name) {
case PI_CONTEXT_INFO_NUM_DEVICES:
return getInfo(param_value_size, param_value, param_value_size_ret, 1);
case PI_CONTEXT_INFO_DEVICES:
return getInfo(param_value_size, param_value, param_value_size_ret,
context->get_device());
case PI_CONTEXT_INFO_REFERENCE_COUNT:
return getInfo(param_value_size, param_value, param_value_size_ret,
context->get_reference_count());
default:
PI_HANDLE_UNKNOWN_PARAM_NAME(param_name);
}
return PI_OUT_OF_RESOURCES;
}
pi_result cuda_piContextRetain(pi_context context) {
assert(context != nullptr);
assert(context->get_reference_count() > 0);
context->increment_reference_count();
return PI_SUCCESS;
}
/// Not applicable to CUDA, devices cannot be partitioned.
///
pi_result cuda_piDevicePartition(
pi_device device,
const cl_device_partition_property *properties, // TODO: untie from OpenCL
pi_uint32 num_devices, pi_device *out_devices, pi_uint32 *out_num_devices) {
return {};
}
/// \return If available, the first binary that is PTX
///
pi_result cuda_piextDeviceSelectBinary(pi_device device,
pi_device_binary *binaries,
pi_uint32 num_binaries,
pi_device_binary *selected_binary) {
if (!binaries) {
cl::sycl::detail::pi::die("No list of device images provided");
}
if (num_binaries < 1) {
cl::sycl::detail::pi::die("No binary images in the list");
}
if (!selected_binary) {
cl::sycl::detail::pi::die("No storage for device binary provided");
}
// Look for an image for the NVPTX64 target, and return the first one that is
// found
for (pi_uint32 i = 0; i < num_binaries; i++) {
if (strcmp(binaries[i]->DeviceTargetSpec,
PI_DEVICE_BINARY_TARGET_NVPTX64) == 0) {
*selected_binary = binaries[i];
return PI_SUCCESS;
}
}
// No image can be loaded for the given device
return PI_INVALID_BINARY;
}
pi_result cuda_piextGetDeviceFunctionPointer(pi_device device,
pi_program program,
const char *function_name,
pi_uint64 *function_pointer_ret) {
cl::sycl::detail::pi::die("cuda_piextGetDeviceFunctionPointer not implemented");
return {};
}
/// \return PI_SUCCESS always since CUDA devices are always root devices.
///
pi_result cuda_piDeviceRelease(pi_device device) {
return PI_SUCCESS;
}
pi_result cuda_piDeviceGetInfo(pi_device device, pi_device_info param_name,
size_t param_value_size, void *param_value,
size_t *param_value_size_ret) {
static constexpr pi_uint32 max_work_item_dimensions = 3u;
assert(device != nullptr);
switch (param_name) {
case PI_DEVICE_INFO_TYPE: {
return getInfo(param_value_size, param_value, param_value_size_ret,
PI_DEVICE_TYPE_GPU);
}
case PI_DEVICE_INFO_VENDOR_ID: {
return getInfo(param_value_size, param_value, param_value_size_ret, 4318u);
}
case PI_DEVICE_INFO_MAX_COMPUTE_UNITS: {
int compute_units = 0;
cl::sycl::detail::pi::assertion(cuDeviceGetAttribute(&compute_units,
CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT,
device->get()) == CUDA_SUCCESS);
cl::sycl::detail::pi::assertion(compute_units >= 0);
return getInfo(param_value_size, param_value, param_value_size_ret,
pi_uint32(compute_units));
}
case PI_DEVICE_INFO_MAX_WORK_ITEM_DIMENSIONS: {
return getInfo(param_value_size, param_value, param_value_size_ret,
max_work_item_dimensions);
}
case PI_DEVICE_INFO_MAX_WORK_ITEM_SIZES: {
size_t return_sizes[max_work_item_dimensions];
int max_x = 0, max_y = 0, max_z = 0;
cl::sycl::detail::pi::assertion(cuDeviceGetAttribute(&max_x,
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X,
device->get()) == CUDA_SUCCESS);
cl::sycl::detail::pi::assertion(max_x >= 0);
cl::sycl::detail::pi::assertion(cuDeviceGetAttribute(&max_y,
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y,
device->get()) == CUDA_SUCCESS);
cl::sycl::detail::pi::assertion(max_y >= 0);
cl::sycl::detail::pi::assertion(cuDeviceGetAttribute(&max_z,
CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z,
device->get()) == CUDA_SUCCESS);
cl::sycl::detail::pi::assertion(max_z >= 0);
return_sizes[0] = size_t(max_x);
return_sizes[1] = size_t(max_y);
return_sizes[2] = size_t(max_z);
return getInfoArray(max_work_item_dimensions, param_value_size, param_value,
param_value_size_ret, return_sizes);
}
case PI_DEVICE_INFO_MAX_WORK_GROUP_SIZE: {
int max_work_group_size = 0;
cl::sycl::detail::pi::assertion(
cuDeviceGetAttribute(&max_work_group_size,
CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
device->get()) == CUDA_SUCCESS);
cl::sycl::detail::pi::assertion(max_work_group_size >= 0);
return getInfo(param_value_size, param_value, param_value_size_ret,
size_t(max_work_group_size));
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_CHAR: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_SHORT: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_INT: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_LONG: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_FLOAT: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_DOUBLE: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_PREFERRED_VECTOR_WIDTH_HALF: {
return getInfo(param_value_size, param_value, param_value_size_ret, 0u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_CHAR: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_SHORT: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_INT: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_LONG: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_FLOAT: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_DOUBLE: {
return getInfo(param_value_size, param_value, param_value_size_ret, 1u);
}
case PI_DEVICE_INFO_NATIVE_VECTOR_WIDTH_HALF: {
return getInfo(param_value_size, param_value, param_value_size_ret, 0u);
}
case PI_DEVICE_INFO_MAX_CLOCK_FREQUENCY: {
int clock_freq = 0;
cl::sycl::detail::pi::assertion(cuDeviceGetAttribute(&clock_freq,
CU_DEVICE_ATTRIBUTE_CLOCK_RATE,
device->get()) == CUDA_SUCCESS);
cl::sycl::detail::pi::assertion(clock_freq >= 0);
return getInfo(param_value_size, param_value, param_value_size_ret,
pi_uint32(clock_freq) / 1000u);
}
case PI_DEVICE_INFO_ADDRESS_BITS: {
auto bits = pi_uint32{std::numeric_limits<uintptr_t>::digits};
return getInfo(param_value_size, param_value, param_value_size_ret, bits);
}
case PI_DEVICE_INFO_MAX_MEM_ALLOC_SIZE: {
// Max size of memory object allocation in bytes.
// The minimum value is max(min(1024 × 1024 ×
// 1024, 1/4th of CL_DEVICE_GLOBAL_MEM_SIZE),
// 32 × 1024 × 1024) for devices that are not of type
// CL_DEVICE_TYPE_CUSTOM.
size_t global = 0;
cl::sycl::detail::pi::assertion(cuDeviceTotalMem(&global, device->get()) == CUDA_SUCCESS);
auto quarter_global = static_cast<pi_uint32>(global / 4u);
auto max_alloc = std::max(std::min(1024u * 1024u * 1024u, quarter_global),
32u * 1024u * 1024u);
return getInfo(param_value_size, param_value, param_value_size_ret,
pi_uint64{max_alloc});
}
case PI_DEVICE_INFO_IMAGE_SUPPORT: {
return getInfo(param_value_size, param_value, param_value_size_ret,
PI_FALSE);
}
case PI_DEVICE_INFO_MAX_READ_IMAGE_ARGS: {
return getInfo(param_value_size, param_value, param_value_size_ret, 0);
}
case PI_DEVICE_INFO_MAX_WRITE_IMAGE_ARGS: {
return getInfo(param_value_size, param_value, param_value_size_ret, 0u);
}
case PI_DEVICE_INFO_IMAGE2D_MAX_HEIGHT: {
return getInfo(param_value_size, param_value, param_value_size_ret,
size_t(0));
}
case PI_DEVICE_INFO_IMAGE2D_MAX_WIDTH: {
return getInfo(param_value_size, param_value, param_value_size_ret,
size_t(0));
}
case PI_DEVICE_INFO_IMAGE3D_MAX_HEIGHT: {
return getInfo(param_value_size, param_value, param_value_size_ret,
size_t(0));
}
case PI_DEVICE_INFO_IMAGE3D_MAX_WIDTH: {
return getInfo(param_value_size, param_value, param_value_size_ret,
size_t(0));
}
case PI_DEVICE_INFO_IMAGE3D_MAX_DEPTH: {
return getInfo(param_value_size, param_value, param_value_size_ret,
size_t(0));