aboutsummaryrefslogtreecommitdiffstats
path: root/mes/hw/mec_kiq_bringup.py
blob: 9d48ce828dd74ea5905fa9ea57a7d8e350d85b52 (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
#!/usr/bin/env python3
"""Full KIQ bring-up on a PF, then the MAP_QUEUES question.

Rounds 7-8 got the queue to activate but not to fetch. Two further details from
`gfx_v11_0.c` were missing, and both are done here:

  * `gfx_v11_0_cp_compute_enable()` enables **all** pipes at once on RS64 parts --
    `MEC_PIPE{0..3}_ACTIVE = 1`, `MEC_PIPE{0..3}_RESET = 0`, `MEC_HALT = 0`,
    `MEC_INVALIDATE_ICACHE = 0` -- rather than flipping one pipe's bit, which is all
    round 8 did.
  * `gfx_v11_0_kiq_init_register()` programs `CP_MEC_DOORBELL_RANGE_LOWER/UPPER`. A
    doorbell outside that window is simply ignored by the CP, which looks exactly like
    a queue that will not fetch.

Slot selection is the round-8 result: gfx11 has `num_mec = 1`, so
`amdgpu_gfx_kiq_acquire()` yields **me=1, pipe=3, queue=0**, reachable through
`setup_ring(idx=12)` so the MQD is still built by driver code. The HIQ pointer is
`RLC_CP_SCHEDULERS = (me<<5)|(pipe<<3)|queue|0x80` per `gfx_v11_0_kiq_setting()`.

**Hazard (CONSTRAINTS.md):** a queue on a pipe that never fetches cannot be dequeued and
only a cold ATX cycle clears it, so this script tries to dequeue at the end and reports
`GRBM_STATUS` either way rather than leaving it silent.

usage: PYTHONPATH=/root/psp/tinygrad mec_kiq_bringup.py --apply [--map-queues]
"""
import argparse
import struct
import time

PACKET3_NOP = 0x10
PACKET3_MAP_QUEUES = 0xa2
KIQ_IDX = 12
ME, PIPE, QUEUE = 1, 3, 0


def pkt3(op, count):
    return (3 << 30) | ((count & 0x3FFF) << 16) | ((op & 0xFF) << 8)


def map_queues(mqd_mc, wptr_mc, doorbell_off):
    o2 = ((0 & 3) << 2) | ((2 & 3) << 4) | ((0 & 7) << 21) | ((0 & 7) << 26) \
         | ((1 & 7) << 29)
    return [pkt3(PACKET3_MAP_QUEUES, 5), o2, (doorbell_off & 0x3ffffff) << 2,
            mqd_mc & 0xffffffff, (mqd_mc >> 32) & 0xffffffff,
            wptr_mc & 0xffffffff, (wptr_mc >> 32) & 0xffffffff]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument('--apply', action='store_true')
    ap.add_argument('--map-queues', action='store_true')
    args = ap.parse_args()
    if not args.apply:
        print('dry run')
        return 0

    from tinygrad import Device
    from tinygrad.runtime.autogen.am import am
    adev = Device["AMD"].iface.dev_impl
    gfx, mc = adev.gfx, adev.paddr2mc

    rs64 = adev.reg('regCP_MEC_RS64_CNTL')
    before_rs64 = rs64.read()
    rs64.write(rs64.encode(mec_pipe0_active=1, mec_pipe1_active=1,
                           mec_pipe2_active=1, mec_pipe3_active=1,
                           mec_pipe0_reset=0, mec_pipe1_reset=0,
                           mec_pipe2_reset=0, mec_pipe3_reset=0,
                           mec_halt=0, mec_invalidate_icache=0))
    time.sleep(0.01)
    print('CP_MEC_RS64_CNTL 0x%08x -> 0x%08x (all pipes active, MEC unhalted)' % (
        before_rs64, rs64.read()))

    ring = adev.mm.palloc(0x1000, zero=True, boot=False)
    rptr = adev.mm.palloc(0x1000, zero=True, boot=False)
    wptr = adev.mm.palloc(0x1000, zero=True, boot=False)
    eop = adev.mm.palloc(0x1000, zero=True, boot=False)
    vmqd = adev.mm.palloc(0x1000, zero=True, boot=False)
    vwptr = adev.mm.palloc(0x1000, zero=True, boot=False)

    doorbell = gfx.setup_ring(ring_addr=mc(ring), ring_size=0x1000,
                              rptr_addr=mc(rptr), wptr_addr=mc(wptr),
                              eop_addr=mc(eop), eop_size=0x1000,
                              idx=KIQ_IDX, aql=False)

    gfx._grbm_select(me=ME, pipe=PIPE, queue=QUEUE)
    ctl = adev.reg('regCP_HQD_PQ_CONTROL')
    ctl.write(ctl.read() | ctl.encode(priv_state=1, kmd_queue=1))
    # the CP ignores doorbells outside this window (gfx_v11_0_kiq_init_register)
    adev.reg('regCP_MEC_DOORBELL_RANGE_LOWER').write((doorbell * 2) << 2)
    adev.reg('regCP_MEC_DOORBELL_RANGE_UPPER').write(((doorbell + 0x20) * 2) << 2)
    active = adev.reg('regCP_HQD_ACTIVE').read()
    gfx._grbm_select()
    sc = adev.reg('regRLC_CP_SCHEDULERS')
    sc.write((sc.read() & 0xffffff00) | (ME << 5) | (PIPE << 3) | QUEUE | 0x80)
    print('KIQ me%d.pipe%d.q%d: ACTIVE=%d doorbell=0x%x range=[0x%x,0x%x)' % (
        ME, PIPE, QUEUE, active, doorbell, (doorbell * 2) << 2,
        ((doorbell + 0x20) * 2) << 2))

    pos = [0]

    def submit(dwords, timeout_s=1.0):
        adev.vram.view(ring + pos[0] * 4, len(dwords) * 4)[:] = struct.pack(
            '<%dI' % len(dwords), *dwords)
        adev.gmc.flush_hdp()
        pos[0] += len(dwords)
        adev.vram.view(wptr, 8)[:] = struct.pack('<Q', pos[0])
        adev.gmc.flush_hdp()
        adev.doorbell64[doorbell] = pos[0]
        t0 = time.time()
        while time.time() - t0 < timeout_s:
            if struct.unpack('<Q', bytes(adev.vram.view(rptr, 8)[:]))[0] >= pos[0]:
                return True, time.time() - t0
            time.sleep(0.002)
        return False, time.time() - t0

    ok, dt = submit([pkt3(PACKET3_NOP, 0), 0])
    print('  control: NOP retired=%s (%.1f ms)' % (ok, 1000 * dt))

    if ok and args.map_queues:
        adev.vram.view(vmqd, 0x1000)[:] = bytes(
            adev.vram.view(gfx.mqd_paddr[0], 0x1000)[:])
        adev.gmc.flush_hdp()
        okm, dtm = submit(map_queues(mc(vmqd), mc(vwptr), 0x20))
        okn, _ = submit([pkt3(PACKET3_NOP, 0), 0])
        print('  MAP_QUEUES retired=%s (%.1f ms); NOP after=%s' % (okm, 1000 * dtm, okn))
        print('\n=== MAP_QUEUES on the KIQ: %s' % (
            'ACCEPTED -- so round 6 stall on a compute ring means "not serviced there", '
            'and the chain is closed by pipe routing' if okm and okn else
            'stalled even here -- encoding suspect, chain still open'))
    elif not ok:
        print('\n  still not fetching; MAP_QUEUES not attempted')

    # cleanup, per the CONSTRAINTS hazard
    gfx._grbm_select(me=ME, pipe=PIPE, queue=QUEUE)
    adev.reg('regCP_HQD_DEQUEUE_REQUEST').write(1)
    for _ in range(100):
        if adev.reg('regCP_HQD_ACTIVE').read() == 0:
            break
        time.sleep(0.01)
    left = adev.reg('regCP_HQD_ACTIVE').read()
    gfx._grbm_select()
    rs64.write(before_rs64)
    grbm = adev.reg('regGRBM_STATUS').read()
    print('\ncleanup: HQD ACTIVE=%d, CP_MEC_RS64_CNTL restored 0x%08x, GRBM=0x%08x%s' % (
        left, rs64.read(), grbm,
        '  <-- ATX cycle needed' if grbm != 0x302c else ''))
    return 0


if __name__ == '__main__':
    raise SystemExit(main())