23 #ifndef HIP_SRC_HIP_HCC_INTERNAL_H 24 #define HIP_SRC_HIP_HCC_INTERNAL_H 28 #include <unordered_map> 31 #include "hsa/hsa_ext_amd.h" 32 #include "hip/hip_runtime.h" 33 #include "hip_prof_api.h" 38 #if (__hcc_workweek__ < 16354) 39 #error("This version of HIP requires a newer version of HCC."); 44 #if defined(__HCC_HAS_EXTENDED_AM_MEMTRACKER_UPDATE) and \ 45 (__HCC_HAS_EXTENDED_AM_MEMTRACKER_UPDATE != 0) 46 #define USE_APP_PTR_FOR_CTX 1 58 extern const int release;
62 extern int HIP_LAUNCH_BLOCKING;
63 extern int HIP_API_BLOCKING;
65 extern int HIP_PRINT_ENV;
66 extern int HIP_PROFILE_API;
70 extern int HIP_STAGING_SIZE;
71 extern int HIP_STREAM_SIGNALS;
72 extern int HIP_VISIBLE_DEVICES;
73 extern int HIP_FORCE_P2P_HOST;
75 extern int HIP_HOST_COHERENT;
77 extern int HIP_HIDDEN_FREE_MEM;
80 extern int HIP_SYNC_HOST_ALLOC;
81 extern int HIP_SYNC_STREAM_WAIT;
83 extern int HIP_SYNC_NULL_STREAM;
84 extern int HIP_INIT_ALLOC;
85 extern int HIP_FORCE_NULL_STREAM;
87 extern int HIP_SYNC_FREE;
89 extern int HIP_DUMP_CODE_OBJECT;
92 extern int HCC_OPT_FLUSH;
99 int tid()
const {
return _shortTid; };
100 pid_t pid()
const {
return _pid; };
101 uint64_t incApiSeqNum() {
return ++_apiSeqNum; };
102 uint64_t apiSeqNum()
const {
return _apiSeqNum; };
113 static const uint64_t MAX_TRIGGER = std::numeric_limits<uint64_t>::max();
115 void print(
int tid) {
116 std::cout <<
"Enabling tracing for ";
117 for (
auto iter = _profTrigger.begin(); iter != _profTrigger.end(); iter++) {
118 std::cout <<
"tid:" << tid <<
"." << *iter <<
",";
123 uint64_t nextTrigger() {
return _profTrigger.empty() ? MAX_TRIGGER : _profTrigger.back(); };
124 void add(uint64_t trigger) { _profTrigger.push_back(trigger); };
125 void sort() { std::sort(_profTrigger.begin(), _profTrigger.end(), std::greater<int>()); };
128 std::vector<uint64_t> _profTrigger;
134 extern thread_local hipError_t tls_lastHipError;
135 extern thread_local
TidInfo tls_tidInfo;
136 extern thread_local
bool tls_getPrimaryCtx;
138 extern std::vector<ProfTrigger> g_dbStartTriggers;
139 extern std::vector<ProfTrigger> g_dbStopTriggers;
149 #define KNRM "\x1B[0m" 150 #define KRED "\x1B[31m" 151 #define KGRN "\x1B[32m" 152 #define KYEL "\x1B[33m" 153 #define KBLU "\x1B[34m" 154 #define KMAG "\x1B[35m" 155 #define KCYN "\x1B[36m" 156 #define KWHT "\x1B[37m" 158 extern const char* API_COLOR;
159 extern const char* API_COLOR_END;
165 #define EVENT_THREAD_SAFE 1 167 #define STREAM_THREAD_SAFE 1 169 #define CTX_THREAD_SAFE 1 171 #define DEVICE_THREAD_SAFE 1 176 #define COMPILE_HIP_DB 1 184 #define COMPILE_HIP_TRACE_API 0x3 189 #ifndef COMPILE_HIP_ATP_MARKER 190 #define COMPILE_HIP_ATP_MARKER 0 199 #if COMPILE_HIP_ATP_MARKER 200 #include "CXLActivityLogger.h" 201 #define MARKER_BEGIN(markerName, group) amdtBeginMarker(markerName, group, nullptr); 202 #define MARKER_END() amdtEndMarker(); 203 #define RESUME_PROFILING amdtResumeProfiling(AMDT_ALL_PROFILING); 204 #define STOP_PROFILING amdtStopProfiling(AMDT_ALL_PROFILING); 207 #define MARKER_BEGIN(markerName, group) 209 #define RESUME_PROFILING 210 #define STOP_PROFILING 216 #define TRACE_ALL 0 // 0x01 217 #define TRACE_KCMD 1 // 0x02, kernel command 218 #define TRACE_MCMD 2 // 0x04, memory command 219 #define TRACE_MEM 3 // 0x08, memory allocation or deallocation. 220 #define TRACE_SYNC 4 // 0x10, synchronization (host or hipStreamWaitEvent) 221 #define TRACE_QUERY 5 // 0x20, hipEventRecord, hipEventQuery, hipStreamQuery 232 #define DB_MAX_FLAG 6 239 const char* _shortName;
243 static const DbName dbName[] = {
245 {KYEL,
"sync"}, {KCYN,
"mem"}, {KMAG,
"copy"}, {KRED,
"warn"},
251 #define tprintf(trace_level, ...) \ 253 if (HIP_DB & (1 << (trace_level))) { \ 255 snprintf(msgStr, sizeof(msgStr), __VA_ARGS__); \ 256 fprintf(stderr, " %ship-%s pid:%d tid:%d:%s%s", dbName[trace_level]._color, \ 257 dbName[trace_level]._shortName, tls_tidInfo.pid(), tls_tidInfo.tid(), msgStr, KNRM); \ 262 #define tprintf(trace_level, ...) 266 static inline uint64_t getTicks() {
return hc::get_system_ticks(); }
269 extern uint64_t recordApiTrace(std::string* fullStr,
const std::string& apiStr);
271 #if COMPILE_HIP_ATP_MARKER || (COMPILE_HIP_TRACE_API & 0x1) 272 #define API_TRACE(forceTrace, ...) \ 273 uint64_t hipApiStartTick = 0; \ 275 tls_tidInfo.incApiSeqNum(); \ 277 (HIP_PROFILE_API || (COMPILE_HIP_DB && (HIP_TRACE_API & (1 << TRACE_ALL))))) { \ 278 std::string apiStr = std::string(__func__) + " (" + ToString(__VA_ARGS__) + ')'; \ 279 std::string fullStr; \ 280 hipApiStartTick = recordApiTrace(&fullStr, apiStr); \ 281 if (HIP_PROFILE_API == 0x1) { \ 282 MARKER_BEGIN(__func__, "HIP") \ 283 } else if (HIP_PROFILE_API == 0x2) { \ 284 MARKER_BEGIN(fullStr.c_str(), "HIP"); \ 291 #define API_TRACE(IS_CMD, ...) tls_tidInfo.incApiSeqNum(); 294 #define HIP_SET_DEVICE() ihipDeviceSetState(); 299 #define HIP_INIT_API(cid, ...) \ 300 hip_impl::hip_init(); \ 301 API_TRACE(0, __VA_ARGS__); \ 302 HIP_CB_SPAWNER_OBJECT(cid); 308 #define HIP_INIT_SPECIAL_API(cid, tbit, ...) \ 309 hip_impl::hip_init(); \ 310 API_TRACE((HIP_TRACE_API & (1 << tbit)), __VA_ARGS__); \ 311 HIP_CB_SPAWNER_OBJECT(cid); 317 #define ihipLogStatus(hipStatus) \ 319 hipError_t localHipStatus = hipStatus; \ 320 tls_lastHipError = localHipStatus; \ 322 if ((COMPILE_HIP_TRACE_API & 0x2) && HIP_TRACE_API & (1 << TRACE_ALL)) { \ 323 auto ticks = getTicks() - hipApiStartTick; \ 324 fprintf(stderr, " %ship-api pid:%d tid:%d.%lu %-30s ret=%2d (%s)>> +%lu ns%s\n", \ 325 (localHipStatus == 0) ? API_COLOR : KRED, tls_tidInfo.pid(), tls_tidInfo.tid(), \ 326 tls_tidInfo.apiSeqNum(), __func__, localHipStatus, \ 327 ihipErrorString(localHipStatus), ticks, API_COLOR_END); \ 329 if (HIP_PROFILE_API) { \ 359 #define HIP_IPC_RESERVED_SIZE 24 366 char reserved[HIP_IPC_RESERVED_SIZE];
371 std::string fileName;
372 hsa_executable_t executable = {};
373 hsa_code_object_reader_t coReader = {};
376 std::string, std::vector<std::pair<std::size_t, std::size_t>>> kernargs;
379 if (executable.handle) hsa_executable_destroy(executable);
380 if (coReader.handle) hsa_code_object_reader_destroy(coReader);
390 bool try_lock() {
return true; }
394 #if EVENT_THREAD_SAFE 395 typedef std::mutex EventMutex;
397 #warning "Stream thread-safe disabled" 401 #if STREAM_THREAD_SAFE 402 typedef std::mutex StreamMutex;
404 #warning "Stream thread-safe disabled" 410 typedef std::mutex CtxMutex;
413 #warning "Ctx thread-safe disabled" 416 #if DEVICE_THREAD_SAFE 417 typedef std::mutex DeviceMutex;
420 #warning "Device thread-safe disabled" 427 template <
typename T>
431 : _criticalData(&criticalData),
432 _autoUnlock(autoUnlock)
435 tprintf(DB_SYNC,
"locking criticalData=%p for %s..\n", _criticalData,
436 ToString(_criticalData->_parent).c_str());
437 _criticalData->_mutex.lock();
442 tprintf(DB_SYNC,
"auto-unlocking criticalData=%p for %s...\n", _criticalData,
443 ToString(_criticalData->_parent).c_str());
444 _criticalData->_mutex.unlock();
449 tprintf(DB_SYNC,
"unlocking criticalData=%p for %s...\n", _criticalData,
450 ToString(_criticalData->_parent).c_str());
451 _criticalData->_mutex.unlock();
455 T* operator->() {
return _criticalData; };
463 template <
typename MUTEX_TYPE>
467 void lock() { _mutex.lock(); }
468 void unlock() { _mutex.unlock(); }
469 bool try_lock() {
return _mutex.try_lock(); }
475 template <
typename MUTEX_TYPE>
479 : _kernelCnt(0), _av(av), _parent(parentStream){};
489 tprintf(DB_SYNC,
"munlocking criticalData=%p for %s...\n",
this,
490 ToString(this->_parent).c_str());
496 tprintf(DB_SYNC,
"mtry_locking=%d criticalData=%p for %s...\n", gotLock,
this,
497 ToString(this->_parent).c_str());
498 return gotLock ?
this :
nullptr;
505 hc::accelerator_view _av;
526 enum ScheduleMode { Auto, Spin, Yield };
527 typedef uint64_t SeqNum_t;
534 void locked_copySync(
void* dst,
const void* src,
size_t sizeBytes,
unsigned kind,
535 bool resolveOn =
true);
537 bool locked_copy2DSync(
void* dst,
const void* src,
size_t width,
size_t height,
size_t srcPitch,
size_t dstPitch,
unsigned kind,
538 bool resolveOn =
true);
540 void locked_copyAsync(
void* dst,
const void* src,
size_t sizeBytes,
unsigned kind);
542 bool locked_copy2DAsync(
void* dst,
const void* src,
size_t width,
size_t height,
size_t srcPitch,
size_t dstPitch,
unsigned kind);
544 void lockedSymbolCopySync(hc::accelerator& acc,
void* dst,
void* src,
size_t sizeBytes,
545 size_t offset,
unsigned kind);
546 void lockedSymbolCopyAsync(hc::accelerator& acc,
void* dst,
void* src,
size_t sizeBytes,
547 size_t offset,
unsigned kind);
553 void lockclose_postKernelCommand(
const char* kernelName, hc::accelerator_view* av,
bool unlockNotNeeded = 0);
558 hc::accelerator_view* locked_getAv() {
564 hc::completion_future locked_recordEvent(
hipEvent_t event);
567 void locked_eventWaitComplete(hc::completion_future& marker, hc::hcWaitMode waitMode);
572 hc::hcWaitMode waitMode()
const;
577 void launchModuleKernel(hc::accelerator_view av, hsa_signal_t signal, uint32_t blockDimX,
578 uint32_t blockDimY, uint32_t blockDimZ, uint32_t gridDimX,
579 uint32_t gridDimY, uint32_t gridDimZ, uint32_t groupSegmentSize,
580 uint32_t sharedMemBytes,
void* kernarg,
size_t kernSize,
591 bool isDefaultStream()
const {
return _id == 0; };
602 unsigned resolveMemcpyDirection(
bool srcInDeviceMem,
bool dstInDeviceMem);
603 void resolveHcMemcpyDirection(
unsigned hipMemKind,
const hc::AmPointerInfo* dstPtrInfo,
604 const hc::AmPointerInfo* srcPtrInfo, hc::hcCommandKind* hcCopyDir,
605 ihipCtx_t** copyDevice,
bool* forceUnpinnedCopy);
607 bool canSeeMemory(
const ihipCtx_t* thisCtx,
const hc::AmPointerInfo* dstInfo,
608 const hc::AmPointerInfo* srcInfo);
610 void addSymbolPtrToTracker(hc::accelerator& acc,
void* ptr,
size_t sizeBytes);
616 std::mutex _hasQueueLock;
621 friend std::ostream& operator<<(std::ostream& os,
const ihipStream_t& s);
624 ScheduleMode _scheduleMode;
633 : _stream(stream), _callback(callback), _userData(userData) {
643 enum hipEventStatus_t {
644 hipEventStatusUnitialized = 0,
645 hipEventStatusCreated = 1,
646 hipEventStatusRecording = 2,
647 hipEventStatusComplete = 3,
651 enum ihipEventType_t {
652 hipEventTypeIndependent,
653 hipEventTypeStartCommand,
654 hipEventTypeStopCommand,
660 _state = hipEventStatusCreated;
663 _type = hipEventTypeIndependent;
666 void marker(
const hc::completion_future& marker) { _marker = marker; };
667 hc::completion_future& marker() {
return _marker; }
668 uint64_t timestamp()
const {
return _timestamp; };
669 ihipEventType_t type()
const {
return _type; };
671 ihipEventType_t _type;
672 hipEventStatus_t _state;
677 hc::completion_future _marker;
683 template <
typename MUTEX_TYPE>
706 void attachToCompletionFuture(
const hc::completion_future* cf,
hipStream_t stream,
707 ihipEventType_t eventType);
708 std::pair<hipEventStatus_t, uint64_t> refreshEventStatus();
714 return _criticalData._eventData;
731 template <
typename MUTEX_TYPE>
735 : _parent(parentDevice), _ctxCount(0){};
742 std::list<ihipCtx_t*>& ctxs() {
return _ctxs; };
743 const std::list<ihipCtx_t*>& const_ctxs()
const {
return _ctxs; };
744 int getcount() {
return _ctxCount; };
751 std::list<ihipCtx_t*> _ctxs;
765 ihipDevice_t(
unsigned deviceId,
unsigned deviceCnt, hc::accelerator& acc);
769 ihipCtx_t* getPrimaryCtx()
const {
return _primaryCtx; };
777 hc::accelerator _acc;
778 hsa_agent_t _hsaAgent;
807 std::vector<char> _arguments;
812 template <
typename MUTEX_TYPE>
816 : _parent(parentCtx), _peerCnt(0) {
817 _peerAgents =
new hsa_agent_t[deviceCnt];
821 if (_peerAgents !=
nullptr) {
823 _peerAgents =
nullptr;
830 std::list<ihipStream_t*>& streams() {
return _streams; };
831 const std::list<ihipStream_t*>& const_streams()
const {
return _streams; };
835 bool isPeerWatcher(
const ihipCtx_t* peer);
839 void resetPeerWatchers(
ihipCtx_t* thisDevice);
840 void printPeerWatchers(FILE* f)
const;
842 uint32_t peerCnt()
const {
return _peerCnt; };
843 hsa_agent_t* peerAgents()
const {
return _peerAgents; };
847 std::list<ihipCtx_t*> _peers;
849 std::stack<ihipExec_t> _execStack;
857 std::list<ihipStream_t*> _streams;
865 hsa_agent_t* _peerAgents;
867 void recomputePeerAgents();
898 void locked_waitAllStreams();
899 void locked_syncDefaultStream(
bool waitOnSelf,
bool syncHost);
903 const ihipDevice_t* getDevice()
const {
return _device; };
904 int getDeviceNum()
const {
return _device->_deviceId; };
907 ihipDevice_t* getWriteableDevice()
const {
return _device; };
909 std::string toString()
const;
933 extern unsigned g_deviceCnt;
934 extern hsa_agent_t g_cpu_agent;
935 extern hsa_agent_t* g_allAgents;
939 extern void ihipInit();
940 extern const char* ihipErrorString(hipError_t);
941 extern ihipCtx_t* ihipGetTlsDefaultCtx();
942 extern void ihipSetTlsDefaultCtx(
ihipCtx_t* ctx);
943 extern hipError_t ihipSynchronize(
void);
944 extern void ihipCtxStackUpdate();
945 extern hipError_t ihipDeviceSetState();
948 ihipCtx_t* ihipGetPrimaryCtx(
unsigned deviceIndex);
950 const char* name, hsa_agent_t *agent);
954 hipError_t ihipStreamSynchronize(
hipStream_t stream);
958 inline std::ostream& operator<<(std::ostream& os,
const ihipStream_t& s) {
960 os << s.getDevice()->_deviceId;
967 inline std::ostream& operator<<(std::ostream& os,
const dim3& s) {
978 inline std::ostream& operator<<(std::ostream& os,
const gl_dim3& s) {
990 inline std::ostream& operator<<(std::ostream& os,
const hipEvent_t& e) {
991 os <<
"event:" << std::hex << static_cast<void*>(e);
995 inline std::ostream& operator<<(std::ostream& os,
const ihipCtx_t* c) {
996 os <<
"ctx:" <<
static_cast<const void*
>(c) <<
".dev:" << c->getDevice()->_deviceId;
1003 hipError_t memcpyAsync(
void* dst,
const void* src,
size_t sizeBytes, hipMemcpyKind kind,
Definition: hip_hcc_internal.h:237
Definition: hip_hcc_internal.h:763
Definition: hip_hcc_internal.h:464
Definition: hip_hcc_internal.h:112
Definition: hip_hcc_internal.h:387
Definition: hip_hcc_internal.h:360
uint32_t x
x
Definition: hip_runtime_api.h:270
Definition: grid_launch.h:17
Definition: hip_module.cpp:106
Definition: hip_hcc_internal.h:802
Definition: hip_hcc_internal.h:883
Definition: hip_runtime_api.h:269
uint32_t y
y
Definition: hip_runtime_api.h:271
void(* hipStreamCallback_t)(hipStream_t stream, hipError_t status, void *userData)
Definition: hip_runtime_api.h:843
Definition: hip_hcc_internal.h:630
Definition: hip_hcc_internal.h:732
unsigned _computeUnits
Number of compute units supported by the device:
Definition: hip_hcc_internal.h:781
uint32_t z
z
Definition: hip_runtime_api.h:272
Definition: hip_runtime_api.h:83
Definition: hip_hcc_internal.h:658
Definition: hip_hcc_internal.h:684
Definition: hip_hcc_internal.h:1002
Definition: hip_hcc_internal.h:336
Definition: hip_hcc_internal.h:703
Definition: hip_hcc_internal.h:813
Definition: hip_hcc_internal.h:524
Definition: hip_hcc_internal.h:476
hipError_t hipEventRecord(hipEvent_t event, hipStream_t stream)
Record an event in the specified stream.
Definition: hip_event.cpp:110
hsa_amd_ipc_memory_t ipc_handle
ipc memory handle on ROCr
Definition: hip_hcc_internal.h:363
Definition: hip_hcc_internal.h:428
Definition: hip_hcc_internal.h:370
hipError_t hipStreamQuery(hipStream_t stream)
Return #hipSuccess if all of the operations in the specified stream have completed, or #hipErrorNotReady if not.
Definition: hip_stream.cpp:161
Definition: hip_hcc_internal.h:95