-
Notifications
You must be signed in to change notification settings - Fork 98
/
amd_gpu_agent.cpp
1643 lines (1439 loc) · 60.1 KB
/
amd_gpu_agent.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
////////////////////////////////////////////////////////////////////////////////
//
// The University of Illinois/NCSA
// Open Source License (NCSA)
//
// Copyright (c) 2014-2020, Advanced Micro Devices, Inc. All rights reserved.
//
// Developed by:
//
// AMD Research and AMD HSA Software Development
//
// Advanced Micro Devices, Inc.
//
// www.amd.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal with the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
// - Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimers in
// the documentation and/or other materials provided with the distribution.
// - Neither the names of Advanced Micro Devices, Inc,
// nor the names of its contributors may be used to endorse or promote
// products derived from this Software without specific prior written
// permission.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS WITH THE SOFTWARE.
//
////////////////////////////////////////////////////////////////////////////////
#include "core/inc/amd_gpu_agent.h"
#include <algorithm>
#include <atomic>
#include <cstring>
#include <climits>
#include <map>
#include <string>
#include <vector>
#include <memory>
#include <utility>
#include <iomanip>
#include "core/inc/amd_aql_queue.h"
#include "core/inc/amd_blit_kernel.h"
#include "core/inc/amd_blit_sdma.h"
#include "core/inc/amd_gpu_pm4.h"
#include "core/inc/amd_gpu_shaders.h"
#include "core/inc/amd_memory_region.h"
#include "core/inc/interrupt_signal.h"
#include "core/inc/isa.h"
#include "core/inc/runtime.h"
#include "core/util/os.h"
#include "inc/hsa_ext_image.h"
#include "inc/hsa_ven_amd_aqlprofile.h"
// Size of scratch (private) segment pre-allocated per thread, in bytes.
#define DEFAULT_SCRATCH_BYTES_PER_THREAD 2048
#define MAX_WAVE_SCRATCH 8387584 // See COMPUTE_TMPRING_SIZE.WAVESIZE
#define MAX_NUM_DOORBELLS 0x400
namespace rocr {
namespace core {
extern HsaApiTable hsa_internal_api_table_;
} // namespace core
namespace AMD {
GpuAgent::GpuAgent(HSAuint32 node, const HsaNodeProperties& node_props, bool xnack_mode,
uint32_t index)
: GpuAgentInt(node),
properties_(node_props),
current_coherency_type_(HSA_AMD_COHERENCY_TYPE_COHERENT),
scratch_used_large_(0),
queues_(),
is_kv_device_(false),
trap_code_buf_(NULL),
trap_code_buf_size_(0),
doorbell_queue_map_(NULL),
memory_bus_width_(0),
memory_max_frequency_(0),
enum_index_(index),
ape1_base_(0),
ape1_size_(0),
scratch_cache_(
[this](void* base, size_t size, bool large) { ReleaseScratch(base, size, large); }) {
const bool is_apu_node = (properties_.NumCPUCores > 0);
profile_ = (is_apu_node) ? HSA_PROFILE_FULL : HSA_PROFILE_BASE;
HSAKMT_STATUS err = hsaKmtGetClockCounters(node_id(), &t0_);
t1_ = t0_;
historical_clock_ratio_ = 0.0;
assert(err == HSAKMT_STATUS_SUCCESS && "hsaGetClockCounters error");
const core::Isa *isa_base = core::IsaRegistry::GetIsa(
core::Isa::Version(node_props.EngineId.ui32.Major,
node_props.EngineId.ui32.Minor,
node_props.EngineId.ui32.Stepping));
if (!isa_base) {
throw AMD::hsa_exception(HSA_STATUS_ERROR_INVALID_ISA, "Agent creation failed.\nThe GPU node has an unrecognized id.\n");
}
rocr::core::IsaFeature sramecc = rocr::core::IsaFeature::Unsupported;
if (isa_base->IsSrameccSupported()) {
sramecc = node_props.Capability.ui32.SRAM_EDCSupport == 1 ? core::IsaFeature::Enabled
: core::IsaFeature::Disabled;
}
rocr::core::IsaFeature xnack = rocr::core::IsaFeature::Unsupported;
if (isa_base->IsXnackSupported()) {
// TODO: This needs to be obtained form KFD once HMM implemented.
xnack = xnack_mode ? core::IsaFeature::Enabled
: core::IsaFeature::Disabled;
}
// Set instruction set architecture via node property, only on GPU device.
isa_ = (core::Isa*)core::IsaRegistry::GetIsa(
core::Isa::Version(node_props.EngineId.ui32.Major, node_props.EngineId.ui32.Minor,
node_props.EngineId.ui32.Stepping), sramecc, xnack);
assert(isa_ != nullptr && "ISA registry inconsistency.");
// Check if the device is Kaveri, only on GPU device.
if (isa_->GetMajorVersion() == 7 && isa_->GetMinorVersion() == 0 &&
isa_->GetStepping() == 0) {
is_kv_device_ = true;
}
current_coherency_type((profile_ == HSA_PROFILE_FULL)
? HSA_AMD_COHERENCY_TYPE_COHERENT
: HSA_AMD_COHERENCY_TYPE_NONCOHERENT);
max_queues_ = core::Runtime::runtime_singleton_->flag().max_queues();
#if !defined(HSA_LARGE_MODEL) || !defined(__linux__)
if (max_queues_ == 0) {
max_queues_ = 10;
}
max_queues_ = std::min(10U, max_queues_);
#else
if (max_queues_ == 0) {
max_queues_ = 128;
}
max_queues_ = std::min(128U, max_queues_);
#endif
// Populate region list.
InitRegionList();
// Populate cache list.
InitCacheList();
}
GpuAgent::~GpuAgent() {
for (auto& blit : blits_) {
if (!blit.empty()) {
hsa_status_t status = blit->Destroy(*this);
assert(status == HSA_STATUS_SUCCESS);
}
}
if (ape1_base_ != 0) {
_aligned_free(reinterpret_cast<void*>(ape1_base_));
}
scratch_cache_.trim(true);
if (scratch_pool_.base() != NULL) {
hsaKmtFreeMemory(scratch_pool_.base(), scratch_pool_.size());
}
system_deallocator()(doorbell_queue_map_);
if (trap_code_buf_ != NULL) {
ReleaseShader(trap_code_buf_, trap_code_buf_size_);
}
std::for_each(regions_.begin(), regions_.end(), DeleteObject());
regions_.clear();
}
void GpuAgent::AssembleShader(const char* func_name, AssembleTarget assemble_target,
void*& code_buf, size_t& code_buf_size) const {
// Select precompiled shader implementation from name/target.
struct ASICShader {
const void* code;
size_t size;
int num_sgprs;
int num_vgprs;
};
struct CompiledShader {
ASICShader compute_7;
ASICShader compute_8;
ASICShader compute_9;
ASICShader compute_90a;
ASICShader compute_1010;
ASICShader compute_10;
};
std::map<std::string, CompiledShader> compiled_shaders = {
{"TrapHandler",
{
{NULL, 0, 0, 0},
{kCodeTrapHandler8, sizeof(kCodeTrapHandler8), 2, 4},
{kCodeTrapHandler9, sizeof(kCodeTrapHandler9), 2, 4},
{kCodeTrapHandler90a, sizeof(kCodeTrapHandler90a), 2, 4},
{kCodeTrapHandler1010, sizeof(kCodeTrapHandler1010), 2, 4},
{kCodeTrapHandler10, sizeof(kCodeTrapHandler10), 2, 4},
}},
{"TrapHandlerKfdExceptions",
{
{NULL, 0, 0, 0},
{kCodeTrapHandler8, sizeof(kCodeTrapHandler8), 2, 4},
{kCodeTrapHandlerV2_9, sizeof(kCodeTrapHandlerV2_9), 2, 4},
{kCodeTrapHandlerV2_9, sizeof(kCodeTrapHandlerV2_9), 2, 4},
{kCodeTrapHandlerV2_1010, sizeof(kCodeTrapHandlerV2_1010), 2, 4},
{kCodeTrapHandlerV2_10, sizeof(kCodeTrapHandlerV2_10), 2, 4},
}},
{"CopyAligned",
{
{kCodeCopyAligned7, sizeof(kCodeCopyAligned7), 32, 12},
{kCodeCopyAligned8, sizeof(kCodeCopyAligned8), 32, 12},
{kCodeCopyAligned8, sizeof(kCodeCopyAligned8), 32, 12},
{kCodeCopyAligned8, sizeof(kCodeCopyAligned8), 32, 12},
{kCodeCopyAligned10, sizeof(kCodeCopyAligned10), 32, 12},
{kCodeCopyAligned10, sizeof(kCodeCopyAligned10), 32, 12},
}},
{"CopyMisaligned",
{
{kCodeCopyMisaligned7, sizeof(kCodeCopyMisaligned7), 23, 10},
{kCodeCopyMisaligned8, sizeof(kCodeCopyMisaligned8), 23, 10},
{kCodeCopyMisaligned8, sizeof(kCodeCopyMisaligned8), 23, 10},
{kCodeCopyMisaligned8, sizeof(kCodeCopyMisaligned8), 23, 10},
{kCodeCopyMisaligned10, sizeof(kCodeCopyMisaligned10), 23, 10},
{kCodeCopyMisaligned10, sizeof(kCodeCopyMisaligned10), 23, 10},
}},
{"Fill",
{
{kCodeFill7, sizeof(kCodeFill7), 19, 8},
{kCodeFill8, sizeof(kCodeFill8), 19, 8},
{kCodeFill8, sizeof(kCodeFill8), 19, 8},
{kCodeFill8, sizeof(kCodeFill8), 19, 8},
{kCodeFill10, sizeof(kCodeFill10), 19, 8},
{kCodeFill10, sizeof(kCodeFill10), 19, 8},
}}};
auto compiled_shader_it = compiled_shaders.find(func_name);
assert(compiled_shader_it != compiled_shaders.end() &&
"Precompiled shader unavailable");
ASICShader* asic_shader = NULL;
switch (isa_->GetMajorVersion()) {
case 7:
asic_shader = &compiled_shader_it->second.compute_7;
break;
case 8:
asic_shader = &compiled_shader_it->second.compute_8;
break;
case 9:
if((isa_->GetMinorVersion() == 0) && (isa_->GetStepping() == 10))
asic_shader = &compiled_shader_it->second.compute_90a;
else
asic_shader = &compiled_shader_it->second.compute_9;
break;
case 10:
if(isa_->GetMinorVersion() == 1)
asic_shader = &compiled_shader_it->second.compute_1010;
else
asic_shader = &compiled_shader_it->second.compute_10;
break;
default:
assert(false && "Precompiled shader unavailable for target");
}
// Allocate a GPU-visible buffer for the shader.
size_t header_size =
(assemble_target == AssembleTarget::AQL ? sizeof(amd_kernel_code_t) : 0);
code_buf_size = AlignUp(header_size + asic_shader->size, 0x1000);
code_buf = system_allocator()(code_buf_size, 0x1000, core::MemoryRegion::AllocateExecutable);
assert(code_buf != NULL && "Code buffer allocation failed");
memset(code_buf, 0, code_buf_size);
// Populate optional code object header.
if (assemble_target == AssembleTarget::AQL) {
amd_kernel_code_t* header = reinterpret_cast<amd_kernel_code_t*>(code_buf);
int gran_sgprs = std::max(0, (int(asic_shader->num_sgprs) - 1) / 8);
int gran_vgprs = std::max(0, (int(asic_shader->num_vgprs) - 1) / 4);
header->kernel_code_entry_byte_offset = sizeof(amd_kernel_code_t);
AMD_HSA_BITS_SET(header->kernel_code_properties,
AMD_KERNEL_CODE_PROPERTIES_ENABLE_SGPR_KERNARG_SEGMENT_PTR,
1);
AMD_HSA_BITS_SET(header->compute_pgm_rsrc1,
AMD_COMPUTE_PGM_RSRC_ONE_GRANULATED_WAVEFRONT_SGPR_COUNT,
gran_sgprs);
AMD_HSA_BITS_SET(header->compute_pgm_rsrc1,
AMD_COMPUTE_PGM_RSRC_ONE_GRANULATED_WORKITEM_VGPR_COUNT,
gran_vgprs);
AMD_HSA_BITS_SET(header->compute_pgm_rsrc1,
AMD_COMPUTE_PGM_RSRC_ONE_FLOAT_DENORM_MODE_16_64, 3);
AMD_HSA_BITS_SET(header->compute_pgm_rsrc1,
AMD_COMPUTE_PGM_RSRC_ONE_ENABLE_IEEE_MODE, 1);
AMD_HSA_BITS_SET(header->compute_pgm_rsrc2,
AMD_COMPUTE_PGM_RSRC_TWO_USER_SGPR_COUNT, 2);
AMD_HSA_BITS_SET(header->compute_pgm_rsrc2,
AMD_COMPUTE_PGM_RSRC_TWO_ENABLE_SGPR_WORKGROUP_ID_X, 1);
if ((isa_->GetMajorVersion() == 9) && (isa_->GetMinorVersion() == 0) &&
(isa_->GetStepping() == 10)) {
// Program COMPUTE_PGM_RSRC3.ACCUM_OFFSET for 0 ACC VGPRs on gfx90a.
// FIXME: Assemble code objects from source at build time
int gran_accvgprs = ((gran_vgprs + 1) * 8) / 4 - 1;
header->max_scratch_backing_memory_byte_size = uint64_t(gran_accvgprs) << 32;
}
}
// Copy shader code into the GPU-visible buffer.
memcpy((void*)(uintptr_t(code_buf) + header_size), asic_shader->code,
asic_shader->size);
}
void GpuAgent::ReleaseShader(void* code_buf, size_t code_buf_size) const {
system_deallocator()(code_buf);
}
void GpuAgent::InitRegionList() {
const bool is_apu_node = (properties_.NumCPUCores > 0);
std::vector<HsaMemoryProperties> mem_props(properties_.NumMemoryBanks);
if (HSAKMT_STATUS_SUCCESS ==
hsaKmtGetNodeMemoryProperties(node_id(), properties_.NumMemoryBanks,
&mem_props[0])) {
for (uint32_t mem_idx = 0; mem_idx < properties_.NumMemoryBanks;
++mem_idx) {
// Ignore the one(s) with unknown size.
if (mem_props[mem_idx].SizeInBytes == 0) {
continue;
}
switch (mem_props[mem_idx].HeapType) {
case HSA_HEAPTYPE_FRAME_BUFFER_PRIVATE:
case HSA_HEAPTYPE_FRAME_BUFFER_PUBLIC:
if (!is_apu_node) {
mem_props[mem_idx].VirtualBaseAddress = 0;
}
memory_bus_width_ = mem_props[mem_idx].Width;
memory_max_frequency_ = mem_props[mem_idx].MemoryClockMax;
case HSA_HEAPTYPE_GPU_LDS:
case HSA_HEAPTYPE_GPU_SCRATCH: {
MemoryRegion* region = new MemoryRegion(false, false, false, this, mem_props[mem_idx]);
regions_.push_back(region);
if (region->IsLocalMemory()) {
// Expose VRAM as uncached/fine grain over PCIe (if enabled) or XGMI.
if ((properties_.HiveID != 0) ||
(core::Runtime::runtime_singleton_->flag().fine_grain_pcie())) {
regions_.push_back(new MemoryRegion(true, false, false, this, mem_props[mem_idx]));
}
}
break;
}
case HSA_HEAPTYPE_SYSTEM:
if (is_apu_node) {
memory_bus_width_ = mem_props[mem_idx].Width;
memory_max_frequency_ = mem_props[mem_idx].MemoryClockMax;
}
break;
case HSA_HEAPTYPE_MMIO_REMAP:
// Remap offsets defined in kfd_ioctl.h
HDP_flush_.HDP_MEM_FLUSH_CNTL = (uint32_t*)mem_props[mem_idx].VirtualBaseAddress;
HDP_flush_.HDP_REG_FLUSH_CNTL = HDP_flush_.HDP_MEM_FLUSH_CNTL + 1;
break;
default:
continue;
}
}
}
}
void GpuAgent::InitScratchPool() {
HsaMemFlags flags;
flags.Value = 0;
flags.ui32.Scratch = 1;
flags.ui32.HostAccess = 1;
scratch_per_thread_ =
core::Runtime::runtime_singleton_->flag().scratch_mem_size();
if (scratch_per_thread_ == 0)
scratch_per_thread_ = DEFAULT_SCRATCH_BYTES_PER_THREAD;
// Scratch length is: waves/CU * threads/wave * queues * #CUs *
// scratch/thread
const uint32_t num_cu =
properties_.NumFComputeCores / properties_.NumSIMDPerCU;
queue_scratch_len_ = AlignUp(32 * 64 * num_cu * scratch_per_thread_, 65536);
size_t max_scratch_len = queue_scratch_len_ * max_queues_;
#if defined(HSA_LARGE_MODEL) && defined(__linux__)
// For 64-bit linux use max queues unless otherwise specified
if ((max_scratch_len == 0) || (max_scratch_len > 4294967296)) {
max_scratch_len = 4294967296; // 4GB apeture max
}
#endif
void* scratch_base;
HSAKMT_STATUS err =
hsaKmtAllocMemory(node_id(), max_scratch_len, flags, &scratch_base);
assert(err == HSAKMT_STATUS_SUCCESS && "hsaKmtAllocMemory(Scratch) failed");
assert(IsMultipleOf(scratch_base, 0x1000) &&
"Scratch base is not page aligned!");
scratch_pool_. ~SmallHeap();
if (HSAKMT_STATUS_SUCCESS == err) {
new (&scratch_pool_) SmallHeap(scratch_base, max_scratch_len);
} else {
new (&scratch_pool_) SmallHeap();
}
}
void GpuAgent::InitCacheList() {
// Get GPU cache information.
// Similar to getting CPU cache but here we use FComputeIdLo.
cache_props_.resize(properties_.NumCaches);
if (HSAKMT_STATUS_SUCCESS !=
hsaKmtGetNodeCacheProperties(node_id(), properties_.FComputeIdLo,
properties_.NumCaches, &cache_props_[0])) {
cache_props_.clear();
} else {
// Only store GPU D-cache.
for (size_t cache_id = 0; cache_id < cache_props_.size(); ++cache_id) {
const HsaCacheType type = cache_props_[cache_id].CacheType;
if (type.ui32.HSACU != 1 || type.ui32.Instruction == 1) {
cache_props_.erase(cache_props_.begin() + cache_id);
--cache_id;
}
}
}
// Update cache objects
caches_.clear();
caches_.resize(cache_props_.size());
char name[64];
GetInfo(HSA_AGENT_INFO_NAME, name);
std::string deviceName = name;
for (size_t i = 0; i < caches_.size(); i++)
caches_[i].reset(new core::Cache(deviceName + " L" + std::to_string(cache_props_[i].CacheLevel),
cache_props_[i].CacheLevel, cache_props_[i].CacheSize));
}
hsa_status_t GpuAgent::IterateRegion(
hsa_status_t (*callback)(hsa_region_t region, void* data),
void* data) const {
return VisitRegion(true, callback, data);
}
hsa_status_t GpuAgent::IterateCache(hsa_status_t (*callback)(hsa_cache_t cache, void* data),
void* data) const {
AMD::callback_t<decltype(callback)> call(callback);
for (size_t i = 0; i < caches_.size(); i++) {
hsa_status_t stat = call(core::Cache::Convert(caches_[i].get()), data);
if (stat != HSA_STATUS_SUCCESS) return stat;
}
return HSA_STATUS_SUCCESS;
}
hsa_status_t GpuAgent::VisitRegion(bool include_peer,
hsa_status_t (*callback)(hsa_region_t region,
void* data),
void* data) const {
if (include_peer) {
// Only expose system, local, and LDS memory of the blit agent.
if (this->node_id() == core::Runtime::runtime_singleton_->region_gpu()->node_id()) {
hsa_status_t stat = VisitRegion(regions_, callback, data);
if (stat != HSA_STATUS_SUCCESS) {
return stat;
}
}
// Also expose system regions accessible by this agent.
hsa_status_t stat =
VisitRegion(core::Runtime::runtime_singleton_->system_regions_fine(),
callback, data);
if (stat != HSA_STATUS_SUCCESS) {
return stat;
}
return VisitRegion(
core::Runtime::runtime_singleton_->system_regions_coarse(), callback,
data);
}
// Only expose system, local, and LDS memory of this agent.
return VisitRegion(regions_, callback, data);
}
hsa_status_t GpuAgent::VisitRegion(
const std::vector<const core::MemoryRegion*>& regions,
hsa_status_t (*callback)(hsa_region_t region, void* data),
void* data) const {
AMD::callback_t<decltype(callback)> call(callback);
for (const core::MemoryRegion* region : regions) {
const AMD::MemoryRegion* amd_region =
reinterpret_cast<const AMD::MemoryRegion*>(region);
// Only expose system, local, and LDS memory.
if (amd_region->IsSystem() || amd_region->IsLocalMemory() ||
amd_region->IsLDS()) {
hsa_region_t region_handle = core::MemoryRegion::Convert(region);
hsa_status_t status = call(region_handle, data);
if (status != HSA_STATUS_SUCCESS) {
return status;
}
}
}
return HSA_STATUS_SUCCESS;
}
core::Queue* GpuAgent::CreateInterceptibleQueue(void (*callback)(hsa_status_t status,
hsa_queue_t* source, void* data),
void* data) {
// Disabled intercept of internal queues pending tools updates.
core::Queue* queue = nullptr;
QueueCreate(minAqlSize_, HSA_QUEUE_TYPE_MULTI, callback, data, 0, 0, &queue);
if (queue != nullptr)
core::Runtime::runtime_singleton_->InternalQueueCreateNotify(core::Queue::Convert(queue),
this->public_handle());
return queue;
}
core::Blit* GpuAgent::CreateBlitSdma(bool use_xgmi) {
AMD::BlitSdmaBase* sdma;
switch (isa_->GetMajorVersion()) {
case 7:
case 8:
sdma = new BlitSdmaV2V3();
break;
case 9:
sdma = new BlitSdmaV4();
break;
case 10:
sdma = new BlitSdmaV5();
break;
default:
assert(false && "Unexpected device major version.");
return nullptr;
}
if (sdma->Initialize(*this, use_xgmi) != HSA_STATUS_SUCCESS) {
sdma->Destroy(*this);
delete sdma;
sdma = nullptr;
}
return sdma;
}
core::Blit* GpuAgent::CreateBlitKernel(core::Queue* queue) {
AMD::BlitKernel* kernl = new AMD::BlitKernel(queue);
if (kernl->Initialize(*this) != HSA_STATUS_SUCCESS) {
kernl->Destroy(*this);
delete kernl;
kernl = NULL;
}
return kernl;
}
void GpuAgent::InitDma() {
// Setup lazy init pointers on queues and blits.
auto queue_lambda = [this]() {
auto ret = CreateInterceptibleQueue();
if (ret == nullptr)
throw AMD::hsa_exception(HSA_STATUS_ERROR_OUT_OF_RESOURCES,
"Internal queue creation failed.");
return ret;
};
// Dedicated compute queue for host-to-device blits.
queues_[QueueBlitOnly].reset(queue_lambda);
// Share utility queue with device-to-host blits.
queues_[QueueUtility].reset(queue_lambda);
// Decide which engine to use for blits.
auto blit_lambda = [this](bool use_xgmi, lazy_ptr<core::Queue>& queue, bool isHostToDev) {
Flag::SDMA_OVERRIDE sdma_override = core::Runtime::runtime_singleton_->flag().enable_sdma();
// User SDMA queues are unstable on gfx8 and unsupported on gfx1013.
bool use_sdma =
((isa_->GetMajorVersion() != 8) && (isa_->GetVersion() != std::make_tuple(10, 1, 3)));
if (sdma_override != Flag::SDMA_DEFAULT) use_sdma = (sdma_override == Flag::SDMA_ENABLE);
if (use_sdma && (HSA_PROFILE_BASE == profile_)) {
// On gfx90a ensure that HostToDevice queue is created first and so is placed on SDMA0.
if ((!use_xgmi) && (!isHostToDev) && (isa_->GetMajorVersion() == 9) &&
(isa_->GetMinorVersion() == 0) && (isa_->GetStepping() == 10)) {
*blits_[BlitHostToDev];
}
auto ret = CreateBlitSdma(use_xgmi);
if (ret != nullptr) return ret;
}
auto ret = CreateBlitKernel((*queue).get());
if (ret == nullptr)
throw AMD::hsa_exception(HSA_STATUS_ERROR_OUT_OF_RESOURCES, "Blit creation failed.");
return ret;
};
// Determine and instantiate the number of blit objects to
// engage. The total number is sum of three plus number of
// sdma-xgmi engines
uint32_t blit_cnt_ = DefaultBlitCount + properties_.NumSdmaXgmiEngines;
blits_.resize(blit_cnt_);
// Initialize blit objects used for D2D, H2D, D2H, and
// P2P copy operations.
// -- Blit at index BlitDevToDev(0) deals with copies within
// local framebuffer and always engages a Blit Kernel
// -- Blit at index BlitHostToDev(1) deals with copies from
// Host to Device (H2D) and could engage either a Blit
// Kernel or sDMA
// -- Blit at index BlitDevToHost(2) deals with copies from
// Device to Host (D2H) and Peer to Peer (P2P) over PCIe.
// It could engage either a Blit Kernel or sDMA
// -- Blit at index DefaultBlitCount(3) and beyond deal
// exclusively P2P over xGMI links
blits_[BlitDevToDev].reset([this]() {
auto ret = CreateBlitKernel((*queues_[QueueUtility]).get());
if (ret == nullptr)
throw AMD::hsa_exception(HSA_STATUS_ERROR_OUT_OF_RESOURCES, "Blit creation failed.");
return ret;
});
blits_[BlitHostToDev].reset(
[blit_lambda, this]() { return blit_lambda(false, queues_[QueueBlitOnly], true); });
blits_[BlitDevToHost].reset(
[blit_lambda, this]() { return blit_lambda(false, queues_[QueueUtility], false); });
// XGMI engines.
for (uint32_t idx = DefaultBlitCount; idx < blit_cnt_; idx++) {
blits_[idx].reset(
[blit_lambda, this]() { return blit_lambda(true, queues_[QueueUtility], false); });
}
// GWS queues.
InitGWS();
}
void GpuAgent::InitGWS() {
gws_queue_.queue_.reset([this]() {
if (properties_.NumGws == 0) return (core::Queue*)nullptr;
std::unique_ptr<core::Queue> queue(CreateInterceptibleQueue());
if (queue == nullptr)
throw AMD::hsa_exception(HSA_STATUS_ERROR_OUT_OF_RESOURCES,
"Internal queue creation failed.");
auto err = static_cast<AqlQueue*>(queue.get())->EnableGWS(1);
if (err != HSA_STATUS_SUCCESS) throw AMD::hsa_exception(err, "GWS allocation failed.");
gws_queue_.ref_ct_ = 0;
return queue.release();
});
}
void GpuAgent::GWSRelease() {
ScopedAcquire<KernelMutex> lock(&gws_queue_.lock_);
gws_queue_.ref_ct_--;
if (gws_queue_.ref_ct_ != 0) return;
InitGWS();
}
void GpuAgent::PreloadBlits() {
for (auto& blit : blits_) {
blit.touch();
}
}
hsa_status_t GpuAgent::PostToolsInit() {
// Defer memory allocation until agents have been discovered.
InitNumaAllocator();
InitScratchPool();
BindTrapHandler();
InitDma();
return HSA_STATUS_SUCCESS;
}
hsa_status_t GpuAgent::DmaCopy(void* dst, const void* src, size_t size) {
return blits_[BlitDevToDev]->SubmitLinearCopyCommand(dst, src, size);
}
hsa_status_t GpuAgent::DmaCopy(void* dst, core::Agent& dst_agent,
const void* src, core::Agent& src_agent,
size_t size,
std::vector<core::Signal*>& dep_signals,
core::Signal& out_signal) {
// Bind the Blit object that will drive this copy operation
lazy_ptr<core::Blit>& blit = GetBlitObject(dst_agent, src_agent, size);
if (profiling_enabled()) {
// Track the agent so we could translate the resulting timestamp to system
// domain correctly.
out_signal.async_copy_agent(core::Agent::Convert(this->public_handle()));
}
hsa_status_t stat = blit->SubmitLinearCopyCommand(dst, src, size, dep_signals, out_signal);
return stat;
}
hsa_status_t GpuAgent::DmaCopyRect(const hsa_pitched_ptr_t* dst, const hsa_dim3_t* dst_offset,
const hsa_pitched_ptr_t* src, const hsa_dim3_t* src_offset,
const hsa_dim3_t* range, hsa_amd_copy_direction_t dir,
std::vector<core::Signal*>& dep_signals,
core::Signal& out_signal) {
if (isa_->GetMajorVersion() < 9) return HSA_STATUS_ERROR_INVALID_AGENT;
lazy_ptr<core::Blit>& blit =
(dir == hsaHostToDevice) ? blits_[BlitHostToDev] : blits_[BlitDevToHost];
if (!blit->isSDMA()) return HSA_STATUS_ERROR_OUT_OF_RESOURCES;
if (profiling_enabled()) {
// Track the agent so we could translate the resulting timestamp to system
// domain correctly.
out_signal.async_copy_agent(core::Agent::Convert(this->public_handle()));
}
BlitSdmaBase* sdmaBlit = static_cast<BlitSdmaBase*>((*blit).get());
hsa_status_t stat = sdmaBlit->SubmitCopyRectCommand(dst, dst_offset, src, src_offset, range,
dep_signals, out_signal);
return stat;
}
hsa_status_t GpuAgent::DmaFill(void* ptr, uint32_t value, size_t count) {
return blits_[BlitDevToDev]->SubmitLinearFillCommand(ptr, value, count);
}
hsa_status_t GpuAgent::EnableDmaProfiling(bool enable) {
for (auto& blit : blits_) {
if (!blit.empty()) {
const hsa_status_t stat = blit->EnableProfiling(enable);
if (stat != HSA_STATUS_SUCCESS) {
return stat;
}
}
}
return HSA_STATUS_SUCCESS;
}
hsa_status_t GpuAgent::GetInfo(hsa_agent_info_t attribute, void* value) const {
// agent, and vendor name size limit
const size_t attribute_u = static_cast<size_t>(attribute);
// agent, and vendor name length limit excluding terminating nul character.
constexpr size_t hsa_name_size = 63;
switch (attribute_u) {
case HSA_AGENT_INFO_NAME: {
std::string name = isa_->GetProcessorName();
assert(name.size() <= hsa_name_size);
std::memset(value, 0, hsa_name_size);
char* temp = reinterpret_cast<char*>(value);
std::strcpy(temp, name.c_str());
break;
}
case HSA_AGENT_INFO_VENDOR_NAME:
std::memset(value, 0, hsa_name_size);
std::memcpy(value, "AMD", sizeof("AMD"));
break;
case HSA_AGENT_INFO_FEATURE:
*((hsa_agent_feature_t*)value) = HSA_AGENT_FEATURE_KERNEL_DISPATCH;
break;
case HSA_AGENT_INFO_MACHINE_MODEL:
#if defined(HSA_LARGE_MODEL)
*((hsa_machine_model_t*)value) = HSA_MACHINE_MODEL_LARGE;
#else
*((hsa_machine_model_t*)value) = HSA_MACHINE_MODEL_SMALL;
#endif
break;
case HSA_AGENT_INFO_BASE_PROFILE_DEFAULT_FLOAT_ROUNDING_MODES:
case HSA_AGENT_INFO_DEFAULT_FLOAT_ROUNDING_MODE:
*((hsa_default_float_rounding_mode_t*)value) =
HSA_DEFAULT_FLOAT_ROUNDING_MODE_NEAR;
break;
case HSA_AGENT_INFO_FAST_F16_OPERATION:
if (isa_->GetMajorVersion() >= 8) {
*((bool*)value) = true;
} else {
*((bool*)value) = false;
}
break;
case HSA_AGENT_INFO_PROFILE:
*((hsa_profile_t*)value) = profile_;
break;
case HSA_AGENT_INFO_WAVEFRONT_SIZE:
*((uint32_t*)value) = properties_.WaveFrontSize;
break;
case HSA_AGENT_INFO_WORKGROUP_MAX_DIM: {
// TODO: must be per-device
const uint16_t group_size[3] = {1024, 1024, 1024};
std::memcpy(value, group_size, sizeof(group_size));
} break;
case HSA_AGENT_INFO_WORKGROUP_MAX_SIZE:
// TODO: must be per-device
*((uint32_t*)value) = 1024;
break;
case HSA_AGENT_INFO_GRID_MAX_DIM: {
const hsa_dim3_t grid_size = {UINT32_MAX, UINT32_MAX, UINT32_MAX};
std::memcpy(value, &grid_size, sizeof(hsa_dim3_t));
} break;
case HSA_AGENT_INFO_GRID_MAX_SIZE:
*((uint32_t*)value) = UINT32_MAX;
break;
case HSA_AGENT_INFO_FBARRIER_MAX_SIZE:
// TODO: to confirm
*((uint32_t*)value) = 32;
break;
case HSA_AGENT_INFO_QUEUES_MAX:
*((uint32_t*)value) = max_queues_;
break;
case HSA_AGENT_INFO_QUEUE_MIN_SIZE:
*((uint32_t*)value) = minAqlSize_;
break;
case HSA_AGENT_INFO_QUEUE_MAX_SIZE:
*((uint32_t*)value) = maxAqlSize_;
break;
case HSA_AGENT_INFO_QUEUE_TYPE:
*((hsa_queue_type32_t*)value) = HSA_QUEUE_TYPE_MULTI;
break;
case HSA_AGENT_INFO_NODE:
// TODO: associate with OS NUMA support (numactl / GetNumaProcessorNode).
*((uint32_t*)value) = node_id();
break;
case HSA_AGENT_INFO_DEVICE:
*((hsa_device_type_t*)value) = HSA_DEVICE_TYPE_GPU;
break;
case HSA_AGENT_INFO_CACHE_SIZE: {
std::memset(value, 0, sizeof(uint32_t) * 4);
assert(cache_props_.size() > 0 && "GPU cache info missing.");
const size_t num_cache = cache_props_.size();
for (size_t i = 0; i < num_cache; ++i) {
const uint32_t line_level = cache_props_[i].CacheLevel;
if (reinterpret_cast<uint32_t*>(value)[line_level - 1] == 0)
reinterpret_cast<uint32_t*>(value)[line_level - 1] = cache_props_[i].CacheSize * 1024;
}
} break;
case HSA_AGENT_INFO_ISA:
*((hsa_isa_t*)value) = core::Isa::Handle(isa_);
break;
case HSA_AGENT_INFO_EXTENSIONS: {
memset(value, 0, sizeof(uint8_t) * 128);
auto setFlag = [&](uint32_t bit) {
assert(bit < 128 * 8 && "Extension value exceeds extension bitmask");
uint index = bit / 8;
uint subBit = bit % 8;
((uint8_t*)value)[index] |= 1 << subBit;
};
if (core::hsa_internal_api_table_.finalizer_api.hsa_ext_program_finalize_fn != NULL) {
setFlag(HSA_EXTENSION_FINALIZER);
}
if (core::hsa_internal_api_table_.image_api.hsa_ext_image_create_fn != NULL) {
setFlag(HSA_EXTENSION_IMAGES);
}
if (os::LibHandle lib = os::LoadLib(kAqlProfileLib)) {
os::CloseLib(lib);
setFlag(HSA_EXTENSION_AMD_AQLPROFILE);
}
setFlag(HSA_EXTENSION_AMD_PROFILER);
break;
}
case HSA_AGENT_INFO_VERSION_MAJOR:
*((uint16_t*)value) = 1;
break;
case HSA_AGENT_INFO_VERSION_MINOR:
*((uint16_t*)value) = 1;
break;
case HSA_EXT_AGENT_INFO_IMAGE_1D_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_1DA_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_1DB_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_2D_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_2DA_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_2DDEPTH_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_2DADEPTH_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_3D_MAX_ELEMENTS:
case HSA_EXT_AGENT_INFO_IMAGE_ARRAY_MAX_LAYERS:
return hsa_amd_image_get_info_max_dim(public_handle(), attribute, value);
case HSA_EXT_AGENT_INFO_MAX_IMAGE_RD_HANDLES:
// TODO: hardcode based on OCL constants.
*((uint32_t*)value) = 128;
break;
case HSA_EXT_AGENT_INFO_MAX_IMAGE_RORW_HANDLES:
// TODO: hardcode based on OCL constants.
*((uint32_t*)value) = 64;
break;
case HSA_EXT_AGENT_INFO_MAX_SAMPLER_HANDLERS:
// TODO: hardcode based on OCL constants.
*((uint32_t*)value) = 16;
case HSA_AMD_AGENT_INFO_CHIP_ID:
*((uint32_t*)value) = properties_.DeviceId;
break;
case HSA_AMD_AGENT_INFO_CACHELINE_SIZE:
for (auto& cache : cache_props_) {
if ((cache.CacheLevel == 2) && (cache.CacheLineSize != 0)) {
*((uint32_t*)value) = cache.CacheLineSize;
break;
}
}
// Fallback for when KFD is returning zero.
*((uint32_t*)value) = 64;
break;
case HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT:
*((uint32_t*)value) =
(properties_.NumFComputeCores / properties_.NumSIMDPerCU);
break;
case HSA_AMD_AGENT_INFO_MAX_CLOCK_FREQUENCY:
*((uint32_t*)value) = properties_.MaxEngineClockMhzFCompute;
break;
case HSA_AMD_AGENT_INFO_DRIVER_NODE_ID:
*((uint32_t*)value) = node_id();
break;
case HSA_AMD_AGENT_INFO_MAX_ADDRESS_WATCH_POINTS:
*((uint32_t*)value) = static_cast<uint32_t>(
1 << properties_.Capability.ui32.WatchPointsTotalBits);
break;
case HSA_AMD_AGENT_INFO_BDFID:
*((uint32_t*)value) = static_cast<uint32_t>(properties_.LocationId);
break;
case HSA_AMD_AGENT_INFO_MEMORY_WIDTH:
*((uint32_t*)value) = memory_bus_width_;
break;
case HSA_AMD_AGENT_INFO_MEMORY_MAX_FREQUENCY:
*((uint32_t*)value) = memory_max_frequency_;
break;
// The code copies HsaNodeProperties.MarketingName a Unicode string
// which is encoded in UTF-16 as a 7-bit ASCII string
case HSA_AMD_AGENT_INFO_PRODUCT_NAME: {
std::memset(value, 0, HSA_PUBLIC_NAME_SIZE);
char* temp = reinterpret_cast<char*>(value);
for (uint32_t idx = 0;
properties_.MarketingName[idx] != 0 && idx < HSA_PUBLIC_NAME_SIZE - 1; idx++) {
temp[idx] = (uint8_t)properties_.MarketingName[idx];
}
break;
}
case HSA_AMD_AGENT_INFO_MAX_WAVES_PER_CU:
*((uint32_t*)value) = static_cast<uint32_t>(
properties_.NumSIMDPerCU * properties_.MaxWavesPerSIMD);
break;
case HSA_AMD_AGENT_INFO_NUM_SIMDS_PER_CU:
*((uint32_t*)value) = properties_.NumSIMDPerCU;
break;
case HSA_AMD_AGENT_INFO_NUM_SHADER_ENGINES:
*((uint32_t*)value) = properties_.NumShaderBanks;
break;
case HSA_AMD_AGENT_INFO_NUM_SHADER_ARRAYS_PER_SE:
*((uint32_t*)value) = properties_.NumArrays;
break;
case HSA_AMD_AGENT_INFO_HDP_FLUSH:
*((hsa_amd_hdp_flush_t*)value) = HDP_flush_;
break;
case HSA_AMD_AGENT_INFO_DOMAIN:
*((uint32_t*)value) = static_cast<uint32_t>(properties_.Domain);
break;
case HSA_AMD_AGENT_INFO_COOPERATIVE_QUEUES:
*((bool*)value) = properties_.NumGws != 0;
break;
case HSA_AMD_AGENT_INFO_UUID: {
uint64_t uuid_value = static_cast<uint64_t>(properties_.UniqueID);
// Either device does not support UUID e.g. a Gfx8 device,
// or runtime is using an older thunk library that does not
// support UUID's
if (uuid_value == 0) {
char uuid_tmp[] = "GPU-XX";