-
Notifications
You must be signed in to change notification settings - Fork 108
/
mcwamp_hsa.cpp
5981 lines (4798 loc) · 223 KB
/
mcwamp_hsa.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
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// Kalmar Runtime implementation (HSA version)
#include "../hc2/headers/types/program_state.hpp"
#include <algorithm>
#include <cassert>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <string>
#include <thread>
#include <unordered_map>
#include <utility>
#include <vector>
#include <unistd.h>
#include <sys/syscall.h>
#include <cxxabi.h>
#include <hsa/hsa.h>
#include <hsa/hsa_ext_finalize.h>
#include <hsa/hsa_ext_amd.h>
#include <hsa/amd_hsa_kernel_code.h>
#include <hsa/hsa_ven_amd_loader.h>
#include "kalmar_runtime.h"
#include "kalmar_aligned_alloc.h"
#include "hc_am_internal.hpp"
#include "unpinned_copy_engine.h"
#include "hc_rt_debug.h"
#include "hc_printf.hpp"
#include "activity_prof.h"
#include <time.h>
#include <iomanip>
#define CHECK_OLDER_COMPLETE 0
// Used to mark pieces of HCC runtime which may be specific to AMD's HSA implementation.
// Intended to help identify this code when porting to another HSA impl.
// FIXME - The AMD_HSA path is experimental and should not be enabled in production
// #define AMD_HSA
/////////////////////////////////////////////////
// kernel dispatch speed optimization flags
/////////////////////////////////////////////////
// Size of default kernarg buffer in the kernarg pool in HSAContext, in bytes.
// Increased from 512 to 4k to match CUDA default. See
// https://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#function-parameters
// When this size is exceeded, on-demand allocation of the kernarg buffer is slow.
#define KERNARG_BUFFER_SIZE (4096)
// number of pre-allocated kernarg buffers in HSAContext
// (some kernels don't allocate signals but nearly all need kernargs)
#define KERNARG_POOL_SIZE (1024)
// Maximum number of inflight commands sent to a single queue.
// If limit is exceeded, HCC will force a queue wait to reclaim
// resources (signals, kernarg)
// MUST be a power of 2.
#define MAX_INFLIGHT_COMMANDS_PER_QUEUE (2*8192)
// Threshold to clean up finished kernel in HSAQueue.asyncOps.
// Reduced from 16k to 1k at the same time when the HCC_KERNARG_BUFFER_SIZE
// was increased, in order to offset the increase in memory pressure.
int HCC_ASYNCOPS_SIZE = (1024);
int HCC_ASYNCOPS_WITHOUT_SIGNAL_SIZE = (HCC_ASYNCOPS_SIZE/2);
//---
// Environment variables:
int HCC_PRINT_ENV=0;
int HCC_UNPINNED_COPY_MODE = UnpinnedCopyEngine::UseStaging;
int HCC_CHECK_COPY=0;
// Copy thresholds, in KB. These are used for "choose-best" copy mode.
long int HCC_H2D_STAGING_THRESHOLD = 64;
long int HCC_H2D_PININPLACE_THRESHOLD = 4096;
long int HCC_D2H_PININPLACE_THRESHOLD = 1024;
// Staging buffer size in KB for unpinned copy engines
int HCC_STAGING_BUFFER_SIZE = 4*1024;
// Default GPU device
unsigned int HCC_DEFAULT_GPU = 0;
unsigned int HCC_ENABLE_PRINTF = 0;
// Chicken bits:
int HCC_SERIALIZE_KERNEL = 0;
int HCC_SERIALIZE_COPY = 0;
int HCC_FORCE_COMPLETION_FUTURE = 0;
int HCC_FORCE_CROSS_QUEUE_FLUSH=0;
int HCC_OPT_FLUSH=1;
unsigned HCC_DB = 0;
unsigned HCC_DB_SYMBOL_FORMAT=0x10;
int HCC_LAZY_QUEUE_CREATION=1;
int HCC_MAX_QUEUES = 20;
#define HCC_PROFILE_SUMMARY (1<<0)
#define HCC_PROFILE_TRACE (1<<1)
int HCC_PROFILE=0;
int HCC_FLUSH_ON_WAIT=1;
#define HCC_PROFILE_VERBOSE_BASIC (1 << 0) // 0x1
#define HCC_PROFILE_VERBOSE_TIMESTAMP (1 << 1) // 0x2
#define HCC_PROFILE_VERBOSE_OPSEQNUM (1 << 2) // 0x4
#define HCC_PROFILE_VERBOSE_TID (1 << 3) // 0x8
#define HCC_PROFILE_VERBOSE_BARRIER (1 << 4) // 0x10
int HCC_PROFILE_VERBOSE=0x1F;
char * HCC_PROFILE_FILE=nullptr;
// Profiler:
// Use str::stream so output is atomic wrt other threads:
#define LOG_PROFILE(op, start, end, type, tag, msg) \
{\
std::stringstream sstream;\
sstream << "profile: " << std::setw(7) << type << ";\t" \
<< std::setw(40) << tag\
<< ";\t" << std::fixed << std::setw(6) << std::setprecision(1) << (end-start)/1000.0 << " us;";\
if (HCC_PROFILE_VERBOSE & (HCC_PROFILE_VERBOSE_TIMESTAMP)) {\
sstream << "\t" << start << ";\t" << end << ";";\
}\
if (HCC_PROFILE_VERBOSE & (HCC_PROFILE_VERBOSE_OPSEQNUM)) {\
sstream << "\t" << *op << ";";\
}\
sstream << msg << "\n";\
Kalmar::ctx()->getHccProfileStream() << sstream.str();\
}
// Track a short thread-id, for debugging:
std::atomic<int> s_lastShortTid(1);
ShortTid::ShortTid() {
_shortTid = s_lastShortTid.fetch_add(1);
}
thread_local ShortTid hcc_tlsShortTid;
#define HSA_BARRIER_DEP_SIGNAL_CNT (5)
// synchronization for copy commands in the same stream, regardless of command type.
// Add a signal dependencies between async copies -
// so completion signal from prev command used as input dep to next.
// If FORCE_SIGNAL_DEP_BETWEEN_COPIES=0 then data copies of the same kind (H2H, H2D, D2H, D2D)
// are assumed to be implicitly ordered.
// ROCR 1.2 runtime implementation currently provides this guarantee when using SDMA queues and compute shaders.
#define FORCE_SIGNAL_DEP_BETWEEN_COPIES (0)
#define CASE_STRING(X) case X: case_string = #X ;break;
static const char* getHcCommandKindString(Kalmar::hcCommandKind k) {
const char* case_string;
switch(k) {
using namespace Kalmar;
CASE_STRING(hcCommandInvalid);
CASE_STRING(hcMemcpyHostToHost);
CASE_STRING(hcMemcpyHostToDevice);
CASE_STRING(hcMemcpyDeviceToHost);
CASE_STRING(hcMemcpyDeviceToDevice);
CASE_STRING(hcCommandKernel);
CASE_STRING(hcCommandMarker);
default: case_string = "Unknown command type";
};
return case_string;
};
static const char* getHSAErrorString(hsa_status_t s) {
const char* case_string;
switch(s) {
CASE_STRING(HSA_STATUS_ERROR);
CASE_STRING(HSA_STATUS_ERROR_INVALID_ARGUMENT);
CASE_STRING(HSA_STATUS_ERROR_INVALID_QUEUE_CREATION);
CASE_STRING(HSA_STATUS_ERROR_INVALID_ALLOCATION);
CASE_STRING(HSA_STATUS_ERROR_INVALID_AGENT);
CASE_STRING(HSA_STATUS_ERROR_INVALID_REGION);
CASE_STRING(HSA_STATUS_ERROR_INVALID_SIGNAL);
CASE_STRING(HSA_STATUS_ERROR_INVALID_QUEUE);
CASE_STRING(HSA_STATUS_ERROR_OUT_OF_RESOURCES);
CASE_STRING(HSA_STATUS_ERROR_INVALID_PACKET_FORMAT);
CASE_STRING(HSA_STATUS_ERROR_RESOURCE_FREE);
CASE_STRING(HSA_STATUS_ERROR_NOT_INITIALIZED);
CASE_STRING(HSA_STATUS_ERROR_REFCOUNT_OVERFLOW);
CASE_STRING(HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS);
CASE_STRING(HSA_STATUS_ERROR_INVALID_INDEX);
CASE_STRING(HSA_STATUS_ERROR_INVALID_ISA);
CASE_STRING(HSA_STATUS_ERROR_INVALID_ISA_NAME);
CASE_STRING(HSA_STATUS_ERROR_INVALID_CODE_OBJECT);
CASE_STRING(HSA_STATUS_ERROR_INVALID_EXECUTABLE);
CASE_STRING(HSA_STATUS_ERROR_FROZEN_EXECUTABLE);
CASE_STRING(HSA_STATUS_ERROR_INVALID_SYMBOL_NAME);
CASE_STRING(HSA_STATUS_ERROR_VARIABLE_ALREADY_DEFINED);
CASE_STRING(HSA_STATUS_ERROR_VARIABLE_UNDEFINED);
CASE_STRING(HSA_STATUS_ERROR_EXCEPTION);
default: case_string = "Unknown Error Code";
};
return case_string;
}
#define STATUS_CHECK(s,line) if (s != HSA_STATUS_SUCCESS && s != HSA_STATUS_INFO_BREAK) {\
hc::print_backtrace(); \
const char* error_string = getHSAErrorString(s);\
printf("### HCC STATUS_CHECK Error: %s (0x%x) at file:%s line:%d\n", error_string, s, __FILENAME__, line);\
assert(HSA_STATUS_SUCCESS == hsa_shut_down());\
abort();\
}
#define STATUS_CHECK_SYMBOL(s,symbol,line) if (s != HSA_STATUS_SUCCESS && s != HSA_STATUS_INFO_BREAK) {\
hc::print_backtrace(); \
const char* error_string = getHSAErrorString(s);\
printf("### HCC STATUS_CHECK_SYMBOL Error: %s (0x%x), symbol name:%s at file:%s line:%d\n", error_string, s, (symbol)!=nullptr?symbol:(const char*)"is a nullptr", __FILENAME__, line);\
assert(HSA_STATUS_SUCCESS == hsa_shut_down());\
abort();\
}
// debug function to dump information on an HSA agent
static void dumpHSAAgentInfo(hsa_agent_t agent, const char* extra_string = (const char*)"") {
hsa_status_t status;
char name[64] = {0};
status = hsa_agent_get_info(agent, HSA_AGENT_INFO_NAME, name);
STATUS_CHECK(status, __LINE__);
uint32_t node = 0;
status = hsa_agent_get_info(agent, HSA_AGENT_INFO_NODE, &node);
STATUS_CHECK(status, __LINE__);
wchar_t path_wchar[128] {0};
swprintf(path_wchar, 128, L"%s%u", name, node);
DBSTREAM << "Dump Agent Info (" << extra_string << ")" << std::endl;
DBSTREAM << "\t Agent: ";
DBWSTREAM << path_wchar << L"\n";
return;
}
static unsigned extractBits(unsigned v, unsigned pos, unsigned w)
{
return (v >> pos) & ((1 << w) - 1);
};
namespace
{
struct Symbol {
std::string name;
ELFIO::Elf64_Addr value = 0;
ELFIO::Elf_Xword size = 0;
ELFIO::Elf_Half sect_idx = 0;
std::uint8_t bind = 0;
std::uint8_t type = 0;
std::uint8_t other = 0;
};
inline
Symbol read_symbol(
const ELFIO::symbol_section_accessor& section, unsigned int idx)
{
assert(idx < section.get_symbols_num());
Symbol r;
section.get_symbol(
idx, r.name, r.value, r.size, r.bind, r.type, r.sect_idx, r.other);
return r;
}
template<typename P>
inline
ELFIO::section* find_section_if(ELFIO::elfio& reader, P p)
{
using namespace std;
const auto it = find_if(
reader.sections.begin(), reader.sections.end(), move(p));
return it != reader.sections.end() ? *it : nullptr;
}
inline
std::vector<std::string> copy_names_of_undefined_symbols(
const ELFIO::symbol_section_accessor& section)
{
using namespace ELFIO;
using namespace std;
vector<string> r;
for (auto i = 0u; i != section.get_symbols_num(); ++i) {
// TODO: this is boyscout code, caching the temporaries
// may be of worth.
auto tmp = read_symbol(section, i);
if (tmp.sect_idx == SHN_UNDEF && !tmp.name.empty()) {
r.push_back(std::move(tmp.name));
}
}
return r;
}
inline
const std::unordered_map<
std::string,
std::pair<ELFIO::Elf64_Addr, ELFIO::Elf_Xword>>& symbol_addresses()
{
using namespace ELFIO;
using namespace std;
static unordered_map<string, pair<Elf64_Addr, Elf_Xword>> r;
static once_flag f;
call_once(f, []() {
dl_iterate_phdr([](dl_phdr_info* info, size_t, void*) {
static constexpr const char self[] = "/proc/self/exe";
elfio reader;
static unsigned int iter = 0u;
if (reader.load(!iter++ ? self : info->dlpi_name)) {
auto it = find_section_if(
reader, [](const class section* x) {
return x->get_type() == SHT_SYMTAB;
});
if (it) {
const symbol_section_accessor symtab{reader, it};
for (auto i = 0u; i != symtab.get_symbols_num(); ++i) {
auto tmp = read_symbol(symtab, i);
if (tmp.type == STT_OBJECT &&
tmp.sect_idx != SHN_UNDEF) {
r.emplace(
move(tmp.name),
make_pair(tmp.value, tmp.size));
}
}
}
}
return 0;
}, nullptr);
});
return r;
}
inline
const std::vector<hsa_agent_t>& all_agents()
{
using namespace std;
static vector<hsa_agent_t> r;
static once_flag f;
call_once(f, []() {
for (auto&& acc : hc::accelerator::get_all()) {
if (acc.is_hsa_accelerator()) {
r.push_back(
*static_cast<hsa_agent_t*>(acc.get_hsa_agent()));
}
}
});
return r;
}
inline
void associate_code_object_symbols_with_host_allocation(
const ELFIO::elfio& reader,
const ELFIO::elfio& self_reader,
ELFIO::section* code_object_dynsym,
ELFIO::section* process_symtab,
hsa_agent_t agent,
hsa_executable_t executable)
{
using namespace ELFIO;
using namespace std;
if (!code_object_dynsym || !process_symtab) return;
const auto undefined_symbols = copy_names_of_undefined_symbols(
symbol_section_accessor{reader, code_object_dynsym});
for (auto&& x : undefined_symbols) {
using RAII_global =
unique_ptr<void, decltype(hsa_amd_memory_unlock)*>;
static unordered_map<string, RAII_global> globals;
static once_flag f;
call_once(f, [=]() { globals.reserve(symbol_addresses().size()); });
if (globals.find(x) != globals.cend()) return;
const auto it1 = symbol_addresses().find(x);
if (it1 == symbol_addresses().cend()) {
throw runtime_error{"Global symbol: " + x + " is undefined."};
}
static mutex mtx;
lock_guard<mutex> lck{mtx};
if (globals.find(x) != globals.cend()) return;
void* host_ptr =
reinterpret_cast<void*>(it1->second.first);
void* agent_ptr = nullptr;
hsa_amd_memory_lock(
host_ptr,
it1->second.second,
// Awful cast because ROCr interface is misspecified.
const_cast<hsa_agent_t*>(all_agents().data()),
all_agents().size(),
&agent_ptr);
hsa_executable_agent_global_variable_define(
executable, agent, x.c_str(), agent_ptr);
globals.emplace(x, RAII_global{host_ptr, hsa_amd_memory_unlock});
}
}
inline
hsa_code_object_reader_t load_code_object_and_freeze_executable(
void* elf,
std::size_t byte_cnt,
hsa_agent_t agent,
hsa_executable_t executable)
{ // TODO: the following sequence is inefficient, should be refactored
// into a single load of the file and subsequent ELFIO
// processing.
using namespace std;
hsa_code_object_reader_t r = {};
hsa_code_object_reader_create_from_memory(elf, byte_cnt, &r);
hsa_executable_load_agent_code_object(
executable, agent, r, nullptr, nullptr);
hsa_executable_freeze(executable, nullptr);
return r;
}
}
namespace hc {
// printf buffer size (in number of packets, see hc_printf.hpp)
constexpr unsigned int default_printf_buffer_size = 2048;
// address of the global printf buffer in host coherent system memory
PrintfPacket* printf_buffer = nullptr;
// store the address of agent accessible hc::printf_buffer;
PrintfPacket** printf_buffer_locked_va = nullptr;
std::mutex printf_buffer_lock;
} // namespace hc
namespace Kalmar {
enum class HCCRuntimeStatus{
// No error
HCCRT_STATUS_SUCCESS = 0x0,
// A generic error
HCCRT_STATUS_ERROR = 0x2000,
// The maximum number of outstanding AQL packets in a queue has been reached
HCCRT_STATUS_ERROR_COMMAND_QUEUE_OVERFLOW = 0x2001
};
const char* getHCCRuntimeStatusMessage(const HCCRuntimeStatus status) {
const char* message = nullptr;
switch(status) {
//HCCRT_CASE_STATUS_STRING(HCCRT_STATUS_SUCCESS,"Success");
case HCCRuntimeStatus::HCCRT_STATUS_SUCCESS:
message = "Success"; break;
case HCCRuntimeStatus::HCCRT_STATUS_ERROR:
message = "Generic error"; break;
case HCCRuntimeStatus::HCCRT_STATUS_ERROR_COMMAND_QUEUE_OVERFLOW:
message = "Command queue overflow"; break;
default:
message = "Unknown error code"; break;
};
return message;
}
inline static void checkHCCRuntimeStatus(const HCCRuntimeStatus status, const unsigned int line, hsa_queue_t* q=nullptr) {
if (status != HCCRuntimeStatus::HCCRT_STATUS_SUCCESS) {
fprintf(stderr, "### HCC runtime error: %s at %s line:%d\n", getHCCRuntimeStatusMessage(status), __FILENAME__, line);
std::string m("HCC Runtime Error - ");
m += getHCCRuntimeStatusMessage(status);
throw Kalmar::runtime_exception(m.c_str(), 0);
//if (q != nullptr)
// assert(HSA_STATUS_SUCCESS == hsa_queue_destroy(q));
//assert(HSA_STATUS_SUCCESS == hsa_shut_down());
//exit(-1);
}
}
} // namespace Kalmar
extern "C" void PushArgImpl(void *ker, int idx, size_t sz, const void *v);
extern "C" void PushArgPtrImpl(void *ker, int idx, size_t sz, const void *v);
// forward declaration
namespace Kalmar {
class HSAQueue;
class HSADevice;
namespace CLAMP {
void LoadInMemoryProgram(KalmarQueue*);
} // namespace CLAMP
} // namespace Kalmar
///
/// kernel compilation / kernel launching
///
/// modeling of HSA executable
class HSAExecutable {
private:
hsa_code_object_reader_t hsaCodeObjectReader;
hsa_executable_t hsaExecutable;
friend class HSAKernel;
friend class Kalmar::HSADevice;
public:
HSAExecutable(hsa_executable_t _hsaExecutable,
hsa_code_object_reader_t _hsaCodeObjectReader) :
hsaExecutable(_hsaExecutable),
hsaCodeObjectReader(_hsaCodeObjectReader) {}
~HSAExecutable() {
hsa_status_t status;
DBOUT(DB_INIT, "HSAExecutable::~HSAExecutable\n");
status = hsa_executable_destroy(hsaExecutable);
STATUS_CHECK(status, __LINE__);
status = hsa_code_object_reader_destroy(hsaCodeObjectReader);
STATUS_CHECK(status, __LINE__);
}
template<typename T>
void setSymbolToValue(const char* symbolName, T value) {
hsa_status_t status;
// get symbol
hsa_executable_symbol_t symbol;
hsa_agent_t agent;
status = hsa_executable_get_symbol_by_name(hsaExecutable, symbolName, const_cast<hsa_agent_t*>(&agent), &symbol);
STATUS_CHECK_SYMBOL(status, symbolName, __LINE__);
// get address of symbol
uint64_t symbol_address;
status = hsa_executable_symbol_get_info(symbol,
HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
&symbol_address);
STATUS_CHECK(status, __LINE__);
// set the value of symbol
T* symbol_ptr = (T*)symbol_address;
*symbol_ptr = value;
}
};
class HSAKernel {
private:
std::string kernelName;
std::string shortKernelName; // short handle, format selectable with HCC_DB_KERNEL_NAME
HSAExecutable* executable;
uint64_t kernelCodeHandle;
hsa_executable_symbol_t hsaExecutableSymbol;
uint32_t static_group_segment_size;
uint32_t private_segment_size;
uint16_t workitem_vgpr_count;
friend class HSADispatch;
public:
HSAKernel(std::string &_kernelName, const std::string &x_shortKernelName, HSAExecutable* _executable,
hsa_executable_symbol_t _hsaExecutableSymbol,
uint64_t _kernelCodeHandle) :
kernelName(_kernelName),
shortKernelName(x_shortKernelName),
executable(_executable),
hsaExecutableSymbol(_hsaExecutableSymbol),
kernelCodeHandle(_kernelCodeHandle) {
if (shortKernelName.empty()) {
shortKernelName = "<unknown_kernel>";
}
hsa_status_t status =
hsa_executable_symbol_get_info(
_hsaExecutableSymbol,
HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE,
&this->static_group_segment_size);
STATUS_CHECK(status, __LINE__);
status =
hsa_executable_symbol_get_info(
_hsaExecutableSymbol,
HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE,
&this->private_segment_size);
STATUS_CHECK(status, __LINE__);
workitem_vgpr_count = 0;
uint16_t ext_version_major = 1;
uint16_t ext_version_minor = 0;
bool ext_supported = false;
status =
hsa_system_major_extension_supported(
HSA_EXTENSION_AMD_LOADER,
ext_version_major,
&ext_version_minor,
&ext_supported);
STATUS_CHECK(status, __LINE__);
if(!ext_supported)
throw Kalmar::runtime_exception("HSA_EXTENSION_AMD_LOADER not supported.", 0);
hsa_ven_amd_loader_1_01_pfn_t ext_table = {nullptr};
status =
hsa_system_get_major_extension_table(
HSA_EXTENSION_AMD_LOADER,
1,
sizeof(ext_table),
&ext_table);
STATUS_CHECK(status, __LINE__);
if (nullptr != ext_table.hsa_ven_amd_loader_query_host_address) {
const amd_kernel_code_t* akc = nullptr;
status =
ext_table.hsa_ven_amd_loader_query_host_address(
reinterpret_cast<const void*>(kernelCodeHandle),
reinterpret_cast<const void**>(&akc));
STATUS_CHECK(status, __LINE__);
workitem_vgpr_count = akc->workitem_vgpr_count;
}
DBOUTL(DB_CODE, "Create kernel " << shortKernelName << " vpr_cnt=" << this->workitem_vgpr_count
<< " static_group_segment_size=" << this->static_group_segment_size
<< " private_segment_size=" << this->private_segment_size );
}
//TODO - fix this so all Kernels set the _kernelName to something sensible.
const std::string &getKernelName() const { return shortKernelName; }
const std::string &getLongKernelName() const { return kernelName; }
~HSAKernel() {
DBOUT(DB_INIT, "HSAKernel::~HSAKernel\n");
}
}; // end of HSAKernel
// Stores the device and queue for op coordinate:
struct HSAOpCoord
{
HSAOpCoord(Kalmar::HSAQueue *queue);
int _deviceId;
uint64_t _queueId;
};
// Base class for the other HSA ops:
class HSAOp : public Kalmar::KalmarAsyncOp {
public:
HSAOp(hc::HSAOpId id, Kalmar::KalmarQueue *queue, hc::hcCommandKind commandKind);
~HSAOp();
const HSAOpCoord opCoord() const { return _opCoord; };
void* getNativeHandle() override { return &_signal; }
virtual bool barrierNextSyncNeedsSysRelease() const { return 0; };
virtual bool barrierNextKernelNeedsSysAcquire() const { return 0; };
virtual void activityReport() = 0;
Kalmar::HSAQueue *hsaQueue() const;
bool isReady() override;
virtual void setSelf(const std::shared_ptr<HSAOp> &self) { _self = self; }
// Factory method to build HSAOp.
template<typename T, typename ... Ts>
static std::shared_ptr<T> buildOp(Ts ... args) {
auto op = std::make_shared<T>(args...);
op->setSelf(op);
return op;
}
// SharedWrapper is a utility class to keep an extra refernce to HSAOp.
// So when the HSA signal of an HSAOp is registered to be notified in a
// ROCR runtime signal callback, the HSAOp is guaranteed to exist.
struct SharedWrapper {
std::shared_ptr<HSAOp> _op;
SharedWrapper(const std::weak_ptr<HSAOp> &op) : _op(op) {}
~SharedWrapper() { _op = nullptr; }
};
static bool signalCallback(hsa_signal_value_t value, void *arg) {
if (arg != nullptr) {
SharedWrapper *wrapper = reinterpret_cast<SharedWrapper*>(arg);
wrapper->_op->activityReport();
delete wrapper;
}
return false; // do not re-use callback.
}
virtual void registerSignalCallback();
protected:
HSAOpCoord _opCoord;
hsa_signal_t _signal;
hsa_agent_t _agent;
activity_prof::ActivityProf _activity_prof;
std::atomic_flag _dispose_flag;
// A weak pointer to the instance itself.
// Helps to track reference count of shared_ptr<HSAOp> within
// HSAQueue::asyncOps.
std::weak_ptr<HSAOp> _self;
};
std::ostream& operator<<(std::ostream& os, const HSAOp & op);
class HSACopy : public HSAOp {
private:
bool isAsync; // copy was performed asynchronously
bool isSingleStepCopy;; // copy was performed on fast-path via a single call to the HSA copy routine
bool isPeerToPeer;
uint64_t apiStartTick;
hsa_wait_state_t waitMode;
// If copy is dependent on another operation, record reference here.
// keep a reference which prevents those ops from being deleted until this op is deleted.
std::shared_ptr<HSAOp> depAsyncOp;
const Kalmar::HSADevice* copyDevice; // Which device did the copy.
// source pointer
const void* src;
// destination pointer
void* dst;
// bytes to be copied
size_t sizeBytes;
public:
const Kalmar::HSADevice* getCopyDevice() const { return copyDevice; } ; // Which device did the copy.
void setWaitMode(Kalmar::hcWaitMode mode) override {
switch (mode) {
case Kalmar::hcWaitModeBlocked:
waitMode = HSA_WAIT_STATE_BLOCKED;
break;
case Kalmar::hcWaitModeActive:
waitMode = HSA_WAIT_STATE_ACTIVE;
break;
}
}
std::string getCopyCommandString()
{
using namespace Kalmar;
std::string s;
switch (getCommandKind()) {
case hcMemcpyHostToHost:
s += "HostToHost";
break;
case hcMemcpyHostToDevice:
s += "HostToDevice";
break;
case hcMemcpyDeviceToHost:
s += "DeviceToHost";
break;
case hcMemcpyDeviceToDevice:
if (isPeerToPeer) {
s += "PeerToPeer";
} else {
s += "DeviceToDevice";
}
break;
default:
s += "UnknownCopy";
break;
};
s += isAsync ? "_async" : "_sync";
s += isSingleStepCopy ? "_fast" : "_slow";
return s;
}
// Copy mode will be set later on.
// HSA signals would be waited in HSA_WAIT_STATE_ACTIVE by default for HSACopy instances
HSACopy(Kalmar::KalmarQueue *queue, const void* src_, void* dst_, size_t sizeBytes_);
~HSACopy() {
wait();
dispose();
}
void enqueueAsyncCopyCommand(const Kalmar::HSADevice *copyDevice, const hc::AmPointerInfo &srcPtrInfo, const hc::AmPointerInfo &dstPtrInfo);
hsa_status_t enqueueAsyncCopy2dCommand(size_t width, size_t height, size_t srcPitch, size_t dstPitch, const Kalmar::HSADevice *copyDevice, const hc::AmPointerInfo &srcPtrInfo, const hc::AmPointerInfo &dstPtrInfo);
// wait for the async copy to complete
void wait() override;
void activityReport() override;
void dispose();
uint64_t getTimestampFrequency() override {
// get system tick frequency
uint64_t timestamp_frequency_hz = 0L;
hsa_system_get_info(HSA_SYSTEM_INFO_TIMESTAMP_FREQUENCY, ×tamp_frequency_hz);
return timestamp_frequency_hz;
}
uint64_t getBeginTimestamp() override;
uint64_t getEndTimestamp() override;
uint64_t getStartTick();
uint64_t getSystemTicks();
// synchronous version of copy
void syncCopy();
void syncCopyExt(hc::hcCommandKind copyDir,
const hc::AmPointerInfo &srcPtrInfo, const hc::AmPointerInfo &dstPtrInfo,
const Kalmar::HSADevice *copyDevice, bool forceUnpinnedCopy);
hsa_status_t syncCopy2DExt(hc::hcCommandKind copyDir,
const hc::AmPointerInfo &srcPtrInfo, const hc::AmPointerInfo &dstPtrInfo,size_t width, size_t height, size_t srcPitch, size_t dstPitch,
const Kalmar::HSADevice *copyDevice, bool forceUnpinnedCopy);
private:
void hcc_memory_async_copy(Kalmar::hcCommandKind copyKind, const Kalmar::HSADevice *copyDevice,
const hc::AmPointerInfo &dstPtrInfo, const hc::AmPointerInfo &srcPtrInfo,
size_t sizeBytes);
hsa_status_t hcc_memory_async_copy_rect(Kalmar::hcCommandKind copyKind, const Kalmar::HSADevice *copyDevice,
const hc::AmPointerInfo &dstPtrInfo, const hc::AmPointerInfo &srcPtrInfo,
size_t width, size_t height, size_t srcPitch, size_t dstPitch);
}; // end of HSACopy
class HSABarrier : public HSAOp {
private:
hsa_wait_state_t waitMode;
// prior dependencies
// maximum up to 5 prior dependencies could be associated with one
// HSABarrier instance
int depCount;
hc::memory_scope _acquire_scope;
// capture the state of _nextSyncNeedsSysRelease and _nextKernelNeedsSysAcquire after
// the barrier is issued. Cross-queue synchronziation commands which synchronize
// with the barrier (create_blocking_marker) then can transer the correct "needs" flags.
bool _barrierNextSyncNeedsSysRelease;
bool _barrierNextKernelNeedsSysAcquire;
public:
uint16_t header; // stores header of AQL packet. Preserve so we can see flushes associated with this barrier.
// array of all operations that this op depends on.
// This array keeps a reference which prevents those ops from being deleted until this op is deleted.
std::shared_ptr<HSAOp> depAsyncOps [HSA_BARRIER_DEP_SIGNAL_CNT];
std::string depAsyncOpsStr;
public:
void acquire_scope(hc::memory_scope acquireScope) { _acquire_scope = acquireScope;};
bool barrierNextSyncNeedsSysRelease() const override { return _barrierNextSyncNeedsSysRelease; };
bool barrierNextKernelNeedsSysAcquire() const override { return _barrierNextKernelNeedsSysAcquire; };
void setWaitMode(Kalmar::hcWaitMode mode) override {
switch (mode) {
case Kalmar::hcWaitModeBlocked:
waitMode = HSA_WAIT_STATE_BLOCKED;
break;
case Kalmar::hcWaitModeActive:
waitMode = HSA_WAIT_STATE_ACTIVE;
break;
}
}
// constructor with 1 prior dependency
HSABarrier(Kalmar::KalmarQueue *queue, std::shared_ptr <Kalmar::KalmarAsyncOp> dependent_op) :
HSAOp(hc::HSA_OP_ID_BARRIER, queue, Kalmar::hcCommandMarker),
_acquire_scope(hc::no_scope),
_barrierNextSyncNeedsSysRelease(false),
_barrierNextKernelNeedsSysAcquire(false),
waitMode(HSA_WAIT_STATE_BLOCKED)
{
if (dependent_op != nullptr) {
assert (dependent_op->getCommandKind() == Kalmar::hcCommandMarker);
depAsyncOps[0] = std::static_pointer_cast<HSAOp> (dependent_op);
depCount = 1;
if ((HCC_PROFILE & HCC_PROFILE_TRACE) && (HCC_PROFILE_VERBOSE & HCC_PROFILE_VERBOSE_BARRIER)) {
std::stringstream depss;
depss << " deps=" << *depAsyncOps[0];
depAsyncOpsStr = depss.str();
}
} else {
depCount = 0;
}
}
// constructor with at most 5 prior dependencies
HSABarrier(Kalmar::KalmarQueue *queue, int count, std::shared_ptr <Kalmar::KalmarAsyncOp> *dependent_op_array) :
HSAOp(hc::HSA_OP_ID_BARRIER, queue, Kalmar::hcCommandMarker),
_acquire_scope(hc::no_scope),
_barrierNextSyncNeedsSysRelease(false),
_barrierNextKernelNeedsSysAcquire(false),
waitMode(HSA_WAIT_STATE_BLOCKED),
depCount(0)
{
if ((count >= 0) && (count <= 5)) {
for (int i = 0; i < count; ++i) {
if (dependent_op_array[i]) {
// squish null ops
depAsyncOps[depCount] = std::static_pointer_cast<HSAOp> (dependent_op_array[i]);
depCount++;