aboutsummaryrefslogtreecommitdiffstats
path: root/psp_out/MEC-PM4-FOOTHOLD.md
blob: 74b19b858058a1b01560e2af2b75fefaeaa85a75 (plain) (blame)
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
# MEC / PM4 — first foothold on a previously untouched surface

Context: PM4 had **zero** coverage in this project. (An earlier grep suggested
"MEC: 15 docs" — those were all the word *MECHANISM*. Actual coverage was nil.)

This is the surface worth attacking because it is the **normal submission path**:
the host writes PM4 command packets into a ring buffer in memory and MEC firmware
parses them. Host-writable data, parsed by a microcontroller, and — unlike every
PSP path in this project — **not signature-gated at the parse step**.

## 1. Firmware located and characterised

`gc_11_0_0_mec.bin`, from tinygrad's firmware cache (`fetch_fw` -> linux-firmware).

    size 406528, header v2.0, ip 11.0, ucode_ver 0xae6
    ucode_size 406272 @ offset 256
    entropy 5.62  <- NOT encrypted, plaintext code

Copy kept as `mec_11_0_0.bin`; payload as `mec_ucode.bin`.

## 2. Architecture: RV64 RISC-V ("RS64") — confirmed, not assumed

The dword histogram is dominated by `...b3` (OP), `...93` (OP-IMM), `...37`/`...b7`
(LUI) and critically `...9b` (**ADDIW, an RV64-only encoding**). Capstone RV64
then decodes it cleanly, with textbook function structure:

    0x001100  sd    a0, 0x7c0(tp)
    0x00110c  ld    a0, 0x7b8(tp)
    0x001110  srli  a1, a0, 0x30
    0x00111c  beq   a1, a2, 0xa4
    0x001128  addi  sp, sp, -0x58      <- prologue
    0x00112c  sd    s0, 0(sp)

IDA agrees: `PROCNAME = riscv`, **164 functions** auto-detected, code 0x1100..0x3c480.
(Note: this is MEC. The earlier "RS64 SMU" claim in this project was retracted —
the SMU is Xtensa. Both can be true; they are different cores.)

## 3. Two signed sub-images

`$PS1` containers at ucode offset **16** and again at **0x41300** (the value the
v2_0 header's `jt_offset` field actually points at — an earlier mis-parse read it
as `0x1d`, which was `ucode_feature_version`). The second header carries
`ucode_ver = 0xae6`, matching. This is the usual MEC1/MEC2 pair.

## 4. THE PM4 DISPATCH TABLE — found and verified

**Base `0x414d8`, stride `0x18`, indexed by PM4 type-3 opcode.**

Verified against tinygrad's own `pm4_nv` opcode list — five *consecutive* opcodes
land on consecutive slots with valid in-range handler addresses:

| opcode | table entry | handler | packet |
|---|---|---|---|
| 0xa2 | 0x042408 | 0x03241c | `PACKET3_MAP_QUEUES` |
| 0xa3 | 0x042420 | 0x00b804 | `PACKET3_UNMAP_QUEUES` |
| 0xa4 | 0x042438 | 0x00b8ac | `PACKET3_QUERY_STATUS` |
| 0xa5 | 0x042450 | 0x00b8b8 | `PACKET3_RUN_LIST` |
| 0xa6 | 0x042468 | 0x032530 | `PACKET3_MAP_PROCESS_VM` |
| 0x01 | 0x0414f0 | 0x03b0a8 | `SET_Q_PREEMPTION_MODE_INIT_SHADOW_MEM` |
| 0x02 | 0x041508 | 0x03b108 | (not in tinygrad's list) |

Six of seven populated slots match known PM4 names, and the five-in-a-row run is
not attributable to chance. These are precisely the compute/HQD queue-management
packets, which is exactly MEC's job.

### The second word per entry may be the bounds check
Each entry carries a second dword: `0x0108c1` (MAP_QUEUES), `0x010002`
(UNMAP/QUERY/RUN_LIST), `0x010001` (MAP_PROCESS_VM), `0x070000` (the low-index
pair). The shape `(0x01 << 16) | N` suggests a per-packet **expected/maximum
dword count** — i.e. the parser's length validation, driven by a table rather
than per-handler code. If so, that table is the first thing to audit: a wrong or
absent entry is exactly how a PM4 parser gets a length bug.

## Status: foothold, NOT a finding
No vulnerability yet. What exists now is: the firmware identified, decrypted
(never was), correctly disassembling, loaded in IDA, and the packet dispatch
table located and cross-validated against an independent opcode list.

## Next
1. Decode the per-entry second dword across all populated slots; confirm whether
   it is a length bound, and find where the parser compares it to the packet's
   `count` field (type-3 header bits 29:16).
2. Read `MAP_QUEUES` (0x3241c) — it consumes host-supplied queue descriptors
   containing addresses, the richest of the five.
3. Only ~29% of the image is in auto-detected functions; the dispatch table's
   handlers cluster at 0x3AFE0-0x3C2B0, so force-analyse that region.

================================================================================
## Round 2 — the dispatcher's structure and a first unbounded-looking index

### Table entries are case labels, not function starts
`0x3241c` (MAP_QUEUES) is **inside** `sub_31360` (0x31360-0x34224, 11972 bytes),
and `0x32530` (MAP_PROCESS_VM) is in the same function. So the PM4 table's
"handlers" are **case labels within one large dispatcher**, as a compiler emits
for a switch. `UNMAP_QUEUES`/`QUERY_STATUS`/`RUN_LIST` (0xb804/0xb8ac/0xb8b8)
live in a separate function near 0xb800.

### Runtime address space: per-hart state at `3 << 48`
The prologue establishes the addressing model:

    li    s0, 3
    slli  s0, s0, 0x30          ; s0 = 0x0003_0000_0000_0000
    csrr  s1, mhartid           ; MEC is multi-core (per pipe)
    slli  t1, s1, 3
    add   t1, t1, s0            ; t1 = per-hart state base
    ld    a7, 0x220(t1)

So MEC's data window sits at `0x0003000000000000 + hartid*8`. This also explains
why no absolute `LUI` reaches the dispatch table: globals are `tp`/hart-relative,
and **file offset != runtime address**.

### The first thing worth chasing: an index with no visible bound

    slli  t3, a1, 0x20
    srli  t3, t3, 0x20          ; t3 = a1 & 0xFFFFFFFF  (zero-extend)
    slli  a1, t3, 5             ; * 32
    add   a1, a1, a0
    add   a1, a1, a7            ; base + a0 + index*32
    lw    a1, 0x14(a1)          ; load at +0x14 -- NO range check seen

`a1` is arg 2 of the dispatcher, scaled by 32 and used as an array index with no
comparison beforehand. Contrast with the fields immediately after, which *are*
bounded — 5-bit extractions masked to `0x1F`:

    srli  a3, a4, 0x20 ; andi a5, a3, 0x1F
    srli  a7, a4, 0x25 ; andi a5, a7, 0x1F
    srli  a2, a4, 0x2A ; andi s1, a2, 0x1F

That contrast is the interesting part: the author *did* mask the queue/pipe/vmid
selectors, but the `a1*32` index arrives pre-scaled with no check in this
function.

### The open question (do not skip this)
**Is `a1` host-controlled?** It is a parameter, so the bound may legitimately live
in the caller — which is exactly the pattern that killed most PSP leads in this
project ("trust argument marshalling"). Tracing `sub_31360`'s callers and the
provenance of arg 2 is the next step, and no claim should be made until that is
done.

### Also still open
The per-entry second dword (`0x0108c1`, `0x010002`, `0x010001`) is still
unconfirmed as a length bound; finding where the parser compares it against the
type-3 header's count field (bits 29:16) remains the cleanest way to characterise
the parser's validation.

================================================================================
## Round 3 — the unbounded index is bounded BY THE CALLER. Lead deflates.

Traced `a1` (the `*32` index) to its origin. Both call sites pass `a1 = s4` from
`sub_34228`, which is a PM4 entry point (**no callers** — reached indirectly) that
reads the packet stream from a FIFO:

    lwu  a5, 0x6F8(tp)      ; repeated reads of the SAME address returning
    lwu  s0, 0x6F8(tp)      ; different values == a FIFO pop.
    ld   a5, 0x6F8(tp)      ; this is the PM4 packet data port.
    ld   s2, 0x6F8(tp)

And `s4` is range-checked before the dispatcher is called:

    0x034430  beqz  s1, loc_34440
    0x034434  ld    a5, [var_48]
    0x034438  lw    a5, 0(a5)
    0x03443c  bltu  s4, a5, loc_34694   ; s4 < limit -> proceed
    ...
    loc_34694 ... 0x346f0  jal sub_31360

The branch **target** of the bounds check is the path that reaches the call, so
arriving at `sub_31360` via that site requires `s4 < limit`. A second, independent
check guards the other use:

    0x034728  lw    a4, -0x40(a3)
    0x03472c  bltu  s4, a4, loc_346C0   ; checked again before `sw s4, 0Ch(a0)`

So the `slli a1, t3, 5` / `lw a1, 0x14(a1)` sequence inside `sub_31360` is not an
unbounded index — the bound simply lives one frame up. This is the same
"argument marshalling is trusted, and correctly so" pattern that killed the two
original double-fetch leads and most of this project's PSP leads.

**Prediction check:** I put this at ~20% before tracing, on the grounds that the
bound was probably in the caller. That was the right call, and it is the seventh
consecutive lead this session to deflate on closer reading.

### One detail left genuinely open (small)
The `0x3443c` check is *conditional*: `beqz s1, loc_34440` skips it when `s1 == 0`.
On that fall-through the code takes a different comparison (`bltu s0, a5`) and a
different path, so it does not obviously reach the same use of `s4` — but the
second call site at `0x3467c` is reached via a different predicate
(`bltu a4, a5` on a queue count at `0x240(tp)`), and at `0x34524` `s4` is
*restored* from the stack rather than derived from the packet. Establishing which
`s4` reaches `0x3467c` is unfinished; it is a small, bounded question, not a lead.

## Status of the MEC/PM4 surface after three rounds
Genuine progress, no vulnerability:
* firmware identified, confirmed **plaintext RV64 RISC-V**, loaded in IDA;
* **PM4 dispatch table located and validated** against an independent opcode list;
* dispatcher structure understood (case labels in `sub_31360`, hart-relative state
  at `3 << 48`);
* **the packet data port identified: `0x6F8(tp)`** — this is the single most useful
  artifact for future work, since every host-controlled byte enters through it.

The productive next step is to work *forward from `0x6F8(tp)`* — enumerate every
read of that port and follow the values — rather than backward from suspicious
arithmetic. That gives a complete, systematic map of host-controlled data in the
parser instead of spot-checking instruction patterns.

================================================================================
## Round 4 — structural map of MEC (understanding, not bug-hunting)

Switched from hunting suspicious arithmetic to mapping the firmware forward from
the packet port. This is the resulting picture.

### The register window: `tp`-relative
MEC addresses its registers/state through `tp`. Scanning every `tp`-relative
load/store in the code region: **101 distinct load offsets, 135 store offsets**.
The read/write ratio classifies them cleanly:

| offset | reads | writes | inferred role |
|---|---|---|---|
| `tp+0x6f8` | **749** | 4 | **PM4 packet FIFO** (extreme asymmetry) |
| `tp+0x038` | 162 | 0 | hardware status (read-only) |
| `tp+0x250` | 130 | 0 | hardware status |
| `tp+0x0f0` | 120 | 0 | hardware status |
| `tp+0x268` | 80 | 0 | hardware status |
| `tp+0x020` | 337 | 10 | hot state |
| `tp+0x390` | 68 | 67 | firmware variable (balanced) |
| `tp+0x2f8` | 50 | 58 | firmware variable |
| `tp+0x3a8` | 41 | 58 | firmware variable |

Zero-write + high-read = hardware status registers; balanced = firmware state;
the 749/4 outlier is the data port. This is a reusable map for future work.

### Per-hart state at `3 << 48`
`csrr sN, mhartid` + base `0x0003_0000_0000_0000` + `hartid*8` indexes per-pipe
state (MEC is multi-core, one hart per pipe). Masks and limits are loaded from
this region, e.g. `ld a5, 0x20(3<<48)` is used as a field mask.

### Known functions

| function | size | role |
|---|---|---|
| `sub_3630` | 13120 | main packet processing (FIFO drain + MQD ingest) |
| `sub_31360` | 11972 | queue-management dispatcher; `MAP_QUEUES` and `MAP_PROCESS_VM` are case labels inside it |
| `sub_34228` | 1460 | PM4 entry point (no callers, reached indirectly); pops the FIFO, bounds-checks indices, calls `sub_31360` |
| ~`0xb800` | - | `UNMAP_QUEUES` / `QUERY_STATUS` / `RUN_LIST` handlers |

### Two ingest paths in `sub_3630`, both bounded

**1. Drain / packet skip — `0x44b0`:**

    li    a5, 0x40
    loop: lwu a4, 0x6F8(tp)      ; read and DISCARD
          addiw a5, a5, -1
          bnez  a5, loop         ; exactly 64 dwords

**2. MQD ingest — `0x5edc`:**

    ld    t1, 0x101120           ; destination pointer (runtime addr)
    loop: lwu t6, 0x6F8(tp)
          sw  t6, 0(t1)
          addiw a5, a5, 1
          addi  t1, t1, 4
          bltu  a5, t2, loop

`t2` is **a constant**, not a packet field:

    andi s4, a3, 0x38
    li   t2, 0x15                ; 21 dwords
    beqz s4, loc_5E88
    li   t2, 0x2F                ; 47 dwords

So the bulk descriptor copy is a fixed 21 or 47 dwords chosen by a firmware mode
bit. **Bounded.**

### Field handling after the bulk copy is masked
The individual fields that follow are AND-ed with a mask from hart state before
being stored:

    ld  a5, 0x20(3<<48)          ; mask
    lwu t1, 0x6F8(tp)
    and t1, a5, t1               ; masked
    sw  t1, -0x7A8(s11)

Not every field is masked (`0x5f28` stores one raw), which is worth noting but is
consistent with those fields being full-width by design.

### Assessment of the surface so far
Everything examined is bounded — by constants, by masks, or by caller-side range
checks. That is four rounds without a vulnerability, but it is now *informed*
negative knowledge: we know where host data enters, how it is bounded, and what
the structure is. The remaining unexamined bulk is the other ~700 FIFO read sites.

================================================================================
## Round 5 — packet consumers mapped; the register-write path resolved

### Consumer map (749 FIFO reads, by containing function)

| function | FIFO reads | size | density |
|---|---|---|---|
| `sub_37DA0` | 140 | 13120 | top consumer |
| `sub_3630` | 65 | 13120 | main packet processing |
| `sub_13190` | 60 | 8372 | |
| **`sub_2C5D0`** | **57** | **1300** | **densest — a pure parser** |
| `sub_35838` / `sub_36528` | 29 each | ~3.5K | |
| *(unanalysed)* | **227** | - | cluster at 0x23c80+ |

`sub_3630` and `sub_37DA0` are the same size (13120) but **92.8% different bytes** —
not a duplicated image, two distinct large handlers.

### `sub_2C5D0` — a register-file write helper
Entered indirectly (no xrefs; callers jump to `base + N*4`). Opens with an 8-way
jump table; the 8th entry is `j loc_2C5EC` — a **self-loop**, i.e. a deliberate
hang on the invalid selector. Each case reads packet dwords and writes them into
the register file at a computed index:

    lui  a1, 0x8001
    slli a1, a1, 0x15          ; register-file base
    add  a5, a5, 0x2C00        ; + fixed window offset
    slli a5, a5, 2             ; * 4
    add  a5, a5, a1
    sw   t4, 0(a5)             ; register write

This is the PM4 `SET_*_REG`/`WRITE_DATA` family — exactly the place a CP must
bound the register index, and historically a real bug class.

### The asymmetry, and why it is NOT a bug
Case 2 derives **two** indices from one packet read and masks only one:

    ld    a4, 0x6F8(tp)
    srli  a2, a4, 0x10         ; index #2 -- NOT masked
    andi  a5, a4, 0x7FF        ; index #1 -- masked to 11 bits

Resolved by determining the FIFO's data width. The firmware builds 64-bit
addresses by combining **two** reads:

    ld   a5, 0x6F8(tp)
    slli a5, a5, 0x20          ; shift LEFT 32
    or   a5, a5, a4            ; OR with a previous read

If one `ld` already returned 64 packet bits, `slli 32` would discard half of it.
So **a FIFO read yields one dword, zero-extended**. Therefore `a4 >> 16` is bits
31:16 — **at most 16 bits**, architecturally bounded by the port width. The
`andi 0x7FF` is needed only because bits 15:11 hold other fields; the upper field
needs no mask because nothing above bit 31 exists.

**Coherent design. Not a bug.** (273 of the 749 reads are 64-bit `ld` form, so
this width property governs a large fraction of the parser.)

### Method note
This round worked the way the previous seven leads should have: spot an anomaly,
state the precise question that decides it (*what is the FIFO's data width?*),
and answer it with evidence from elsewhere in the binary — rather than asserting
a bug from the anomaly alone.

### Remaining
The 227 FIFO reads outside any recognised function (clustered at 0x23c80+) are the
largest unmapped block. Forcing analysis there is the next systematic step.

================================================================================
## Round 6 — the unmapped block, and the RIGHT question for this surface

The 227 unanalysed FIFO reads form 12 clusters; the largest (75 reads,
`0x2af9c-0x2c5ac`) sits immediately before the register-write helper. It is
jump-table target code, which is why IDA never traced it.

### What it does: consumes 64-bit ADDRESSES from the packet

    lwu  s0, 0x6F8(tp)         ; flags word
    ld   a4, 0x6F8(tp)         ; address lo
    ld   a5, 0x6F8(tp)         ; address hi
    slli a5, a5, 0x20
    or   a5, a5, a4            ; assemble 64-bit address
    sd   a5, 0x390(tp)         ; stage it (tp+0x390 = the 68r/67w state var)
    ld   s1, 0x390(tp)

...twice, and a packet flag selects an address window:

    andi a3, s0, 4
    snez a3, a3
    addi a3, a3, 3             ; 3 or 4
    slli a3, a3, 0x1D          ; 0x6000_0000 or 0x8000_0000

### Those addresses are dereferenced directly — both directions

    ld   a5, 0xF8(tp)
    sd   a5, 0(s1)             ; STORE to a packet-supplied 64-bit address

    ld   a5, 0x390(tp)
    lw   a5, 0(a5)             ; LOAD from a packet-supplied 64-bit address

No range check, no mask, no aperture comparison anywhere on these paths.

### Why that is NOT automatically a bug — and what the real question is
This is **normal and by design** for a GPU command processor. PM4 packets such as
`WRITE_DATA`, `COPY_DATA`, `WAIT_REG_MEM` and `RELEASE_MEM` all carry addresses,
and the protection model is **GPUVM**: the address is translated through the page
tables of the submitting queue's VMID. Firmware is not supposed to bounds-check
it; the MMU confines it.

So the security question for this entire surface is **not** "is the address
validated?" (it is not, correctly) but:

> **Which VMID / translation context does the CP use when it dereferences a
> packet-supplied address — the submitting queue's, or a privileged one?**

If any path dereferences with VMID 0 / physical / a privileged context while the
address comes from an unprivileged queue's packet, that is a genuine escalation.
If every path uses the queue's own VMID, the surface is confined by the MMU and
the whole address-handling area is uninteresting no matter how unchecked it looks.

This reframes the remaining work productively: stop looking for missing bounds
checks (there will not be any, by design) and instead trace VMID selection. The
5-bit `andi 0x1F` field extractions seen in Round 2 at the dispatcher entry are
very likely the VMID/queue/pipe selectors, which makes them the thread to pull.

### Status
Six rounds, no vulnerability, but the surface is now genuinely *understood*:
entry point, packet port, register map, dispatcher structure, descriptor ingest,
register-write path, and now the address-handling model and its protection
assumption. That last item is the difference between guessing and knowing where
a bug could actually live here.

================================================================================
## Round 7 — MEC-as-confused-deputy for PSP SRAM: REFUTED (statically, no hardware)

Hypothesis worth testing: the vendor RDL says the C2PMSG **ATTR** arrays gate the
x86 host only — *on-die SMN masters bypass them*. MEC is an on-die master we can
drive with arbitrary PM4. `PACKET3_COPY_DATA` with
`SRC_SEL=MEM_MAPPED_REGISTER`, `DST_SEL=TC_L2` is literally "read a register,
write it to memory I choose". If its source could name MP0, the PSP's host gating
would not apply.

**It cannot.** PM4's register address space is far below MP0:

    PACKET3_SET_CONFIG_REG   0x2000 - 0x2C00
    PACKET3_SET_SH_REG       0x2C00 - 0x3000
    PACKET3_SET_CONTEXT_REG  0xA000 - 0xA400
    PACKET3_SET_UCONFIG_REG  0xC000 - 0xC400   <- top of PM4 register space
    MP0_SMN_C2PMSG_0         0x16040            <- dword offset in BAR5

Corroborated independently from the firmware: `sub_2C5D0`'s register writes compute
`base + (idx + 0x2C00)*4`, and **`0x2C00` is exactly `PACKET3_SET_SH_REG_START`** —
so MEC's register-file view is anchored at the PM4 SH_REG window, and its 16-bit
index reaches at most dword `0x12BFF`, still short of `0x16040`.

Two independent lines of evidence agree, so no hardware test is warranted. The
idea cost nothing and was refuted before any risk to the card — which is the
correct order of operations and the opposite of how the `$AMDVBFL` question was
handled earlier in this project.

### Consequence for the PSP-SRAM question
The on-die-deputy route via MEC is closed. It remains true that on-die masters
bypass ATTR, so the *principle* is sound — but MEC specifically cannot address
MP0. Any future deputy would need a master whose address window actually covers
`0x03800000`/`0x03900000`, and nothing we have found so far does.

================================================================================
## Round 4 — table base corrected, length-bound hypothesis refuted, taint tooling

Tool: `../mes/mec_audit.py` (`table` / `bounds` / `taint`). This round applies the
methodology that worked on SDMA (`../f32/AUDIT-SDMA-01.md`): recover the dispatch
table, validate it against published enums, then taint from the packet data port with
dataflow that respects calls *and* basic blocks.

### The table base in Round 1 was 0x100 low

**`0x414d8` is wrong; the base is `0x415d8`.** This is the same nested-`$PS1` offset
error that put every address in `dmcub/AUDIT-DMCUB-01.md` 0x100 low, and it is now
recorded in three separate places in this tree. All five anchors from Round 1 verify
exactly at the corrected base:

```
op 0xa2 -> 0x03241c   op 0xa3 -> 0x00b804   op 0xa4 -> 0x00b8ac
op 0xa5 -> 0x00b8b8   op 0xa6 -> 0x032530      (all OK)
```

Naming is the validation, and it only works at the corrected base: **5 of 7 populated
slots carry a published `PACKET3_*` name** — `MAP_QUEUES`, `UNMAP_QUEUES`,
`QUERY_STATUS`, `RUN_LIST`, `MAP_PROCESS_VM`. At the old base, zero did.

### This table is the queue-management path only

Seven populated slots cannot cover compute PM4 (`DISPATCH_*`, `WRITE_DATA`,
`RELEASE_MEM`, …). Two scans looked for another dispatch structure and found none:

* no second run of `(handler, flags)` pairs anywhere in the image beyond this table;
* no run of plain code pointers in sub-image 1 that opcode-indexes onto the enum
  (best fit: 0/123).

So the remaining packets are dispatched by compare chains, consistent with Round 2's
"case labels inside one large dispatcher". The named five are exactly the KIQ/HQD
packets, which is MEC's job.

### The per-entry second dword is NOT a length bound — hypothesis refuted

Round 1 flagged `(0x01 << 16) | N` as a probable table-driven length check and called
it "the first thing to audit". Across all populated slots it does not behave like one:

| opcode | packet | dword1 | low half |
| --- | --- | --- | --- |
| 0xa2 | MAP_QUEUES | 0x000108c1 | **2241** |
| 0xa3 | UNMAP_QUEUES | 0x00010002 | 2 |
| 0xa4 | QUERY_STATUS | 0x00010002 | 2 |
| 0xa5 | RUN_LIST | 0x00010002 | 2 |
| 0xa6 | MAP_PROCESS_VM | 0x00010001 | 1 |

2241 dwords is not a bound for `MAP_QUEUES`, and 2 is not the length of `UNMAP_QUEUES`
or `QUERY_STATUS` in the ABI. The low half is a flags/bitfield, not a count, and the
high half only separates this group (0x0001) from the two low opcodes (0x0007). **The
parser's length validation is not in this table**; it has to be found in code.

### Taint from the packet data port

Round 3's best artifact was `0x6F8(tp)`, the PM4 data port. `mec_audit.py taint` treats
every read of it as host data and propagates with two rules learned the hard way in the
SDMA audit: a `jal` clobbers caller-saved registers, and **an unconditional `j`/`jr`
ends the block**.

That second rule matters. Without it the pass reported a striking lead at `0x3af08` —
a raw packet dword shifted left 36 into MMIO-aperture bits and used as a store address,
which would have been a host-controlled register write. It is an artifact: `0x3aefc` is
an unconditional `j`, so the block at `0x3af00` gets its base from elsewhere. Adding
block-awareness removed it along with 16 other sinks (92 -> 75).

Of the 75 survivors, 27 build their address as `(hi << 32) | lo` from two packet
dwords — that is a GPU virtual address, confined by the queue's page tables exactly as
SDMA's PTEPDE was proven to be [HW]. The rest are unclassified.

### Status after round 4: still no finding

Gained: a corrected and independently validated dispatch table, a refuted hypothesis,
reusable tooling, and 75 taint sinks with 27 already explained. Not gained: any
demonstrated bug.

Next, in order:
1. Classify the remaining ~48 sinks — specifically whether any address is formed from
   a *single* packet dword (internal state index) rather than a 64-bit VA pair.
2. Find the length validation in code, since it is not in the table.
3. Locate the privileged-packet check. PM4 distinguishes privileged from unprivileged
   packets, and on SDMA the equivalent (`RB_PRIV`) turned out to be the whole boundary
   — with a hardware live-flip test available to confirm it.

================================================================================
## Round 5 [HW] — the PM4 privilege boundary exists and holds

Script `../mes/hw/mec_pm4_priv_probe.py`, evidence `../mes/hw/EVIDENCE-mec-pm4-priv.txt`.

The structural question, borrowed from the SDMA result: PM4 packets are submitted by
**unprivileged user queues**, and `PACKET3_WRITE_DATA` with `dst_sel = 0` names a
memory-mapped **register**. If that is not gated, it is a user->kernel primitive — the
thing none of the ten DMCUB findings can be, because that inbox is kernel-only.

tinygrad's AM driver sets `cp_hqd_pq_control.priv_state`/`kmd_queue` **only for KIQ**,
so an ordinary compute ring is exactly the unprivileged case. A 2x2 was run — queue
privilege x write destination — because either factor alone is uninterpretable:

| | `dst_sel = memory` | `dst_sel = register` |
| --- | --- | --- |
| **priv_state = 0** (ordinary compute queue) | **wrote** 0x7e5701ce | **refused**, register unchanged, queue then faults |
| **priv_state = 1** (live-flipped) | **wrote** 0x7e5701ce | **wrote** 0x7e5701ce, queue stays alive |

Both controls matter and both are in the table:

* the **memory** column proves the packet encoding, the ring, the doorbell and the
  submission path are all correct. Without it, "the register did not change" is
  equally consistent with a malformed packet — the trap that made the first SDMA
  `RB_PRIV=0` run inconclusive.
* the **priv_state=1** row proves the refusal is about *privilege*, not about
  `WRITE_DATA`->register being unsupported on MEC. That alternative explanation was
  live until this row existed.

Privilege was changed by live-flipping `CP_HQD_PQ_CONTROL` on a queue that was already
running (`0x00008509 -> 0xc0008509`), so the only difference between the two runs is
that bit — the same technique that isolated `RB_PRIV` on SDMA.

**Verdict: the PM4 register-write boundary is real and enforced on gfx11.** An
unprivileged compute queue cannot write registers, and attempting it faults the queue
rather than silently continuing.

### What this means for the surface

This closes the most valuable single question about PM4, and it closes it *negatively*:
the one surface on this card that an unprivileged process can submit to does **not**
hand out register writes. Combined with the SDMA result, the pattern across both
user-submittable engines is identical — memory access confined by the VM, register
access gated by a per-queue privilege bit, and the gate holds under test.

What is still open on PM4 is narrower and less likely to pay:
1. the ~48 unclassified taint sinks (whether any address is formed from a *single*
   packet dword rather than a 64-bit VA pair);
2. the length validation, which Round 4 showed is not table-driven;
3. whether any *other* packet reaches a privileged effect without consulting the same
   bit — `MAP_QUEUES`/`MAP_PROCESS_VM` are the candidates, since they manipulate queue
   and VM state by design.

================================================================================
## Round 6 — the indirect route (MAP_QUEUES) is UNTESTED, not closed

Script `../mes/hw/mec_pm4_mapqueues_probe.py`.

Round 5 closed the direct route: an unprivileged queue cannot write registers. The
obvious follow-up is indirect:

```
unprivileged queue --MAP_QUEUES--> map a queue whose MQD sets priv_state=1
                   --WRITE_DATA(register) on that queue--> registers
```

That would be a full user->kernel chain needing no memory-safety bug at all, just one
missing check. KFD only ever issues `MAP_QUEUES` on the kernel-owned HIQ/KIQ ring, but
"the kernel never does it" is not enforcement.

**Result: inconclusive, and deliberately reported as such.**

```
priv_state=0   NOP before: retired   MAP_QUEUES: stalled   NOP after: dead
priv_state=1   NOP before: retired   MAP_QUEUES: stalled   NOP after: dead
```

The stall is identical in both modes, and identical again after seeding the target MQD
with the one the driver had just built (so the packet had something plausible to map).
Since the privileged queue stalls too, **the stall is not a privilege effect** — the
overwhelmingly likely reading is that `MAP_QUEUES` is an HIQ/KIQ-pipe packet and is
simply not serviced on an ordinary compute ring.

This matters methodologically: a stall looks exactly like the round-5 privilege fault,
and without the `priv_state=1` comparison it would have been easy to write up as "the
gate covers MAP_QUEUES too". It does not support that claim. The probe's verdict text
was corrected to say so rather than to echo the round-5 conclusion.

**So the indirect chain remains open.** Testing it properly needs submission on the HIQ
pipe with a user-owned ring, which tinygrad's AM does not currently expose (its KIQ MQD
slots are not allocated for arbitrary reuse — `setup_ring(kiq_xcc=0)` indexes past
`mqd_mc`). That is the concrete blocker, and it is a driver-plumbing problem rather
than a firmware one.

================================================================================
## Round 7 — HIQ plumbing attempted; blocked, and the blocker is now precise

Script `../mes/hw/mec_hiq_probe.py`. Goal: stand up a KIQ/HIQ ring so the round-6
question ("is MAP_QUEUES refused on a compute ring, or simply not serviced there?")
gets its missing control.

Two obstacles were cleared, one was not:

1. **MQD slot shortage — fixed.** `AM_GFX.init_sw` allocates `mqd_paddr` with
   `2 + is_vf` entries while `setup_ring(kiq_xcc=0)` indexes `queue + 2*kiq` = 2, so it
   raised `IndexError`. Appending one allocation to the driver's own lists lets its
   MQD-building code run unchanged.
2. **Doorbell routing — addressed.** `setup_ring` gives the KIQ
   `AMDGPU_DOORBELL_KIQ` (index 0), but AM only enables the SDMA and MEC_RING
   doorbell apertures, so index 0 is very likely unrouted. The HQD was re-pointed at
   `MEC_RING0 + 4`, an index the compute probe had already rung successfully.
3. **The HQD never activates.** After `setup_ring(kiq_xcc=0)`, `CP_HQD_ACTIVE` reads
   back **0x0** — the CP rejected the queue — and the ring never retires a NOP.

Root cause, from the kernel: tinygrad's KIQ path is **VF-only** (`init_hw` calls it
under `if self.adev.is_vf`), and it hardcodes `me=2, pipe=1, queue=0`. amdgpu does not
use constants: `amdgpu_gfx_kiq_acquire()` picks me/pipe/queue from the per-device queue
bitmap, and a PF KIQ additionally needs the HPD EOP region, MEC pipe enablement and the
KIQ doorbell aperture. That is a port of amdgpu's KIQ bring-up, not a patch.

**Status: the indirect MAP_QUEUES chain is still open, and untested.** No claim is made
in either direction. What changed is that the blocker is now specific — three named
prerequisites rather than "tinygrad doesn't expose it" — so the next attempt starts
from a known position.

Worth noting for honesty: it would have been easy to read round 6's stall plus this
round's dead KIQ as "MAP_QUEUES is gated everywhere". Neither result supports that. A
queue that never activates cannot refuse anything.

================================================================================
## Round 8 — KIQ port: three steps forward, one gap left

Continuing the round-7 blocker. amdgpu's KIQ bring-up was read and ported piece by
piece; the queue now activates but still does not fetch.

**Fixed 1 — the slot was wrong, not just unallocated.** `amdgpu_gfx_kiq_acquire()`
scans the compute queue bitmap downward and requires `queue == 0`; gfx11 sets
`num_mec = 1`, `num_pipe_per_mec = 4`, so `mec` is always 0 and `ring->me = mec + 1 =
**1**`. tinygrad's `kiq_xcc` path hardcodes `me=2, pipe=1` (a VF layout), which is why
round 7 saw `CP_HQD_ACTIVE = 0`. The KIQ slot on this part is **me=1, pipe=3, queue=0**,
and `setup_ring`'s ordinary path reaches it with `idx = 12` — so the MQD is still built
by the driver's own code.

Result: **`CP_HQD_ACTIVE = 0x1`**. The queue activates.

**Fixed 2 — the HIQ pointer.** `gfx_v11_0_kiq_setting()` writes
`RLC_CP_SCHEDULERS = (me << 5) | (pipe << 3) | queue | 0x80`; for this slot that is
`0x38 | 0x80`. (tinygrad's VF constant `(2<<5)|(1<<3)|0x80` encodes the wrong slot.)

**Fixed 3 — the pipe was not enabled.** gfx11 is RS64, so the per-pipe enables live in
**`CP_MEC_RS64_CNTL`**, not `CP_MEC_CNTL` (`gfx_v11_0_cp_compute_enable` branches on
`rs64_enable`). It read `0x04000000` — **only `mec_pipe0_active`**. Enabling
`mec_pipe3_active` gives `0x24000000`.

**Still stalled.** With the correct slot, an active HQD, the scheduler pointed at it and
the pipe enabled, `CP_HQD_PQ_RPTR` stays 0 while the doorbell and `CP_HQD_PQ_WPTR_LO`
both reach the queue. A pipe-0 queue on the identical code path retires the same NOP
(`HQD_RPTR 0 -> 2`), so the submission mechanism is sound and the gap is pipe-3 specific
— most likely the per-pipe HPD/EOP programming amdgpu does during compute resume, which
was not ported.

`CP_MEC_RS64_CNTL` was restored to `0x04000000` afterwards.

**Hardware note — this round left a stuck queue, and it cost an ATX cycle.** The pipe-3
HQD could not be dequeued (`CP_HQD_DEQUEUE_REQUEST` left `CP_HQD_ACTIVE = 1`, naturally,
since the pipe was not servicing anything), `GRBM_STATUS` stayed at `0xa800302c` instead
of the `0x0000302c` baseline, and neither `reset_mec()` nor a full AM re-init cleared it.
A cold ATX cycle did: after it, `GRBM_STATUS = 0x0000302c` and the pipe-3 HQD reads
inactive. Worth recording as a standing hazard — **bringing up a compute pipe that does
not fetch leaves an undequeueable queue that only a power cycle clears**, so this work
should be done when an ATX cycle is acceptable.

**MAP_QUEUES therefore remains untested.** The position is much better than round 7
though: the KIQ slot, the scheduler encoding and the pipe-enable register are all now
known and verified, and the one remaining piece is named.

================================================================================
## Round 9 — the KIQ port is abandoned; cost/benefit no longer justifies it

Two further prerequisites from `gfx_v11_0.c` were ported and neither closed the gap:

* `gfx_v11_0_cp_compute_enable()` on RS64 enables **all four pipes together** with
  `MEC_HALT = 0` and `MEC_INVALIDATE_ICACHE = 0`, not one pipe's bit.
  `CP_MEC_RS64_CNTL` went `0x04000000 -> 0x3c000000` as intended.
* `gfx_v11_0_kiq_init_register()` programs `CP_MEC_DOORBELL_RANGE_LOWER/UPPER`; a
  doorbell outside that window is silently ignored by the CP, which is
  indistinguishable from a queue that will not fetch. The range was set around our
  doorbell.

With the correct slot (me=1, pipe=3, queue=0), `CP_HQD_ACTIVE = 1`, the scheduler
pointed at it, all pipes active, the MEC unhalted and the doorbell range programmed,
**the queue still does not retire a NOP**. The remaining candidate is the MEC firmware's
own per-pipe initialisation — amdgpu loads MEC microcode per pipe
(`gfx_v11_0_cp_compute_load_microcode`) and the RS64 MEC likely only services pipes it
was initialised for at load time. Reproducing that means reloading MEC firmware, which
is a substantially larger port.

**Cost is now the deciding factor.** Each failed attempt leaves an undequeueable HQD and
`GRBM_STATUS = 0xa800302c`, recoverable only by a cold ATX cycle (three spent so far).
That is a poor trade for one open question, so this thread is stopped.

### The cheaper route, for whoever picks this up

Answer it statically instead. The PM4 table is validated and `MAP_QUEUES` is at
`0x3241c`; the surrounding code is a case label inside the ~12 KB dispatcher
`sub_31360`, and its head does test firmware state (`ld a4, 0x790(tp); beqz ...`) before
assembling the queue descriptor. Establishing whether any path from that label consults
a privilege bit is a bounded reverse of one dispatcher — no hardware, no ATX cycles, and
it answers the same question.

### Status of the whole MEC/PM4 thread

* [HW] the **direct** route is closed: unprivileged queues cannot write registers,
  proven as a 2x2 (round 5);
* the **indirect** route (`MAP_QUEUES`) is **untested**, with the blocker now fully
  characterised rather than vague;
* everything else on this surface (length validation, the ~48 taint sinks) was rated
  low-yield in round 4 and nothing since has changed that.

================================================================================
## Round 10 [ST] — MAP_QUEUES has no firmware privilege check; the boundary is routing

The cheap route promised in round 9, and it settles the thread without hardware.

Round 5 established [HW] that `priv_state` is bit 31 of `CP_HQD_PQ_CONTROL` and
`kmd_queue` bit 30 (`0x8509 -> 0xc0008509` when both are set). So a firmware-side
privilege check would have to extract those bits — `srli/srliw ..,0x1f`, a `bltz/bgez`
sign test, an `andi` against `lui 0x80000`, or the `..,0x1e` pair extract.

Walking the CFG from the validated `MAP_QUEUES` case label `0x3241c`, following branches
and descending into called functions to depth 3 — **3984 instructions** — those idioms
appear as follows, and every one resolves to something else:

| idiom | count | what it actually is |
| --- | --- | --- |
| `bltz/bgez` sign test | 2 | not on queue-control words |
| `srli/srliw ..,0x1f` | 2 | **ring-slot phase wait**: `lw a5,0(a3); srliw a4,a5,0x1f; bne a4,a2,<same addr>` — spinning until a slot's ownership bit flips |
| `srli ..,0x1e` | 9 | **index arithmetic**: `and a4,a4,(count-1); slli ..,0x20; srli ..,0x1e` = `(idx & mask) * 4`, i.e. a *masked* ring index |
| `lui 0x80000` | 11 | descriptor construction — the bit is **set** into an outgoing word, never tested |

**There is no test of the submitting queue's privilege anywhere on the path.**

### What that means, combined with the hardware results

* [HW] round 5: an unprivileged queue's `WRITE_DATA(dst_sel=register)` is refused **and
  the queue faults** — the signature of a hardware check, not a firmware branch.
* [HW] round 6: `MAP_QUEUES` is not serviced on a compute ring at all, at either
  privilege level.
* [ST] round 10: MEC's `MAP_QUEUES` handler never consults queue privilege.

The consistent reading is that **the PM4 privilege boundary is enforced by hardware and
packet routing, not by checks inside MEC**. An unprivileged queue cannot escalate via
`MAP_QUEUES` because the packet never reaches that handler from such a queue — not
because the handler refuses it.

That is a *weaker* kind of safety than SDMA's, where `RB_PRIV` is an explicit firmware
gate proven to flip behaviour. It is worth stating as a conditional: **anything that
lets a packet reach the HWS path from a queue the hardware would not have routed there
faces no second line of defence in firmware.** No such route is known here; the value of
the statement is that it tells a future reader exactly what to look for.

### Caveats

* The closure starts at a case label inside a ~12 KB dispatcher, so it includes code
  shared with other packets. That makes the *absence* of an idiom stronger, not weaker —
  more code searched, still nothing.
* Depth-3 call closure; deeper callees were not searched.
* A check implemented without those idioms (a table lookup, or a compare against a value
  fetched from queue state) would not have been caught. The search is idiom-based, and
  is reported as such rather than as a proof.

### Thread status: closed

Direct route closed [HW]; indirect route explained — routing, not firmware [ST+HW];
remaining items (length validation, ~48 taint sinks) rated low-yield in round 4.