forked from openxla/xla
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathaql_packet_decode_gdb.py
More file actions
1794 lines (1548 loc) · 67.6 KB
/
Copy pathaql_packet_decode_gdb.py
File metadata and controls
1794 lines (1548 loc) · 67.6 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
import gdb
import struct
outfile = open('aql_packet_decode_gdb.txt', 'w')
outfile.write("=== AQL + SDMA Packet Decode via plain gdb ===\n")
outfile.write("This extracts kernel names, signal addresses from AQL packets,\n")
outfile.write("and decodes SDMA (DMA) ring packets.\n")
outfile.write("Queues are discovered by walking the ROCR runtime singleton\n")
outfile.write("(no rocgdb 'info queues' / 'info dispatch' commands required;\n")
outfile.write("librocr debug symbols must be loaded).\n\n")
AQL_PACKET_SIZE = 64
# AQL packet types (lower 8 bits of header)
PACKET_TYPES = {
0: "VENDOR_SPECIFIC",
1: "INVALID",
2: "KERNEL_DISPATCH",
3: "BARRIER_AND",
4: "AGENT_DISPATCH",
5: "BARRIER_OR",
}
AMD_VENDOR_PACKET_BARRIER_VALUE = 2 # hsa_amd_barrier_value_packet_s
AMD_SIGNAL_VALUE_OFFSET = 8
HSA_SIGNAL_CONDITION_NAMES = {
0: "EQ",
1: "NE",
2: "LT",
3: "GTE",
}
# ---------------------------------------------------------------------------
# SDMA packet opcodes we decode
# ---------------------------------------------------------------------------
SDMA_OP_COPY = 1 # 28 bytes
SDMA_OP_FENCE = 5 # 16 bytes
SDMA_OP_TRAP = 6 # 8 bytes
SDMA_OP_POLL_REGMEM = 8 # 24 bytes
SDMA_OP_ATOMIC = 10 # 32 bytes
SDMA_OP_TIMESTAMP = 13 # 12 bytes
SDMA_OP_NAMES = {
SDMA_OP_COPY: "SDMA_OP_COPY",
SDMA_OP_FENCE: "SDMA_OP_FENCE",
SDMA_OP_TRAP: "SDMA_OP_TRAP",
SDMA_OP_POLL_REGMEM: "SDMA_OP_POLL_REGMEM",
SDMA_OP_ATOMIC: "SDMA_OP_ATOMIC",
SDMA_OP_TIMESTAMP: "SDMA_OP_TIMESTAMP",
}
SDMA_TIMESTAMP_SUBOP = {
0: "SET_LOCAL_TIMESTAMP",
1: "GET_LOCAL_TIMESTAMP",
2: "GET_GLOBAL_TIMESTAMP",
}
# POLL_REGMEM func bits[30:28] of header
SDMA_POLL_REGMEM_FUNC = {
0: "ALWAYS",
1: "LT",
2: "LTE",
3: "EQ",
4: "NE",
5: "GTE",
6: "GT",
7: "RSVD",
}
# Offsets of 4-byte words inside amd_signal_s. Used to identify which field
# an SDMA packet targets and recover the encompassing signal.
# (amd_signal_s layout, see hsa_ext_amd.h.)
SIGNAL_FIELD_NAMES = {
0: "kind (lo32)",
4: "kind (hi32)",
8: "value (lo32)",
12: "value (hi32)",
16: "event_mailbox_ptr (lo32)",
20: "event_mailbox_ptr (hi32)",
24: "event_id",
28: "reserved1",
32: "start_ts (lo32)",
36: "start_ts (hi32)",
40: "end_ts (lo32)",
44: "end_ts (hi32)",
48: "queue_ptr (lo32)",
52: "queue_ptr (hi32)",
}
# Aliases for 8-byte-wide field lookups (timestamps, value, etc.) where the
# SDMA packet addresses the whole 64-bit field by its base offset.
SIGNAL_FIELD_NAMES_64 = {
0: "kind",
8: "value",
16: "event_mailbox_ptr",
24: "event_id + reserved1",
32: "start_ts",
40: "end_ts",
48: "queue_ptr",
}
VALID_SIGNAL_KINDS = {0, 1, -1, -2}
# amd_signal_s is declared with __attribute__((aligned(64))) in hsa_ext_amd.h,
# so every signal allocation is 64-byte aligned. We use this to recover the
# signal base from any address that falls inside it.
SIGNAL_ALIGNMENT = 64
def read_memory(addr, size):
"""Read memory from inferior process."""
try:
inferior = gdb.selected_inferior()
return inferior.read_memory(addr, size).tobytes()
except Exception as e:
outfile.write(f" [read_memory] Failed at 0x{addr:x} size={size}: {e}\n")
return None
def read_amd_signal(signal_handle):
"""Read fields from an amd_signal_s structure."""
if signal_handle == 0:
return None
try:
data = read_memory(signal_handle, 56)
if not data or len(data) < 56:
return None
kind = struct.unpack('<q', data[0:8])[0]
value = struct.unpack('<q', data[8:16])[0]
event_mailbox_ptr = struct.unpack('<Q', data[16:24])[0]
event_id = struct.unpack('<I', data[24:28])[0]
start_ts = struct.unpack('<Q', data[32:40])[0]
end_ts = struct.unpack('<Q', data[40:48])[0]
queue_ptr = struct.unpack('<Q', data[48:56])[0]
kind_name = {
0: "INVALID",
1: "USER",
-1: "DOORBELL",
-2: "LEGACY_DOORBELL",
}.get(kind, f"UNKNOWN({kind})")
return {
'kind': kind,
'kind_name': kind_name,
'value': value,
'event_mailbox_ptr': event_mailbox_ptr,
'event_id': event_id,
'start_ts': start_ts,
'end_ts': end_ts,
'queue_ptr': queue_ptr,
}
except Exception as e:
outfile.write(f" [read_amd_signal] Failed for 0x{signal_handle:x}: {e}\n")
return None
def format_signal_info(sig_info, indent=" "):
"""Detailed amd_signal_s dump - now always prints every meaningful field."""
if sig_info is None:
return f"{indent}<failed to read>\n"
lines = []
lines.append(f"{indent} kind: {sig_info['kind_name']} ({sig_info['kind']})")
lines.append(f"{indent} value: {sig_info['value']} (0x{sig_info['value'] & 0xFFFFFFFFFFFFFFFF:016x})")
if sig_info['value'] > 0:
lines.append(f"{indent} status: PENDING (value={sig_info['value']})")
elif sig_info['value'] == 0:
lines.append(f"{indent} status: COMPLETED")
else:
lines.append(f"{indent} status: COMPLETED (negative: {sig_info['value']})")
lines.append(f"{indent} event_mb: 0x{sig_info['event_mailbox_ptr']:x}")
lines.append(f"{indent} event_id: {sig_info['event_id']}")
lines.append(f"{indent} start_ts: {sig_info['start_ts']}"
+ ("" if sig_info['start_ts'] == 0 else f" (0x{sig_info['start_ts']:x})"))
lines.append(f"{indent} end_ts: {sig_info['end_ts']}"
+ ("" if sig_info['end_ts'] == 0 else f" (0x{sig_info['end_ts']:x})"))
if sig_info['start_ts'] != 0 and sig_info['end_ts'] != 0 and sig_info['end_ts'] > sig_info['start_ts']:
dur = sig_info['end_ts'] - sig_info['start_ts']
lines.append(f"{indent} duration: {dur} ns ({dur / 1e6:.3f} ms)")
lines.append(f"{indent} queue_ptr: 0x{sig_info['queue_ptr']:x}")
return '\n'.join(lines) + '\n'
def find_encompassing_signal(addr):
"""Round `addr` down to the 64-byte signal alignment, validate that the
base actually looks like an amd_signal_s, and return the offset within it.
Works regardless of which field inside the signal the SDMA packet was
pointing at - start_ts (+32), end_ts (+40), value (+8), etc. all live in
the same 64-byte cache-line-aligned block.
Returns (offset_in_signal, signal_base, sig_info_dict) or (None, None, None).
"""
base = addr & ~(SIGNAL_ALIGNMENT - 1)
off = addr - base
sig = read_amd_signal(base)
if sig is None:
return None, None, None
if sig['kind'] not in VALID_SIGNAL_KINDS:
return None, None, None
return off, base, sig
def write_encompassing_signal(addr, indent=" "):
"""Look up & pretty-print the amd_signal_s that `addr` lives inside.
Returns True if a signal was identified, False otherwise.
"""
off, sig_base, sig = find_encompassing_signal(addr)
if sig is None:
outfile.write(f"{indent}encompassing signal: "
f"<not found - 0x{addr:x} & ~0x3f does not look like an amd_signal_s>\n")
return False
field64 = SIGNAL_FIELD_NAMES_64.get(off)
field32 = SIGNAL_FIELD_NAMES.get(off, f"+0x{off:x}")
field = field64 if field64 else field32
outfile.write(f"{indent}encompassing signal:\n")
outfile.write(f"{indent} base: 0x{sig_base:x}\n")
outfile.write(f"{indent} field: {field} (signal+{off})\n")
outfile.write(format_signal_info(sig, indent=indent + " "))
return True
def resolve_kernel_entry_point(kernel_object):
"""Return (absolute_entry_addr, symbol_str, kernarg_preload_bias) for a kernel descriptor.
AMD amdhsa kernel_descriptor_t layout (64 bytes total):
+0 uint32 group_segment_fixed_size
+4 uint32 private_segment_fixed_size
+8 uint32 kernarg_size
+12 uint32 reserved0
+16 int64 kernel_code_entry_byte_offset (signed, delta from descriptor start)
+24 uint8[20] reserved1
+44 uint32 compute_pgm_rsrc3
+48 uint32 compute_pgm_rsrc1
+52 uint32 compute_pgm_rsrc2
+56 uint16 kernel_code_properties
+58 uint16 kernarg_preload_spec <-- non-zero => kernarg preload enabled
+60 uint32 reserved2
Base entry = kernel_object + kernel_code_entry_byte_offset.
When kernarg_preload_spec != 0 the compiler inserts a 256-byte preload
trampoline at base entry; the real ISA code follows immediately after, so:
entry_point = base_entry + 256 (with bias applied)
"""
if not kernel_object:
return None, None, False
desc = read_memory(kernel_object, 60)
if not desc or len(desc) < 60:
return None, None, False
entry_offset = struct.unpack('<q', desc[16:24])[0] # signed int64
kernarg_preload_spec = struct.unpack('<H', desc[58:60])[0] # uint16
base_entry = kernel_object + entry_offset
preload_bias = (kernarg_preload_spec != 0)
entry_addr = base_entry + (256 if preload_bias else 0)
entry_sym = f"<unresolved @ 0x{entry_addr:x}>"
try:
result = gdb.execute(f"info symbol {entry_addr}", to_string=True)
entry_sym = result.strip()
except Exception:
pass
return entry_addr, entry_sym, preload_bias
def decode_kernel_dispatch(data, pkt_addr):
if len(data) < 64:
return None
header = struct.unpack('<H', data[0:2])[0]
setup = struct.unpack('<H', data[2:4])[0]
workgroup_x = struct.unpack('<H', data[4:6])[0]
workgroup_y = struct.unpack('<H', data[6:8])[0]
workgroup_z = struct.unpack('<H', data[8:10])[0]
grid_x = struct.unpack('<I', data[12:16])[0]
grid_y = struct.unpack('<I', data[16:20])[0]
grid_z = struct.unpack('<I', data[20:24])[0]
private_segment_size = struct.unpack('<I', data[24:28])[0]
group_segment_size = struct.unpack('<I', data[28:32])[0]
kernel_object = struct.unpack('<Q', data[32:40])[0]
kernarg_address = struct.unpack('<Q', data[40:48])[0]
completion_signal = struct.unpack('<Q', data[56:64])[0]
kernel_name = "??"
if kernel_object != 0:
try:
result = gdb.execute(f"info symbol {kernel_object}", to_string=True)
kernel_name = result.strip()
except Exception:
kernel_name = f"<unresolved @ 0x{kernel_object:x}>"
entry_point, entry_symbol, entry_preload_bias = resolve_kernel_entry_point(kernel_object)
return {
'header': header,
'setup': setup,
'workgroup': (workgroup_x, workgroup_y, workgroup_z),
'grid': (grid_x, grid_y, grid_z),
'private_segment_size': private_segment_size,
'group_segment_size': group_segment_size,
'kernel_object': kernel_object,
'kernel_name': kernel_name,
'entry_point': entry_point,
'entry_symbol': entry_symbol,
'entry_preload_bias': entry_preload_bias,
'kernarg': kernarg_address,
'completion_signal': completion_signal,
}
def decode_barrier_packet(data, pkt_addr, ptype):
if len(data) < 64:
return None
header = struct.unpack('<H', data[0:2])[0]
dep_signals = []
for i in range(5):
offset = 8 + i * 8
sig = struct.unpack('<Q', data[offset:offset + 8])[0]
dep_signals.append(sig)
completion_signal = struct.unpack('<Q', data[56:64])[0]
return {
'header': header,
'type_name': 'BARRIER_AND' if ptype == 3 else 'BARRIER_OR',
'dep_signals': dep_signals,
'completion_signal': completion_signal,
}
def decode_barrier_value_packet(data, pkt_addr):
if len(data) < 64:
return None
header = struct.unpack('<H', data[0:2])[0]
# AmdFormat is a uint16_t at offset [2:4] (hsa_amd_vendor_packet_header_t).
amd_format = struct.unpack('<H', data[2:4])[0]
watch_signal = struct.unpack('<Q', data[8:16])[0]
compare_value = struct.unpack('<q', data[16:24])[0]
mask = struct.unpack('<q', data[24:32])[0]
cond = struct.unpack('<I', data[32:36])[0]
completion_signal = struct.unpack('<Q', data[56:64])[0]
cond_name = HSA_SIGNAL_CONDITION_NAMES.get(cond, f"UNKNOWN({cond})")
return {
'header': header,
'amd_format': amd_format,
'watch_signal': watch_signal,
'compare_value': compare_value,
'mask': mask,
'cond': cond,
'cond_name': cond_name,
'completion_signal': completion_signal,
}
# ---------------------------------------------------------------------------
# SDMA packet decoding (DMA queues)
# ---------------------------------------------------------------------------
def decode_sdma_packet(pkt_addr):
"""Read and decode one SDMA packet starting at pkt_addr.
Returns (info_dict, size_in_bytes). info_dict['op'] == 0 signals end of
stream. Returns (None, 0) on read failure; (info, 0) for unknown opcodes
whose length we can't determine safely.
"""
head = read_memory(pkt_addr, 4)
if not head or len(head) < 4:
return None, 0
header = struct.unpack('<I', head)[0]
op = header & 0xFF
sub_op = (header >> 8) & 0xFF
if op == 0:
return {'op': 0, 'sub_op': sub_op, 'header': header, 'name': 'END'}, 0
if op == SDMA_OP_COPY:
data = read_memory(pkt_addr, 28)
if not data or len(data) < 28:
return None, 0
_hdr, count, parameter, src_addr, dst_addr = struct.unpack('<IIIQQ', data)
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': SDMA_OP_NAMES[op],
'count': count, 'parameter': parameter,
'src_addr': src_addr, 'dst_addr': dst_addr,
}, 28)
if op == SDMA_OP_FENCE:
data = read_memory(pkt_addr, 16)
if not data or len(data) < 16:
return None, 0
_hdr, addr, value = struct.unpack('<IQI', data)
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': SDMA_OP_NAMES[op],
'addr': addr, 'data': value,
}, 16)
if op == SDMA_OP_TRAP:
data = read_memory(pkt_addr, 8)
if not data or len(data) < 8:
return None, 0
_hdr, context = struct.unpack('<II', data)
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': SDMA_OP_NAMES[op],
'context': context,
}, 8)
if op == SDMA_OP_POLL_REGMEM:
# header(4) + addr(8) + value(4) + mask(4) + dw5(4) = 24
data = read_memory(pkt_addr, 24)
if not data or len(data) < 24:
return None, 0
_hdr, addr, value, mask, dw5 = struct.unpack('<IQIII', data)
# Header:
# [7:0] op
# [15:8] sub_op
# [26] hdp_flush
# [30:28] func
# [31] mem_poll (0=register, 1=memory)
func = (header >> 28) & 0x7
mem_poll = (header >> 31) & 0x1
interval = dw5 & 0xFFFF
retry_count = (dw5 >> 16) & 0xFFF
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': SDMA_OP_NAMES[op],
'addr': addr, 'value': value, 'mask': mask,
'func': func, 'func_name': SDMA_POLL_REGMEM_FUNC.get(func, f"UNK({func})"),
'mem_poll': mem_poll, 'interval': interval, 'retry_count': retry_count,
}, 24)
if op == SDMA_OP_ATOMIC:
# header(4) + addr(8) + src_data(8) + cmp_data(8) + loop_interval(4) = 32
data = read_memory(pkt_addr, 32)
if not data or len(data) < 32:
return None, 0
_hdr, addr, src_data, cmp_data, loop_interval = struct.unpack('<IQQQI', data)
atomic_op = (header >> 25) & 0x7F
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': SDMA_OP_NAMES[op],
'atomic_op': atomic_op, 'addr': addr,
'src_data': src_data, 'cmp_data': cmp_data,
'loop_interval': loop_interval,
}, 32)
if op == SDMA_OP_TIMESTAMP:
# header(4) + value_or_addr(8) = 12
# sub_op 0 SET_LOCAL_TIMESTAMP: 64-bit timestamp value
# sub_op 1 GET_LOCAL_TIMESTAMP: 64-bit dest address
# sub_op 2 GET_GLOBAL_TIMESTAMP: 64-bit dest address (used by rocr)
data = read_memory(pkt_addr, 12)
if not data or len(data) < 12:
return None, 0
_hdr, value_or_addr = struct.unpack('<IQ', data)
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': SDMA_OP_NAMES[op],
'sub_op_name': SDMA_TIMESTAMP_SUBOP.get(sub_op, f"UNKNOWN({sub_op})"),
'value_or_addr': value_or_addr,
}, 12)
return ({
'op': op, 'sub_op': sub_op, 'header': header, 'name': f"UNKNOWN({op})",
}, 0)
def _eval_poll(func, masked, ref):
if func == 0: return True
elif func == 1: return masked < ref
elif func == 2: return masked <= ref
elif func == 3: return masked == ref
elif func == 4: return masked != ref
elif func == 5: return masked >= ref
elif func == 6: return masked > ref
return None
def write_sdma_packet(i, pkt_addr, pkt):
op = pkt['op']
outfile.write(
f" [{i}] @ 0x{pkt_addr:x}: {pkt['name']} "
f"(op=0x{op:x}, sub_op=0x{pkt['sub_op']:x}, header=0x{pkt['header']:08x})\n"
)
if op == SDMA_OP_COPY:
outfile.write(f" count: {pkt['count']} (bytes_to_copy = count+1 = {pkt['count'] + 1})\n")
outfile.write(f" parameter: 0x{pkt['parameter']:08x}\n")
outfile.write(f" src_addr: 0x{pkt['src_addr']:x}\n")
outfile.write(f" dst_addr: 0x{pkt['dst_addr']:x}\n")
elif op == SDMA_OP_FENCE:
outfile.write(f" addr: 0x{pkt['addr']:x}\n")
outfile.write(f" data: 0x{pkt['data']:08x} ({pkt['data']})\n")
mem = read_memory(pkt['addr'], 4)
if mem:
cur = struct.unpack('<I', mem)[0]
outfile.write(f" *addr: 0x{cur:08x} "
f"{'<fence written>' if cur == pkt['data'] else '<not yet written>'}\n")
elif op == SDMA_OP_TRAP:
outfile.write(f" context: 0x{pkt['context']:08x}\n")
elif op == SDMA_OP_POLL_REGMEM:
target = "MEM" if pkt['mem_poll'] else "REG"
outfile.write(f" target: {target} ({'memory' if pkt['mem_poll'] else 'register'})\n")
outfile.write(f" addr: 0x{pkt['addr']:x}\n")
outfile.write(f" func: {pkt['func_name']} ({pkt['func']})\n")
outfile.write(f" ref_value: 0x{pkt['value']:08x} ({pkt['value']})\n")
outfile.write(f" mask: 0x{pkt['mask']:08x}\n")
outfile.write(f" interval: {pkt['interval']} (poll cycles)\n")
outfile.write(f" retry: {pkt['retry_count']} "
f"({'infinite' if pkt['retry_count'] == 0 else 'count'})\n")
if pkt['mem_poll']:
mem = read_memory(pkt['addr'], 4)
if mem:
cur = struct.unpack('<I', mem)[0]
masked = cur & pkt['mask']
ref = pkt['value'] & pkt['mask']
outfile.write(f" *addr: 0x{cur:08x} (masked=0x{masked:08x})\n")
satisfied = _eval_poll(pkt['func'], masked, ref)
if satisfied is not None:
outfile.write(f" eval: masked {pkt['func_name']} 0x{ref:08x} -> "
f"{'SATISFIED' if satisfied else 'BLOCKED (queue waiting here)'}\n")
write_encompassing_signal(pkt['addr'])
elif op == SDMA_OP_ATOMIC:
outfile.write(f" atomic_op: {pkt['atomic_op']}\n")
outfile.write(f" addr: 0x{pkt['addr']:x}\n")
outfile.write(f" src_data: 0x{pkt['src_data']:x} ({pkt['src_data']})\n")
outfile.write(f" cmp_data: 0x{pkt['cmp_data']:x} ({pkt['cmp_data']})\n")
outfile.write(f" loop_interval: {pkt['loop_interval']} "
f"(>>1 = {pkt['loop_interval'] >> 1})\n")
# SDMA atomic typically modifies a signal's `value` field (+8).
write_encompassing_signal(pkt['addr'])
elif op == SDMA_OP_TIMESTAMP:
outfile.write(f" sub_op: {pkt['sub_op_name']} ({pkt['sub_op']})\n")
if pkt['sub_op'] == 0:
outfile.write(f" timestamp: 0x{pkt['value_or_addr']:x} ({pkt['value_or_addr']})\n")
else:
outfile.write(f" dst_addr: 0x{pkt['value_or_addr']:x}\n")
ts_mem = read_memory(pkt['value_or_addr'], 8)
if ts_mem:
ts_val = struct.unpack('<Q', ts_mem)[0]
outfile.write(f" *dst: 0x{ts_val:x} ({ts_val}) "
f"{'<written>' if ts_val != 0 else '<not yet written>'}\n")
outfile.write("\n")
def decode_sdma_ring(ring_base, ring_size_bytes, max_packets=2048):
"""Walk an SDMA ring buffer starting at ring_base, stop at op==0 or end."""
end = ring_base + ring_size_bytes
addr = ring_base
i = 0
decoded = 0
while addr + 4 <= end and i < max_packets:
pkt, size = decode_sdma_packet(addr)
if pkt is None:
outfile.write(f" [{i}] @ 0x{addr:x}: FAILED TO READ - stopping\n\n")
return
if pkt['op'] == 0:
outfile.write(f" [{i}] @ 0x{addr:x}: end-of-stream (op=0), "
f"decoded {decoded} packet(s)\n\n")
return
if size == 0:
outfile.write(f" [{i}] @ 0x{addr:x}: {pkt['name']} "
f"(header=0x{pkt['header']:08x}) - cannot continue past unknown op\n")
sample = read_memory(addr, 64)
if sample:
outfile.write(" raw[64]: " +
' '.join(f'{b:02x}' for b in sample) + "\n")
outfile.write("\n")
return
write_sdma_packet(i, addr, pkt)
decoded += 1
addr += size
i += 1
outfile.write(f" (stopped after {i} packet(s); reached "
f"{'max_packets' if i >= max_packets else 'end of buffer'})\n\n")
# ---------------------------------------------------------------------------
# Runtime singleton queue enumeration (plain gdb, no 'info queues')
#
# Walks rocr::core::Runtime::runtime_singleton_->gpu_agents_ to enumerate
# every HSA AQL queue (user-created + 3 internal per agent) and every SDMA
# blit ring (BlitSdma<...>) without going through any rocgdb-specific
# command. Requires librocr debug symbols loaded in gdb.
#
# Returned dicts use the same shape as the previous 'info queues' parser:
# id, device, queue_num, qid, target_id, type, read, write, size, address
# so the existing decode_hsa_queue / decode_dma_queue functions consume them
# unchanged.
# ---------------------------------------------------------------------------
def _vec_iter(vec):
"""Yield each element of a libstdc++ std::vector<T> as a gdb.Value."""
impl = vec['_M_impl']
start = impl['_M_start']
end = impl['_M_finish']
elem_size = start.type.target().sizeof
if elem_size == 0:
return
n = (int(end) - int(start)) // elem_size
for i in range(n):
yield (start + i).dereference()
def _unique_ptr_get(up):
"""Return the raw T* stored inside a std::unique_ptr<T>, as gdb.Value."""
for path in (
('_M_t', '_M_t', '_M_head_impl'), # libstdc++ (most versions)
('_M_t', '_M_head_impl'), # libstdc++ (older)
('__ptr_',), # libc++
('_M_ptr',), # fallback
):
try:
v = up
for p in path:
v = v[p]
return v
except gdb.error:
continue
except Exception:
continue
return None
def _lazy_ptr_get(lp, target_type=None):
"""Return the raw T* held by a rocr::lazy_ptr<T>, as gdb.Value.
Tries the typed std::unique_ptr internal-field path first; if that fails
(older/newer libstdc++ layouts, missing debug info), falls back to
reading the first 8 bytes of the lazy_ptr - safe because `obj` is the
first member and libstdc++'s std::unique_ptr with an empty deleter is
layout-compatible with a raw pointer.
"""
try:
v = _unique_ptr_get(lp['obj'])
if v is not None:
return v
except Exception:
pass
if target_type is None:
return None
try:
addr = int(lp.address)
raw = read_memory(addr, 8)
if not raw:
return None
ptr_val = struct.unpack('<Q', raw)[0]
if ptr_val == 0:
return None
return gdb.Value(ptr_val).cast(target_type.pointer())
except Exception:
return None
def _hsa_queue_dict(core_q, dev_idx, q_idx, queue_id, internal=False):
"""Build the queue dict for a core::Queue / AqlQueue gdb.Value.
Returns None for the runtime's internal 4 KB PM4 queues - they don't
carry AQL packets, so we don't want them in the enumeration at all.
"""
try:
amd_q = core_q['amd_queue_']
hsa_q = amd_q['hsa_queue']
base = int(hsa_q['base_address'])
slots = int(hsa_q['size'])
qid = int(hsa_q['id'])
rptr_field = amd_q['read_dispatch_id']
wptr_field = amd_q['write_dispatch_id']
read_idx = int(rptr_field)
write_idx = int(wptr_field)
rptr_addr = int(rptr_field.address) if rptr_field.address else None
wptr_addr = int(wptr_field.address) if wptr_field.address else None
except Exception as e:
outfile.write(f" [enum] cannot read amd_queue_ fields: {e}\n")
return None
size_bytes = slots * AQL_PACKET_SIZE
if size_bytes == 4096:
return None # internal PM4 queue, not AQL - ignore.
label = f"AMDGPU Queue {dev_idx}:{q_idx} (QID {qid})"
if internal:
label += " [internal]"
return {
'id': queue_id,
'device': dev_idx,
'queue_num': q_idx,
'qid': qid,
'target_id': label,
'type': 'HSA',
'read': read_idx,
'write': write_idx,
'rptr_addr': rptr_addr,
'wptr_addr': wptr_addr,
'size': size_bytes,
'address': base,
}
def _sdma_queue_dict(blit_obj, dev_idx, q_idx, queue_id):
"""Build the queue dict for a BlitSdma<...> gdb.Value pointer.
blit_obj is a gdb.Value pointer (e.g. core::Blit*). dynamic_type is used
to recover the concrete BlitSdma<...> instantiation, which is where the
queue_start_addr_ / queue_resource_ / queue_(r|w)ptr_ fields live.
Returns None if the object isn't an SDMA blit or hasn't been initialised.
"""
try:
real_type = blit_obj.dynamic_type
except Exception:
return None
if real_type is None:
return None
type_name = real_type.name or str(real_type)
if 'BlitSdma' not in type_name:
return None # likely a kernel blit (BlitKernel*), skip
# dynamic_type may return either a pointer type or the bare object type
# depending on gdb version. Normalize to a pointer and dereference.
try:
if real_type.code == gdb.TYPE_CODE_PTR:
concrete = blit_obj.cast(real_type).dereference()
else:
concrete = blit_obj.cast(real_type.pointer()).dereference()
except Exception as e:
outfile.write(f" [enum] cannot cast Blit to {type_name}: {e}\n")
return None
try:
ring_base = int(concrete['queue_start_addr_'])
except Exception:
return None
if ring_base == 0:
return None # lazy_ptr created but BlitSdma not yet Initialize()d
qid = 0
try:
qid = int(concrete['queue_resource_']['QueueId'])
except Exception:
pass
try:
ring_size = int(gdb.parse_and_eval("'rocr::AMD::BlitSdmaBase'::kQueueSize"))
except Exception:
ring_size = 4 * 1024 * 1024 # historical default
read_idx = None
write_idx = None
try:
rptr = concrete['queue_rptr_']
if int(rptr) != 0:
read_idx = int(rptr.dereference())
except Exception:
pass
try:
wptr = concrete['queue_wptr_']
if int(wptr) != 0:
write_idx = int(wptr.dereference())
except Exception:
pass
return {
'id': queue_id,
'device': dev_idx,
'queue_num': q_idx,
'qid': qid,
'target_id': f"AMDGPU Queue {dev_idx}:{q_idx} (QID {qid}) <{type_name}>",
'type': 'DMA',
'read': read_idx,
'write': write_idx,
'size': ring_size,
'address': ring_base,
}
def enumerate_runtime_queues():
"""Walk rocr::core::Runtime::runtime_singleton_ and return a list of
queue dicts compatible with decode_hsa_queue / decode_dma_queue.
Plain gdb only - no rocgdb commands. Needs librocr debug symbols.
"""
queues = []
# Quote the class so gdb treats it as a single symbol; the last "::"
# is otherwise ambiguous with the static-member separator.
try:
rt = gdb.parse_and_eval("'rocr::core::Runtime'::runtime_singleton_")
except Exception as e:
outfile.write(f"[enum] cannot read 'rocr::core::Runtime'::runtime_singleton_: {e}\n")
outfile.write(" (librocr debug symbols not loaded?)\n\n")
return queues
if int(rt) == 0:
outfile.write("[enum] runtime_singleton_ is null - runtime not initialised.\n\n")
return queues
try:
runtime = rt.dereference()
gpu_agents_vec = runtime['gpu_agents_']
except Exception as e:
outfile.write(f"[enum] cannot access gpu_agents_: {e}\n\n")
return queues
try:
gpu_agent_ptr_t = gdb.lookup_type('rocr::AMD::GpuAgent').pointer()
except Exception as e:
outfile.write(f"[enum] cannot find type rocr::AMD::GpuAgent: {e}\n\n")
return queues
try:
aql_queue_ptr_t = gdb.lookup_type('rocr::AMD::AqlQueue').pointer()
except Exception:
aql_queue_ptr_t = None
try:
core_blit_t = gdb.lookup_type('rocr::core::Blit')
except Exception:
core_blit_t = None
try:
core_queue_t = gdb.lookup_type('rocr::core::Queue')
except Exception:
core_queue_t = None
qid_counter = 0
for dev_idx, agent_ptr_v in enumerate(_vec_iter(gpu_agents_vec)):
if int(agent_ptr_v) == 0:
continue
try:
gpu_ptr = agent_ptr_v.cast(gpu_agent_ptr_t)
gpu = gpu_ptr.dereference()
except Exception as e:
outfile.write(f" [enum] device {dev_idx}: cannot cast to GpuAgent: {e}\n")
continue
# ---- (1) user-created AQL queues: GpuAgent::aql_queues_
try:
aql_vec = gpu['aql_queues_']
for q_idx, aq_ptr_v in enumerate(_vec_iter(aql_vec)):
if int(aq_ptr_v) == 0:
continue
try:
if aql_queue_ptr_t is not None:
aq = aq_ptr_v.cast(aql_queue_ptr_t).dereference()
else:
aq = aq_ptr_v.dereference()
qd = _hsa_queue_dict(aq, dev_idx, q_idx, qid_counter)
if qd:
queues.append(qd)
qid_counter += 1
except Exception as e:
outfile.write(f" [warn] device {dev_idx} aql_queues_[{q_idx}]: {e}\n")
except Exception as e:
outfile.write(f" [enum] device {dev_idx}: cannot read aql_queues_: {e}\n")
# ---- (2) internal AQL queues: GpuAgent::queues_[QueueCount]
# (QueueUtility, QueueBlitOnly, QueuePCSampling)
try:
internal = gpu['queues_']
atype = internal.type
try:
rng = atype.range()
nelems = int(rng[1] - rng[0]) + 1
except Exception:
nelems = int(atype.sizeof // atype.target().sizeof)
for sub in range(nelems):
lp = internal[sub]
obj = _lazy_ptr_get(lp, core_queue_t)
if obj is None or int(obj) == 0:
continue
try:
core_q = obj.dereference()
qd = _hsa_queue_dict(core_q, dev_idx, 100 + sub, qid_counter,
internal=True)
if qd:
queues.append(qd)
qid_counter += 1
except Exception as e:
outfile.write(f" [warn] device {dev_idx} queues_[{sub}]: {e}\n")
except Exception as e:
outfile.write(f" [enum] device {dev_idx}: cannot read internal queues_: {e}\n")
# ---- (3) SDMA blit rings: GpuAgent::blits_
#
# _vec_iter() uses Python integer arithmetic to compute the element
# count (end - start) / elem_size, and elem_size may be wrong when
# gdb cannot fully resolve the lazy_ptr<Blit> template instantiation
# (it often returns pointer-size = 8 instead of the true ~80 bytes).
# Instead, use gdb.parse_and_eval with the typed agent pointer so
# gdb's own type-aware arithmetic computes the correct count and
# index, bypassing the elem_size problem entirely.
try:
agent_expr = f"(('rocr::AMD::GpuAgent'*)0x{int(gpu_ptr):x})"
n_blits = int(gdb.parse_and_eval(
f"{agent_expr}->blits_._M_impl._M_finish"
f" - {agent_expr}->blits_._M_impl._M_start"))
null_ptrs = kernel_blits = uninit = added = 0
for b_idx in range(n_blits):
try:
lp = gdb.parse_and_eval(
f"{agent_expr}->blits_._M_impl._M_start[{b_idx}]")
except Exception as e:
outfile.write(f" [warn] device {dev_idx} blits_[{b_idx}]: {e}\n")
null_ptrs += 1
continue
# Extract raw Blit* from lazy_ptr<Blit>::obj (unique_ptr<Blit>).
# Try the typed path first; fall back to reading 8 bytes directly
# from the start of the unique_ptr (which stores the raw pointer
# as its first word in every known libstdc++/libc++ ABI).
obj = None
try:
obj = _unique_ptr_get(lp['obj'])
except Exception:
pass
if obj is None:
try:
up_addr = int(lp['obj'].address)
raw = read_memory(up_addr, 8)
if raw:
ptr_val = struct.unpack('<Q', raw)[0]
if ptr_val:
blit_t = core_blit_t or gdb.lookup_type('rocr::core::Blit')
obj = gdb.Value(ptr_val).cast(blit_t.pointer())
except Exception:
pass
if obj is None or int(obj) == 0:
null_ptrs += 1
continue
try:
dt = obj.dynamic_type
dt_name = (dt.name or str(dt)) if dt else "<unknown>"
except Exception as e:
dt_name = f"<dynamic_type failed: {e}>"
if 'BlitSdma' not in dt_name:
kernel_blits += 1
continue
qd = _sdma_queue_dict(obj, dev_idx, 200 + b_idx, qid_counter)
if qd is None:
uninit += 1
continue
queues.append(qd)
qid_counter += 1
added += 1
pass
except Exception as e:
outfile.write(f" [enum] device {dev_idx}: cannot read blits_: {e}\n")
return queues
# ---------------------------------------------------------------------------
# Per-queue dispatchers
# ---------------------------------------------------------------------------
def _write_signal_block(addr, label, indent=" "):
"""Print 'label: 0xADDR' followed by the full signal struct dump."""
outfile.write(f"{indent}{label}: 0x{addr:x}\n")
if addr != 0:
sig = read_amd_signal(addr)
outfile.write(f"{indent}{' ' * len(label)} signal info:\n")
outfile.write(format_signal_info(sig, indent=indent + ' ' * (len(label) + 2)))
# Per-packet-body printers, shared between live and inferred-consumed decoding.
def _print_kernel_dispatch_body(pkt, barrier_bit):
gx, gy, gz = pkt['grid']
wx, wy, wz = pkt['workgroup']
outfile.write(f" kernel: {pkt['kernel_name']}\n")
outfile.write(f" kernel_obj: 0x{pkt['kernel_object']:x}\n")
if pkt.get('entry_point') is not None:
bias_note = " (+256 kernarg_preload bias)" if pkt.get('entry_preload_bias') else ""
outfile.write(f" entry_point: 0x{pkt['entry_point']:x}{bias_note} [{pkt['entry_symbol']}]\n")
else:
outfile.write(f" entry_point: <unreadable>\n")
outfile.write(f" grid: [{gx}, {gy}, {gz}]\n")
outfile.write(f" workgroup: [{wx}, {wy}, {wz}]\n")
outfile.write(f" kernarg: 0x{pkt['kernarg']:x}\n")