Repository navigation
Expand file tree
/
Copy pathbackend.py
More file actions
3132 lines (2890 loc) · 118 KB
/
Copy pathbackend.py
File metadata and controls
3132 lines (2890 loc) · 118 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
#!/usr/bin/env python3
# SPDX-License-Identifier: BSD-3-Clause
# Copyright(c) 2026 Intel Corporation. All rights reserved.
"""
backend.py — Local (/dev/sof-dsp0 / debugfs) and Remote TCP Network
(sof_remote_server) backends, SOFZ wire decompressor, and TEL2/PMW2 binary
telemetry parsers for sof-top.
"""
import collections
import ctypes
import fcntl
import fnmatch
import math
import mmap
import os
import re
import shlex
import socket
import struct
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Tuple
# -----------------------------------------------------------------------------
# Protocol & IOCTL Constants matching sof_remote_proto.h
# -----------------------------------------------------------------------------
SOF_NET_MAGIC = 0x534F4652
SOF_NET_VERSION = 1
SOF_NET_DEFAULT_PORT = 9998
SOF_NET_OP_FLAG_COMPRESSED = 0x8000
SOF_NET_OP_MASK = 0x7FFF
SOF_NET_COMP_MAGIC = 0x5A464F53 # 'SOFZ'
SOF_NET_OP_PING = 0x0000
SOF_NET_OP_GET_INFO = 0x0001
SOF_NET_OP_PM_CTL = 0x0002
SOF_NET_OP_IPC_TX = 0x0010
SOF_NET_OP_IPC_LARGE_CFG = 0x0011
SOF_NET_OP_WIN_INFO = 0x0020
SOF_NET_OP_WIN_READ = 0x0021
SOF_NET_OP_WIN_WRITE = 0x0022
SOF_NET_OP_WINSTREAM_IO = 0x0023
SOF_NET_OP_TELEM_SNAPSHOT = 0x0028
SOF_NET_OP_LLEXT_LOAD = 0x0030
SOF_NET_OP_SHELL_EXEC = 0x0040
SOF_NET_OP_PROBE_CTL = 0x0050
SOF_NET_OP_PCM_CTL = 0x0060
SOF_NET_OP_CARD_LIST = 0x0070
SOF_NET_OP_PCM_CAPS = 0x0071
SOF_NET_OP_DAPM_GRAPH = 0x0072
SOF_NET_OP_COMPR_CTL = 0x0073
SOF_NET_OP_KCTL_LIST = 0x0074
SOF_NET_OP_KCTL_GET = 0x0075
SOF_NET_OP_KCTL_SET = 0x0076
SOF_AUDIO_API_ALSA = 1
SOF_AUDIO_API_TINYALSA = 2
SOF_AUDIO_API_TINYCOMPRESS = 3
SOF_TELEM_FL_FW_REGS = 1 << 0
SOF_TELEM_FL_TELEM_SLOT = 1 << 1
SOF_TELEM_FL_PERF_WIN3 = 1 << 2
SOF_TELEM_FL_MEM_STATE_TLV = 1 << 3
SOF_TELEM_FL_PWR_STATE_TLV = 1 << 4
SOF_TELEM_FL_EXT_PERF_TLV = 1 << 5
SOF_TELEM_FL_MODULES_INFO_TLV = 1 << 6
SOF_TELEM_FL_SYS_HOST_STATS = 1 << 7
SOF_TELEM_FL_TEL2_SLOT = 1 << 8
SOF_TELEM_FL_PMW2_WIN3 = 1 << 9
SOF_TELEM_FL_HOT_ONLY = 1 << 10
SOF_TELEM_FL_COMPRESS = 1 << 14
SOF_TELEM_FL_WAKE_DSP = 1 << 15
SOF_PM_OP_QUERY = 0
SOF_PM_OP_WAKE_HOLD = 1
SOF_PM_OP_RELEASE_HOLD = 2
SOF_PM_OP_BOOT_DSP = 3
SOF_PM_OP_CORE_GET = 4
SOF_PM_OP_CORE_PUT = 5
SOF_PCM_OP_STATUS = 0
SOF_PCM_OP_START_TONE = 1
SOF_PCM_OP_STOP_TONE = 2
SOF_PCM_OP_PLAY_BUFFER = 3
SOF_PCM_OP_CAPTURE_BUFFER = 4
SOF_PROBE_OP_INIT = 1
SOF_PROBE_OP_DEINIT = 2
SOF_PROBE_OP_INFO_ACTIVE = 3
SOF_PROBE_OP_INFO_AVAILABLE = 4
SOF_PROBE_OP_POINTS_ADD = 5
SOF_PROBE_OP_POINTS_REMOVE = 6
# IPC4 BaseFW Param IDs
IPC4_MODULES_INFO_GET = 9
IPC4_MEMORY_STATE_INFO_GET = 14
IPC4_POWER_STATE_INFO_GET = 15
IPC4_PERF_MEASUREMENTS_STATE = 17
IPC4_GLOBAL_PERF_DATA = 18
IPC4_EXTENDED_GLOBAL_PERF_DATA = 30
# Debug Slot Types
SOF_CDEV_SLOT_UNUSED = 0x00000000
SOF_CDEV_SLOT_CRITICAL_LOG = 0x54524300
SOF_CDEV_SLOT_DEBUG_LOG = 0x474F4C00
SOF_CDEV_SLOT_GDB_STUB = 0x42444700
SOF_CDEV_SLOT_TELEMETRY = 0x4C455400
SOF_CDEV_SLOT_BROKEN = 0x44414544
SOF_CDEV_SLOT_SHELL = 0x73686C6C
SOF_CDEV_SLOT_LLEXT_LOAD = 0x4C454C44
# Extended Telemetry v2 ("TEL2" & "PMW2") Constants
SOF_TEL_EXT_MAGIC = 0x324C4554 # "TEL2"
SOF_TEL_EXT_HDR_OFFSET = 0x0100
SOF_TEL_EXT_DEBUGFS_HDR_OFFSET = 0x00FC
SOF_TEL_OFF_HOT_LINE0 = 0x0140
SOF_TEL_OFF_GW_HOT = 0x0180
SOF_TEL_OFF_MEM_SEC = 0x0240
SOF_TEL_OFF_VREG_SEC = 0x0340
SOF_TEL_OFF_PPL_SEC = 0x0540
SOF_TEL_OFF_DAI_SEC = 0x06C0
SOF_TEL_OFF_THD_SEC = 0x07C0
SOF_TEL_MW3_MAGIC = 0x32574D50 # "PMW2"
SOF_TEL_MW3_MAX_COMP_ITEMS = 88
SOF_TEL_MW3_MAX_IO_ITEMS = 128
SOF_TEL_MW3_COMP_PERF_STRIDE = 48
SOF_TEL_MW3_MOD_HOT_OFFSET = 0x1080
SOF_TEL_MW3_MOD_COLD_OFFSET = 0x1200
SOF_TEL_MW3_IO_PERF_OFFSET = 0x1800
SOF_TEL_MW3_HDR_OFFSET = 0x1FC0
SOF_NET_TELEM_SNAPSHOT_V1_SIZE = 16356
HEAP_TYPE_NAMES = {
0: "NONE",
1: "SYS_HEAP (SRAM)",
2: "SHARED_HEAP (SRAM)",
3: "LL_MOD_HEAP (SRAM)",
4: "L3_IMR (DRAM)",
5: "DRV_BUF (SRAM)",
}
GW_TYPE_NAMES = {
0: "NONE",
1: "SSP/I2S",
2: "DMIC",
3: "ALH/SDW",
4: "HDA",
5: "HOST_DMA",
6: "OTHER",
}
PPL_STATUS_NAMES = {
0: "NOT_EXIST",
1: "INIT",
2: "READY",
3: "SUSPEND",
4: "PREPARE",
5: "PAUSED",
6: "ACTIVE",
7: "PRE_ACTIVE",
}
FW_STATE_NAMES = {
0: "NOT_STARTED",
1: "BOOT_NEEDED",
2: "BOOT_PREPARE",
3: "BOOT_IN_PROGRESS",
4: "BOOT_FAILED",
5: "BOOT_READY",
6: "BOOT_READY_FAILED",
7: "BOOT_COMPLETE",
8: "CRASHED",
}
def slot_type_name(stype: int) -> str:
if stype == 0:
return "UNUSED"
if (stype & 0xFFFFFF00) == SOF_CDEV_SLOT_CRITICAL_LOG:
return f"CRIT_LOG(C{stype & 0xFF})"
if (stype & 0xFFFFFF00) == SOF_CDEV_SLOT_DEBUG_LOG:
return f"DBG_LOG(C{stype & 0xFF})"
if stype == SOF_CDEV_SLOT_TELEMETRY:
return "TELEMETRY"
if stype == SOF_CDEV_SLOT_GDB_STUB:
return "GDB_STUB"
if stype == SOF_CDEV_SLOT_SHELL:
return "SHELL('shll')"
if stype == SOF_CDEV_SLOT_LLEXT_LOAD:
return "LLEXT('LELD')"
if stype == SOF_CDEV_SLOT_BROKEN:
return "DEAD/BROKEN"
return f"0x{stype:08x}"
def sof_net_decompress(src: bytes) -> bytes:
"""Decompress a SOFZ ('SOFZ' magic) compressed network payload."""
if len(src) < 8:
return src
magic, raw_size = struct.unpack_from("<II", src, 0)
if magic != SOF_NET_COMP_MAGIC or raw_size > 16 * 1024 * 1024:
return src
dst = bytearray(raw_size)
in_pos = 8
out_pos = 0
src_len = len(src)
while in_pos < src_len and out_pos < raw_size:
tok = src[in_pos]
in_pos += 1
tag = tok >> 6
if tag == 0:
zlen = tok
if zlen == 0:
if in_pos + 2 > src_len:
return b""
zlen = src[in_pos] | (src[in_pos + 1] << 8)
in_pos += 2
if zlen == 0 or out_pos + zlen > raw_size:
return b""
out_pos += zlen
elif tag == 1:
llen = (tok & 0x3F) + 1
if in_pos + llen > src_len or out_pos + llen > raw_size:
return b""
dst[out_pos : out_pos + llen] = src[in_pos : in_pos + llen]
in_pos += llen
out_pos += llen
elif tag == 2:
rlen = (tok & 0x3F) + 3
if in_pos + 1 > src_len or out_pos + rlen > raw_size:
return b""
bval = src[in_pos]
in_pos += 1
dst[out_pos : out_pos + rlen] = bytes([bval]) * rlen
out_pos += rlen
else:
mlen = (tok & 0x3F) + 4
if in_pos + 2 > src_len:
return b""
dist = src[in_pos] | (src[in_pos + 1] << 8)
in_pos += 2
if dist == 0 or dist > out_pos or out_pos + mlen > raw_size:
return b""
mpos = out_pos - dist
for k in range(mlen):
dst[out_pos + k] = dst[mpos + k]
out_pos += mlen
return bytes(dst) if out_pos == raw_size else b""
# -----------------------------------------------------------------------------
# Structured Telemetry Models
# -----------------------------------------------------------------------------
@dataclass
class CoreTelemetry:
core_id: int
enabled: bool = False
tick_count: int = 0
ticks_per_sec: float = 0.0
last_time_elapsed_cyc: int = 0
max_time_elapsed_cyc: int = 0
last_time_elapsed_us: float = 0.0
max_time_elapsed_us: float = 0.0
last_ccount: int = 0
avg_kcps: int = 0
peak_kcps: int = 0
peak_4k_kcps: int = 0
peak_8k_kcps: int = 0
budget_kcps: int = 0
cpu_load_pct: float = 0.0
peak_load_pct: float = 0.0
ll_overruns: int = 0
dp_deadline_misses: int = 0
active_ll_tasks: int = 0
active_dp_tasks: int = 0
active_ppl_count: int = 0
@dataclass
class ComponentPerfItem:
resource_id: int
module_id: int
instance_id: int
module_name: str
core_id: int = 0
power_mode: str = "LL"
is_removed: bool = False
avg_kcps: int = 0
peak_kcps: int = 0
iterations: int = 0
total_cycles: int = 0
restricted_peak_cycles: int = 0
restricted_iterations: int = 0
restricted_cycles: int = 0
cpc_violations: int = 0
xrun_count: int = 0
heap_usage_bytes: int = 0
heap_hwm_bytes: int = 0
configured_cpc: int = 0
@dataclass
class IoPerfItem:
resource_id: int
power_mode: int
perf_usage: int
@property
def utilization_kcps(self) -> int:
return self.perf_usage
@dataclass
class SramSegmentState:
name: str
total_banks: int = 0
powered_banks: int = 0
gated_banks: int = 0
free_phys_pages: int = 0
total_phys_pages: int = 0
bank_powered: List[bool] = field(default_factory=list)
bank_alloc_mask: List[int] = field(default_factory=list)
def compute_sram_segment_metrics(seg: SramSegmentState, bank_kb: float) -> Tuple[float, float, float]:
"""Return (used_kb, powered_kb, total_kb) distinguishing page allocation from power gates."""
tot_kb = float(seg.total_banks * bank_kb)
pwr_kb = float(seg.powered_banks * bank_kb)
if seg.total_phys_pages > 0 and seg.free_phys_pages <= seg.total_phys_pages:
used_kb = max(0.0, float(seg.total_phys_pages - seg.free_phys_pages) * 4.0)
else:
used_kb = pwr_kb
return used_kb, pwr_kb, tot_kb
@dataclass
class HeapTelemetry:
heap_type: int
name: str
is_dram: bool = False
total_bytes: int = 0
allocated_bytes: int = 0
free_bytes: int = 0
max_allocated_bytes: int = 0
alloc_fail_count: int = 0
@dataclass
class VmhBundleInfo:
blk_sz_shift: int
block_size_bytes: int
total_blocks: int
used_blocks: int
max_blocks_or_oom: int
@dataclass
class FastGetInfo:
active_entries: int = 0
fail_count: int = 0
total_sram_bytes: int = 0
peak_sram_bytes: int = 0
total_get_calls: int = 0
@dataclass
class VregionInfo:
base_va: int
total_pages: int
use_count: int
type_and_flags: int
lifetime_size_bytes: int
lifetime_used_bytes: int
interim_alloc_bytes: int
interim_free_kb: int
lifetime_free_count: int
@dataclass
class VregionSectionInfo:
total_pages: int = 0
free_pages: int = 0
min_free_pages: int = 0
num_elems_in_use: int = 0
alloc_fail_count: int = 0
region_base_va: int = 0
active_vregion_count: int = 0
total_vregions_created: int = 0
velems: List[Tuple[int, int]] = field(default_factory=list)
vregions: List[VregionInfo] = field(default_factory=list)
@dataclass
class PipelineInfo:
pipeline_id: int
core: int
priority: int
status: int
status_name: str
comp_count: int
attributes: int
period_us: int
sched_comp_id: int
last_xrun_bytes: int
xrun_count: int = 0
@dataclass
class GatewayInfo:
slot_idx: int
gw_type: int
type_name: str
index: int
direction: int # 0=playback/tx, 1=capture/rx
dma_chan: int
comp_id: int
state: int
group_id: int
period_bytes: int
dma_buf_size: int
total_kb_or_frames: int = 0
dma_buf_avail_bytes: int = 0
xrun_or_skip_count: int = 0
@dataclass
class ThreadInfo:
thread_id: int
name: str
core: int
prio: int
state: int
cpu_load_pct: float
stack_usage_pct: float
flags: int
stack_size_bytes: int
total_exec_kcycles: int
@dataclass
class DspTaskItem:
"""Unified DSP Task entry for the User Edition Task List and Developer views."""
task_id: str
name: str
task_type: str # "LL Module", "DP Module", "RTOS Thread", "Pipeline", "Core Sched", "DAI Gateway"
core_id: int
status: str # "RUNNING", "ACTIVE", "READY", "IDLE", "PAUSED", "XRUN!", "CPC_VIOL", "GATED"
cpu_pct: float
avg_kcps: int
peak_kcps: int
mem_used_kb: float
mem_limit_kb: float
mem_desc: str
iterations: int
xruns: int
@dataclass
class DebugSlotInfo:
slot_index: int
res_id: int
slot_type: int
type_name: str
vma: int
win_offset: int
bar_offset: int
size: int
@dataclass
class WindowInfo:
win_id: int
bar_offset: int
size: int
mapped: bool
@dataclass
class TelemetrySnapshot:
timestamp: float = 0.0
connected: bool = False
platform: str = "unknown"
fw_filename: str = ""
fw_version: str = "0.0.0.0"
ipc_type: int = 1
fw_state: int = 0
fw_state_name: str = "NOT_STARTED"
dsp_power_state: int = 0
pm_runtime_active: bool = False
num_cores: int = 2
enabled_cores_mask: int = 1
dsp_clock_hz: int = 400_000_000
active_pcm_streams: int = 0
wire_bytes: int = 0
raw_bytes: int = 0
# Window 0 FW Regs
fw_status: int = 0
lec: int = 0
fps: int = 0
lnec: int = 0
ltr: int = 0
# Windows & Debug Slots
windows: List[WindowInfo] = field(default_factory=list)
debug_slots: List[DebugSlotInfo] = field(default_factory=list)
# Cores, Components, Pipelines, Gateways, Threads, Unified Tasks
cores: List[CoreTelemetry] = field(default_factory=list)
components: List[ComponentPerfItem] = field(default_factory=list)
io_perf_items: List[IoPerfItem] = field(default_factory=list)
pipelines: List[PipelineInfo] = field(default_factory=list)
gateways: List[GatewayInfo] = field(default_factory=list)
threads: List[ThreadInfo] = field(default_factory=list)
tasks: List[DspTaskItem] = field(default_factory=list)
total_xrun_events: int = 0
tel2_present: bool = False
pmw2_present: bool = False
tel2_seq: int = 0
tel2_timestamp_us: int = 0
# Memory State (SRAM + DRAM + Heaps + VMH + VRegions)
hpsram: SramSegmentState = field(default_factory=lambda: SramSegmentState("HPSRAM"))
lpsram: SramSegmentState = field(default_factory=lambda: SramSegmentState("LPSRAM"))
heaps: List[HeapTelemetry] = field(default_factory=list)
sram_used_kb: float = 0.0
sram_powered_kb: float = 0.0
sram_total_kb: float = 0.0
dram_used_kb: float = 0.0
dram_hwm_kb: float = 0.0
dram_total_kb: float = 0.0
heap_allocated_bytes: int = 0
heap_free_bytes: int = 0
heap_max_bytes: int = 0
heap_total_bytes: int = 0
vmh_region_size: int = 0
vmh_bundle_count: int = 0
vmh_oom_total: int = 0
vmh_bundles: List[VmhBundleInfo] = field(default_factory=list)
fast_get: FastGetInfo = field(default_factory=FastGetInfo)
vregion_sec: VregionSectionInfo = field(default_factory=VregionSectionInfo)
loaded_modules: Dict[int, str] = field(default_factory=dict)
# -----------------------------------------------------------------------------
# Binary Parsers for Firmware Windows & IPC4 BaseFW TLVs
# -----------------------------------------------------------------------------
WELL_KNOWN_IPC4_MODULES = {
0x0000: "basefw",
0x0001: "mixin",
0x0002: "mixout",
0x0003: "copier",
0x0004: "peakvol",
0x0005: "src",
0x0006: "asrc",
0x0007: "probe",
0x0008: "updown_mix",
0x0009: "smart_amp",
0x000A: "dts",
0x000B: "dolby",
0x000C: "eq_iir",
0x000D: "eq_fir",
0x000E: "drc",
0x000F: "tdfb",
0x0010: "crossover",
0x0011: "multiband_drc",
0x0012: "aria",
0x0013: "igo_nr",
0x0094: "copier",
0x0095: "mixin",
0x0096: "mixout",
0x0097: "gain",
0x0098: "src",
0x0099: "wov_detect",
}
def sof_tel2_slot_bias(buf: bytes) -> int:
if len(buf) >= SOF_TEL_EXT_HDR_OFFSET + 64:
(magic,) = struct.unpack_from("<I", buf, SOF_TEL_EXT_HDR_OFFSET)
if magic == SOF_TEL_EXT_MAGIC:
return 0
if len(buf) >= SOF_TEL_EXT_DEBUGFS_HDR_OFFSET + 64:
(magic,) = struct.unpack_from("<I", buf, SOF_TEL_EXT_DEBUGFS_HDR_OFFSET)
if magic == SOF_TEL_EXT_MAGIC:
return 4
return -1
class TelemetryParser:
def __init__(self):
self.prev_ts: float = 0.0
self.prev_ticks: Dict[int, int] = {}
self.prev_ccount: Dict[int, int] = {}
self.module_name_lookup: Dict[int, str] = dict(WELL_KNOWN_IPC4_MODULES)
self.cached_modules: Dict[int, str] = {}
self.cached_hpsram: Optional[SramSegmentState] = None
self.cached_lpsram: Optional[SramSegmentState] = None
self.cached_core_kcps: Dict[int, int] = {}
self.cached_enabled_cores_mask: int = 0
self.cached_ext_perf: List[ComponentPerfItem] = []
def lookup_module_name(self, mod_id: int) -> str:
return (
self.cached_modules.get(mod_id)
or self.module_name_lookup.get(mod_id, f"mod_0x{mod_id:02x}")
)
def parse_cdev_info_into(self, raw_info: bytes, snap: TelemetrySnapshot):
if len(raw_info) < 140:
return
(
abi_ver,
ipc_type,
fw_state,
dsp_power_state,
pm_active,
num_cores,
enabled_cores_mask,
max_payload,
ver_maj,
ver_min,
ver_mic,
ver_bld,
hw_ip,
plat_bytes,
fw_bytes,
) = struct.unpack_from("<IIIIIIIIHHHHI32s64s", raw_info, 0)
snap.ipc_type = ipc_type
snap.fw_state = fw_state
snap.fw_state_name = FW_STATE_NAMES.get(fw_state, f"STATE_{fw_state}")
snap.dsp_power_state = dsp_power_state
snap.pm_runtime_active = bool(pm_active)
snap.num_cores = max(1, min(8, num_cores))
snap.enabled_cores_mask = enabled_cores_mask
snap.fw_version = f"{ver_maj}.{ver_min}.{ver_mic}.{ver_bld}"
snap.platform = plat_bytes.split(b"\x00", 1)[0].decode("ascii", errors="replace")
snap.fw_filename = fw_bytes.split(b"\x00", 1)[0].decode("ascii", errors="replace")
off = 140
snap.windows = []
for _ in range(4):
if off + 16 <= len(raw_info):
wid, boff, wsz, wfl = struct.unpack_from("<IIII", raw_info, off)
snap.windows.append(WindowInfo(wid, boff, wsz, bool(wfl)))
off += 16
snap.debug_slots = []
for _ in range(16):
if off + 32 <= len(raw_info):
sidx, resid, stype, vma, woff, boff, ssz, _ = struct.unpack_from(
"<IIIIIIII", raw_info, off
)
snap.debug_slots.append(
DebugSlotInfo(
sidx, resid, stype, slot_type_name(stype), vma, woff, boff, ssz
)
)
off += 32
def parse_modules_info_tlv(self, data: bytes):
if len(data) < 4:
return
(mod_count,) = struct.unpack_from("<I", data, 0)
mod_count = min(mod_count, 128)
off = 4
for idx in range(mod_count):
if off + 116 > len(data):
break
mod_id_rt, _ = struct.unpack_from("<HH", data, off)
if data[off : off + 4] == b"$AME":
mod_id_rt = idx
name_raw = data[off + 4 : off + 12]
mname = name_raw.split(b"\x00", 1)[0].decode("ascii", errors="replace").strip()
if mname:
self.cached_modules[mod_id_rt] = mname
self.cached_modules[idx] = mname
self.module_name_lookup[mod_id_rt] = mname
self.module_name_lookup[idx] = mname
off += 116
def parse_memory_state_tlv(self, data: bytes) -> Tuple[bool, bool]:
got_hp = False
got_lp = False
off = 0
while off + 8 <= len(data):
ttype, tlen = struct.unpack_from("<II", data, off)
off += 8
if tlen == 0 or off + tlen > len(data):
break
val = data[off : off + tlen]
off += tlen
if len(val) < 12:
continue
free_pages, ebb_dwords = struct.unpack_from("<II", val, 0)
if ebb_dwords > 8 or 8 + ebb_dwords * 4 + 4 > len(val):
continue
pgctl_masks = struct.unpack_from(f"<{ebb_dwords}I", val, 8) if ebb_dwords > 0 else ()
(bank_count,) = struct.unpack_from("<I", val, 8 + ebb_dwords * 4)
if ebb_dwords > 0:
bank_count = min(bank_count, ebb_dwords * 32, 64)
else:
bank_count = 0
seg = SramSegmentState("HPSRAM" if ttype == 1 else "LPSRAM")
seg.total_banks = bank_count
seg.total_phys_pages = bank_count * (32 if ttype == 1 else 16)
seg.free_phys_pages = free_pages
for b in range(bank_count):
dword_idx = b // 32
bit_idx = b % 32
is_gated = bool((pgctl_masks[dword_idx] >> bit_idx) & 1)
is_powered = not is_gated
seg.bank_powered.append(is_powered)
if is_powered:
seg.powered_banks += 1
else:
seg.gated_banks += 1
alloc_off = 12 + ebb_dwords * 4
for _ in range(bank_count):
if alloc_off + 2 <= len(val):
(amask,) = struct.unpack_from("<H", val, alloc_off)
seg.bank_alloc_mask.append(amask)
alloc_off += 2
if ttype == 1 and seg.total_banks > 0:
self.cached_hpsram = seg
got_hp = True
elif ttype == 0 and seg.total_banks > 0:
self.cached_lpsram = seg
got_lp = True
return got_hp, got_lp
def parse_power_state_tlv(self, data: bytes, snap: TelemetrySnapshot):
off = 0
while off + 8 <= len(data):
ttype, tlen = struct.unpack_from("<II", data, off)
off += 8
if off + tlen > len(data):
break
val = data[off : off + tlen]
off += tlen
if ttype == 0 and tlen >= 4:
(mask,) = struct.unpack_from("<I", val, 0)
snap.enabled_cores_mask = mask
if mask > 0:
self.cached_enabled_cores_mask = mask
elif ttype == 1 and tlen >= 4:
n = tlen // 4
kcps_arr = struct.unpack_from(f"<{n}I", val, 0)
for cid, kv in enumerate(kcps_arr):
self.cached_core_kcps[cid] = 0 if (kv >= 0xFFFFFF00 or kv > 2_000_000) else kv
@staticmethod
def _extract_kcps_records(
perf_win3: bytes, pmw2_win3: bytes
) -> Dict[int, Tuple[int, int]]:
kcps_map: Dict[int, Tuple[int, int]] = {}
if len(pmw2_win3) >= SOF_TEL_MW3_HDR_OFFSET + 4:
(mw3_magic,) = struct.unpack_from("<I", pmw2_win3, SOF_TEL_MW3_HDR_OFFSET)
if mw3_magic == SOF_TEL_MW3_MAGIC:
for i in range(SOF_TEL_MW3_MAX_COMP_ITEMS):
poff = i * SOF_TEL_MW3_COMP_PERF_STRIDE
if poff + 16 > len(pmw2_win3):
break
rid, _flg, pk, av = struct.unpack_from("<IIII", pmw2_win3, poff)
if rid not in (0, 0xFFFFFFFF):
kcps_map[rid] = (pk, av)
for off in range(0, len(perf_win3) - 31, 32):
rid, _flg, pk, av = struct.unpack_from("<IIII", perf_win3, off)
if rid in (0, 0xFFFFFFFF):
break
if rid not in kcps_map:
kcps_map[rid] = (pk, av)
return kcps_map
@staticmethod
def _extract_default_period_us(tel2: bytes) -> int:
bias = sof_tel2_slot_bias(tel2)
if bias >= 0:
ppl_off = SOF_TEL_OFF_PPL_SEC - bias
if ppl_off + 400 <= len(tel2):
act_ppls, _ = struct.unpack_from("<HH", tel2, ppl_off)
for p_i in range(min(16, act_ppls if act_ppls > 0 else 16)):
poff = ppl_off + 80 + p_i * 20
_pid, _pcore, _pprio, _pst, _pcomp, _pattr, pper = struct.unpack_from(
"<HBBBBHI", tel2, poff
)
if pper > 0:
return pper
return 1000
def parse_ext_perf_tlv(
self,
data: bytes,
kcps_by_res: Optional[Dict[int, Tuple[int, int]]] = None,
period_us: int = 1000,
):
if len(data) < 4:
return
(count,) = struct.unpack_from("<I", data, 0)
if count == 0:
self.cached_ext_perf = []
return
if count > 256:
return
items: List[ComponentPerfItem] = []
off = 4
rem = len(data) - 4
if rem >= count * 48:
stride = 48
elif rem >= count * 32:
stride = 32
else:
stride = 16
eff_period_us = period_us if period_us > 0 else 1000
for _ in range(count):
if off + stride > len(data):
break
if stride == 48:
(
res_id,
flags,
peak_cyc,
total_cyc,
iters,
_r_peak,
_r_tot,
_r_it,
) = struct.unpack_from("<IIIQQIQQ", data, off)
rec_kcps = kcps_by_res.get(res_id) if kcps_by_res else None
if rec_kcps is not None and (rec_kcps[0] > 0 or rec_kcps[1] > 0):
peak_kcps, avg_kcps = rec_kcps
else:
peak_kcps = (
int((peak_cyc * 1000) // eff_period_us)
if peak_cyc >= 1000
else int(peak_cyc)
)
avg_kcps = (
int((total_cyc * 1000) // (iters * eff_period_us))
if iters > 0
else peak_kcps
)
cycles = total_cyc
elif stride == 32:
res_id, flags, peak_kcps, avg_kcps, iters, cycles = struct.unpack_from(
"<IIIIQQ", data, off
)
else:
res_id, flags, peak_kcps, avg_kcps = struct.unpack_from(
"<IIII", data, off
)
iters, cycles = 0, 0
off += stride
if res_id == 0 and peak_kcps == 0 and avg_kcps == 0 and cycles == 0:
continue
if res_id == 0xFFFFFFFF:
continue
mod_id = res_id & 0xFFFF
inst_id = (res_id >> 16) & 0xFFFF
mname = (
f"Core {inst_id} Summary"
if mod_id == 0
else self.lookup_module_name(mod_id)
)
pmode = "DP" if (flags & 1) else "LL"
removed = bool((flags >> 31) & 1)
items.append(
ComponentPerfItem(
resource_id=res_id,
module_id=mod_id,
instance_id=inst_id,
module_name=mname,
core_id=inst_id if mod_id == 0 else 0,
power_mode=pmode,
is_removed=removed,
avg_kcps=avg_kcps,
peak_kcps=peak_kcps,
iterations=iters,
total_cycles=cycles,
)
)
self.cached_ext_perf = items
def parse_tel2_and_pmw2(
self,
tel2: bytes,
pmw2: bytes,
snap: TelemetrySnapshot,
got_hp_tlv: bool = False,
got_lp_tlv: bool = False,
):
"""Parse Extended Telemetry v2 (TEL2 4KB slot & PMW2 8KB window)."""
bias = sof_tel2_slot_bias(tel2)
if bias >= 0:
snap.tel2_present = True
hdr_off = SOF_TEL_EXT_HDR_OFFSET - bias
if hdr_off + 16 <= len(tel2):
_, ver, max_cores, num_secs, seq, ts_us = struct.unpack_from(
"<IBBHII", tel2, hdr_off
)
snap.tel2_seq = seq
snap.tel2_timestamp_us = ts_us
# 1. Hot Line 0 (0x0140)
hl_off = SOF_TEL_OFF_HOT_LINE0 - bias
ppl_xruns: List[int] = [0] * 16
if hl_off + 64 <= len(tel2):
vals = struct.unpack_from("<5H5H5HH16H", tel2, hl_off)
ll_ov = vals[0:5]
dp_miss = vals[5:10]
act_ll = vals[10:15]
snap.total_xrun_events = vals[15]
ppl_xruns = list(vals[16:32])
for c in range(min(5, len(snap.cores))):
snap.cores[c].ll_overruns = ll_ov[c]
snap.cores[c].dp_deadline_misses = dp_miss[c]
snap.cores[c].active_ll_tasks = act_ll[c]
# 2. Gateway Hot (0x0180, 16 x 8B)
gw_hot_off = SOF_TEL_OFF_GW_HOT - bias
gw_hot_list = []
if gw_hot_off + 128 <= len(tel2):
for g in range(16):
tot_kb_f, avail_b, xrun_c = struct.unpack_from(
"<IHH", tel2, gw_hot_off + g * 8
)
gw_hot_list.append((tot_kb_f, avail_b, xrun_c))
# 3. Memory Section (0x0240, 256B)
mem_off = SOF_TEL_OFF_MEM_SEC - bias
if mem_off + 256 <= len(tel2):
(
hp_free,
hp_tot,
lp_free,
lp_tot,
ebb_lo,
ebb_hi,
lp_ebb,
_rsvd,
) = struct.unpack_from("<HHHHIIII", tel2, mem_off)
if hp_tot > 0:
snap.hpsram.total_phys_pages = hp_tot
snap.hpsram.free_phys_pages = hp_free
if not got_hp_tlv or snap.hpsram.total_banks == 0:
hp_banks = (hp_tot + 31) // 32
pwr_hp = bin(ebb_lo).count("1") + bin(ebb_hi).count("1")
snap.hpsram.total_banks = hp_banks
snap.hpsram.powered_banks = (
min(hp_banks, pwr_hp)
if pwr_hp > 0
else (hp_banks if hp_free < hp_tot else 0)
)
snap.hpsram.gated_banks = max(
0, snap.hpsram.total_banks - snap.hpsram.powered_banks
)
snap.hpsram.bank_powered = [
bool(((ebb_lo if b < 32 else ebb_hi) >> (b % 32)) & 1)
if pwr_hp > 0
else (b < snap.hpsram.powered_banks)
for b in range(hp_banks)
]
self.cached_hpsram = snap.hpsram
if lp_tot > 0:
snap.lpsram.total_phys_pages = lp_tot
snap.lpsram.free_phys_pages = lp_free
if not got_lp_tlv or snap.lpsram.total_banks == 0:
lp_banks = (lp_tot + 15) // 16
pwr_lp = bin(lp_ebb).count("1")
snap.lpsram.total_banks = lp_banks
snap.lpsram.powered_banks = (
min(lp_banks, pwr_lp)
if pwr_lp > 0
else (lp_banks if lp_free < lp_tot else 0)
)
snap.lpsram.gated_banks = max(
0, snap.lpsram.total_banks - snap.lpsram.powered_banks
)
snap.lpsram.bank_powered = [
bool((lp_ebb >> b) & 1)
if pwr_lp > 0
else (b < snap.lpsram.powered_banks)
for b in range(lp_banks)
]
self.cached_lpsram = snap.lpsram
# Heaps[6] (each 20B at mem_off + 24)
snap.heaps = []
tot_alloc = 0