Phase 1B chunk 17: HQD program + CP enable + SubmitTestPM4 — Hello PM4 plumbing complete

Closes the Phase 1B critical path: every link from "userspace calls
SubmitTestPM4" to "EOP fence appears as kIRQBitGFXEOPFence in
WaitInterrupt's irqPending" is now in the codebase. Each link is
backed by upstream-cited code; the chain just hasn't been exercised
on real hardware yet.

(1) CP storage refactored to DART sysmem (chunk 17a):
  Previously KIQ ring + MQD lived in VRAM via the bump allocator.
  That meant the dext couldn't actually write PM4 to the ring
  without first mapping BAR2 inside the dext. Switched both to
  DART-mapped sysmem (cp_alloc_dma_block) so the dext writes
  PM4 directly into the ring buffer through normal CPU stores —
  the GPU fetches via GART translation, same correctness.

  cp_ring_write now actually writes into the ring (previously
  it just advanced wptr); no functional difference for the test
  path, but the staging slot now does what it says.

(2) HQD register programming (chunk 17b):
  cp_hqd_program writes the GFX ring's HQD registers:
    CP_RB0_BASE / BASE_HI    (ring physical bus, [39:8]/[39:40])
    CP_RB0_CNTL              (BUFSZ = log2(ring_dw/2), BLKSZ=8)
    CP_RB_VMID               (0 — system)
    CP_RB0_WPTR              (reset to 0)
    CP_RB0_RPTR_ADDR{,_HI}   (WB page rptr offset)
    CP_RB_DOORBELL_CONTROL   (enable=bit30 + index<<2)
    CP_RB_DOORBELL_RANGE_*   (lower=index, upper=index+1)
  Mirrors gfx_v12_0_cp_gfx_resume. Skips GRBM_GFX_INDEX (default
  pipe). Doorbell index pinned to 0 for first PM4.

  cp_enable toggles CP_ME_CNTL.ME_HALT (bit 21).

  cp_init_full now does: alloc storage → if GC IP base resolved,
  halt CP → program HQD → un-halt CP. Skips HQD path if IP base
  isn't loaded yet (storage stays staged for later).

(3) cp_submit_eop_test (chunk 17c):
  Builds NOP + RELEASE_MEM via cp_emit_eop_fence, kicks doorbell
  via cp_kick_doorbell (writes BAR5 + (doorbell_index<<3) using
  IOPCIDevice::MemoryWrite32 on dev.bar5MemIndex — no dext-side
  BAR5 CPU mapping required), polls *fence_cpu until the fence
  value materialises or timeout_us elapses.

(4) SubmitTestPM4 selector (chunk 17d):
  New selector 14 on MacAMDGPUUserClient. Takes timeout_us,
  returns the observed fence value (0 on timeout). Driven by
  --submit-test in scripts/macamdgpu_ping.swift.

End-to-end path now wired:
  Swift CLI --submit-test
    → SubmitTestPM4 selector
      → cp_submit_eop_test
        → cp_emit_eop_fence (PM4 NOP + RELEASE_MEM into ring)
        → cp_kick_doorbell (BAR5 write via PCI MemoryWrite32)
          GPU side: CP fetches PM4 → executes RELEASE_MEM
            → writes fence value to fence_gpu_addr (WB page)
            → IH ring entry (CLIENT_GFX/SRC_CP_EOP)
            → MSI-X to host
              → MacAMDGPUUserClient::InterruptOccurred
                → ih_drain → mac_amdgpu_ih_dispatch
                  → kIRQBitGFXEOPFence in irqPending
                  → WaitInterrupt wakes userspace
        → polls *fence_cpu directly, returns observed value

Two completion paths are now present (poll vs. interrupt). Either
should work on hardware. The interrupt path is the production-
intended one — polling is just the simplest test signal.

Pre-existing dispatcher bug also repaired in chunk 16: SMUInit /
GMCInit / IMUInit lost their case bodies and silently fell through
to IHInit. Restored each + added missing TMRSetup case.

Build clean: ** BUILD SUCCEEDED **.

Userspace path on real hardware (when entitlement + IP bases are
in place):

  1. LoadDiscoveryBin or SetIPBase to populate IP bases
  2. LoadFirmware(SOS, size) → InitDevice(PSPLoadSOS)
  3. InitDevice(PSPRingCreate) → InitDevice(TMRSetup)
  4. LoadFirmware(PMFW=0x112) → InitDevice(SMUInit)
  5. LoadFirmware for RLC_G, CP_PFP, CP_ME, CP_MEC, MES via PSP
     LOAD_IP_FW
  6. InitDevice(GMCInit) → InitDevice(IHInit) → InitDevice(RLCInit)
     → InitDevice(CPInit)
  7. SubmitTestPM4(timeout_us=1_000_000)
  8. Receive fence value; "Hello PM4" complete.

What's not yet in the codebase but should still be straightforward
follow-ups (none gating "first fence works"):

  - MES v12_1 init + ADD_QUEUE for a non-KIQ GFX queue (Phase 1B
    chunk 18). The current path uses CP_RB0 directly; MES is the
    upstream "correct" path on RDNA4 but CP_RB0 also works for
    first-PM4.
  - SDMA v7_1 ring (Phase 1B chunk 19+). Enables async sysmem<->VRAM
    copies and the moving-BAR-window strategy for large VRAM access.
  - amdgpu UAPI proper (alloc_bo, submit_cs, fence, info) — Phase 2
    once Hello PM4 is verified.
This commit is contained in:
geramyloveless committed 2026-05-13 16:23:28 -07:00
1 parent f517262610
commit 8a04754bad
4 files changed
+341 -63

No files matched your search

+23
View File
@@ -32,6 +32,7 @@
#include "amdgpu/amdgpu_init.h"
#include "amdgpu/amdgpu_discovery.h"
#include "amdgpu/amdgpu_ih.h"
#include "amdgpu/amdgpu_cp.h"
#define MACAMDGPU_LOG(fmt, ...) \
os_log(OS_LOG_DEFAULT, "mac.amdgpu: " fmt, ##__VA_ARGS__)
@@ -54,6 +55,7 @@ enum {
kMacAMDGPUMethodSetIPBase = 11,
kMacAMDGPUMethodGetIPBase = 12,
kMacAMDGPUMethodLoadDiscoveryBin = 13,
kMacAMDGPUMethodSubmitTestPM4 = 14,
};
// Firmware type tags used by LoadFirmware. Pre-SOS components route
@@ -969,6 +971,27 @@ MacAMDGPUUserClient::ExternalMethod(uint64_t selector,
return kIOReturnSuccess;
}
case kMacAMDGPUMethodSubmitTestPM4: {
// scalarInput[0] = timeout_us
// scalarOutput[0] = fence value if observed, 0 on timeout
if (arguments->scalarInput == nullptr ||
arguments->scalarInputCount < 1 ||
arguments->scalarOutput == nullptr ||
arguments->scalarOutputCount < 1) {
return kIOReturnBadArgument;
}
if (!driver->ivars->pciOpen) return kIOReturnNotOpen;
uint64_t timeout_us = arguments->scalarInput[0];
if (timeout_us == 0) timeout_us = 1000000; // 1 s default
uint32_t fence = 0;
kern_return_t r = amdgpu::cp_submit_eop_test(
driver->ivars->bringup.device,
driver->ivars->bringup.cp,
timeout_us, &fence);
arguments->scalarOutput[0] = fence;
return r;
}
case kMacAMDGPUMethodLoadDiscoveryBin: {
// scalarInput[0] = size in bytes of the discovery binary
// currently sitting at the start of this client's DMABuffer.
+81 -14
View File
@@ -9,11 +9,16 @@
// See docs/port_plans/HELLO_PM4.md for the full critical path.
//
// Memory layout:
// KIQ ring buffer — 4 KB, **VRAM** (carved from VRAMBumpAllocator).
// The CP reads PM4 from here.
// KIQ MQD — 4 KB, **VRAM**. Memory Queue Descriptor;
// the CP reads it once at queue-create time
// to learn what's in the ring.
// KIQ ring buffer — 16 KB, **DART-mapped sysmem** (via GART
// once GMC is up). The CP fetches PM4 from
// here through GART translation. Sysmem
// (not VRAM) so we can write PM4 directly
// from the dext without needing an in-dext
// BAR2 mapping.
// KIQ MQD — 4 KB, **DART-mapped sysmem**. Memory
// Queue Descriptor; the CP reads it once at
// queue-create time to learn what's in the
// ring.
// Write-back page — 16 KB, **DART-mapped sysmem**. The CP
// writes back rptr/wptr and fence values
// here; the host reads from the same backing.
@@ -37,6 +42,28 @@ namespace amdgpu {
struct GMCContext; // forward — we ask its VRAM allocator for storage
// GC register offsets for the CP HQD registers we touch.
// Sourced from gc_12_0_0_offset.h. Used by cp_hqd_program / cp_enable.
namespace CPRegs {
constexpr uint32_t CP_RB0_BASE = 0x1DE0;
constexpr uint32_t CP_RB0_CNTL = 0x1DE1;
constexpr uint32_t CP_RB0_RPTR_ADDR = 0x1DE3;
constexpr uint32_t CP_RB0_RPTR_ADDR_HI = 0x1DE4;
constexpr uint32_t CP_RB_VMID = 0x1DF1;
constexpr uint32_t CP_RB0_WPTR = 0x1DF4;
constexpr uint32_t CP_RB_DOORBELL_RANGE_LOWER = 0x1DFA;
constexpr uint32_t CP_RB_DOORBELL_RANGE_UPPER = 0x1DFB;
constexpr uint32_t CP_RB0_BASE_HI = 0x1E51;
constexpr uint32_t CP_RB_DOORBELL_CONTROL = 0x1E8D;
constexpr uint32_t CP_ME_CNTL = 0x0803;
}
// CP_ME_CNTL bit positions (gfx_v12_0.c REG_SET_FIELDs imply these).
// ME_HALT lives at bit 21 in gfx12; setting 1 halts ME0, 0 runs it.
// PFP_HALT at bit 18, MEC_HALT at bit 22 (we don't touch those here).
constexpr uint32_t kCP_ME_CNTL__ME_HALT__SHIFT = 21;
constexpr uint32_t kCP_ME_CNTL__ME_HALT_MASK = (1u << 21);
// Default ring size — 4 KB matches Linux's KIQ ring default for
// GFX12 (one page; smaller than the upstream 16 KB only because the
// GPU's CP can address any power-of-two ≥ 4 KB).
@@ -53,15 +80,25 @@ constexpr uint32_t kCPWBOffsetFence = 0x080; // 8 B, qword-aligned
struct CPContext {
bool inited;
// KIQ ring (VRAM)
VRAMAllocation kiq_ring;
uint32_t kiq_ring_size_dwords;
uint32_t kiq_ring_ptr_mask; // ring_size_dwords - 1
// KIQ ring (sysmem, GART-mapped)
#ifdef __APPLE__
IOBufferMemoryDescriptor *ring_buf;
IODMACommand *ring_dma;
#endif
uint64_t ring_bus; // GPU-side bus address (== GART iova)
void *ring_cpu; // CPU-side write target
uint32_t ring_size_dwords;
uint32_t ring_ptr_mask; // ring_size_dwords - 1
// KIQ MQD (VRAM)
VRAMAllocation kiq_mqd;
// KIQ MQD (sysmem)
#ifdef __APPLE__
IOBufferMemoryDescriptor *mqd_buf;
IODMACommand *mqd_dma;
#endif
uint64_t mqd_bus;
void *mqd_cpu;
// Write-back page (DART-mapped sysmem)
// Write-back page (sysmem)
#ifdef __APPLE__
IOBufferMemoryDescriptor *wb_buf;
IODMACommand *wb_dma;
@@ -110,8 +147,38 @@ uint32_t cp_ring_write(CPContext &cp, const uint32_t *src,
// should kick the doorbell then poll *fence_cpu for that value.
uint32_t cp_emit_eop_fence(CPContext &cp);
// Top-level CPInit stage entry — alloc storage only for now.
// Actual ring activation lands in the next chunk.
// Program the GFX ring's HQD registers (CP_RB0_BASE/BASE_HI/CNTL,
// RPTR_ADDR/HI, WPTR, VMID, doorbell range). Mirrors
// gfx_v12_0_cp_gfx_resume's register sequence — minus the per-pipe
// GRBM_GFX_INDEX selection since we're targeting RB0 on the default
// pipe. Caller must have populated CPContext via cp_alloc_storage.
//
// Picks doorbell index from cp.doorbell_index (caller sets — for
// first PM4 we hardcode 0 inside cp_init_full).
kern_return_t cp_hqd_program(const DeviceContext &dev, CPContext &cp);
// Toggle CP_ME_CNTL.ME_HALT. After cp_enable(true) the CP can fetch
// + execute from the GFX ring; before, the ring is dormant.
kern_return_t cp_enable(const DeviceContext &dev, bool enable);
// Write the GFX ring's doorbell (BAR5 + doorbell_index<<3) with the
// current software wptr. The actual register-level write goes through
// IOPCIDevice::MemoryWrite32 on dev.bar5MemIndex.
kern_return_t cp_kick_doorbell(const DeviceContext &dev,
const CPContext &cp);
// End-to-end test: emit NOP+RELEASE_MEM, kick doorbell, poll fence.
// Returns kIOReturnSuccess if the fence value materialised at
// *fence_cpu within timeout_us microseconds. Designed for the
// SubmitTestPM4 selector — sanity-checks the entire submit path
// once HQD + CP enable have run.
kern_return_t cp_submit_eop_test(const DeviceContext &dev,
CPContext &cp,
uint64_t timeout_us,
uint32_t *outFence);
// Top-level CPInit stage entry — alloc storage + (if IP base is
// resolved) program HQD + enable CP. Idempotent.
kern_return_t cp_init_full(DeviceContext &dev,
GMCContext &gmc, CPContext &cp);
+218 -49
View File
@@ -69,35 +69,49 @@ cp_alloc_dma_block(DeviceContext &dev, uint64_t size,
return kIOReturnSuccess;
}
// ----- cp_alloc_storage: ring + MQD + write-back page -----
// ----- cp_alloc_storage: ring + MQD + write-back page (all sysmem) -----
kern_return_t
cp_alloc_storage(DeviceContext &dev, GMCContext &gmc, CPContext &cp)
{
(void)gmc;
if (cp.inited) return kIOReturnSuccess;
if (!gmc.vram_alloc.is_inited()) return kIOReturnNotReady;
// KIQ ring — power-of-two, 16 KB-aligned, in visible VRAM.
if (!gmc.vram_alloc.alloc(kCPRingDefaultBytes, kASPageSize,
&cp.kiq_ring)) {
CP_LOG("KIQ ring VRAM alloc failed (%llu free)",
gmc.vram_alloc.bytes_free());
return kIOReturnNoMemory;
}
cp.kiq_ring_size_dwords = kCPRingDefaultBytes / 4;
cp.kiq_ring_ptr_mask = cp.kiq_ring_size_dwords - 1;
// KIQ MQD — 4 KB in VRAM. The CP reads MQD once at queue-create
// and after that ignores it; alignment is just AS page rule.
if (!gmc.vram_alloc.alloc(kCPMQDBytes, kASPageSize, &cp.kiq_mqd)) {
CP_LOG("KIQ MQD VRAM alloc failed");
return kIOReturnNoMemory;
}
// Write-back page in sysmem.
void *cpu = nullptr;
kern_return_t r = cp_alloc_dma_block(dev, kCPWBPageBytes,
&cp.wb_buf, &cp.wb_dma,
&cp.wb_bus, &cpu);
kern_return_t r;
// KIQ ring — power-of-two, 16 KB-aligned, in DART sysmem. CP
// fetches PM4 through GART translation; sysmem is the easy path
// until we have a VRAM-resident allocator that's also CPU-writable
// (which on AS requires a BAR2 mapping inside the dext).
r = cp_alloc_dma_block(dev, kCPRingDefaultBytes,
&cp.ring_buf, &cp.ring_dma,
&cp.ring_bus, &cpu);
if (r != kIOReturnSuccess) {
CP_LOG("KIQ ring sysmem alloc failed: %#x", r);
return r;
}
memset(cpu, 0, kCPRingDefaultBytes);
cp.ring_cpu = cpu;
cp.ring_size_dwords = kCPRingDefaultBytes / 4;
cp.ring_ptr_mask = cp.ring_size_dwords - 1;
// KIQ MQD — 4 KB sysmem. CP reads it once at queue-create and
// doesn't touch it after.
r = cp_alloc_dma_block(dev, kCPMQDBytes,
&cp.mqd_buf, &cp.mqd_dma,
&cp.mqd_bus, &cpu);
if (r != kIOReturnSuccess) {
CP_LOG("KIQ MQD sysmem alloc failed: %#x", r);
return r;
}
memset(cpu, 0, kCPMQDBytes);
cp.mqd_cpu = cpu;
// Write-back page — sysmem, 16 KB. CP writes rptr/wptr/fence
// values here; host reads from the same backing.
r = cp_alloc_dma_block(dev, kCPWBPageBytes,
&cp.wb_buf, &cp.wb_dma,
&cp.wb_bus, &cpu);
if (r != kIOReturnSuccess) {
CP_LOG("WB page alloc failed: %#x", r);
return r;
@@ -108,19 +122,19 @@ cp_alloc_storage(DeviceContext &dev, GMCContext &gmc, CPContext &cp)
cp.rptr_cpu = reinterpret_cast<volatile uint32_t *>(wb + kCPWBOffsetRptr);
cp.wptr_cpu = reinterpret_cast<volatile uint32_t *>(wb + kCPWBOffsetWptr);
cp.fence_cpu = reinterpret_cast<volatile uint64_t *>(wb + kCPWBOffsetFence);
cp.rptr_gpu_addr = cp.wb_bus + kCPWBOffsetRptr;
cp.wptr_gpu_addr = cp.wb_bus + kCPWBOffsetWptr;
cp.rptr_gpu_addr = cp.wb_bus + kCPWBOffsetRptr;
cp.wptr_gpu_addr = cp.wb_bus + kCPWBOffsetWptr;
cp.fence_gpu_addr = cp.wb_bus + kCPWBOffsetFence;
cp.wptr = 0;
cp.fence_counter = 0;
cp.wptr = 0;
cp.fence_counter = 0;
cp.doorbell_index = 0; // assigned in next chunk
cp.inited = true;
cp.inited = true;
CP_LOG("storage ok: ring gpu=%#llx (%u dwords), mqd gpu=%#llx, "
CP_LOG("storage ok: ring bus=%#llx (%u dwords), mqd bus=%#llx, "
"wb bus=%#llx (rptr=%#llx wptr=%#llx fence=%#llx)",
cp.kiq_ring.gpu_va, cp.kiq_ring_size_dwords,
cp.kiq_mqd.gpu_va, cp.wb_bus,
cp.ring_bus, cp.ring_size_dwords,
cp.mqd_bus, cp.wb_bus,
cp.rptr_gpu_addr, cp.wptr_gpu_addr, cp.fence_gpu_addr);
return kIOReturnSuccess;
}
@@ -128,17 +142,21 @@ cp_alloc_storage(DeviceContext &dev, GMCContext &gmc, CPContext &cp)
void
cp_release_storage(CPContext &cp)
{
if (cp.wb_dma != nullptr) {
cp.wb_dma->CompleteDMA(kIODMACommandCompleteDMANoOptions);
cp.wb_dma->release(); cp.wb_dma = nullptr;
}
if (cp.wb_buf != nullptr) {
cp.wb_buf->release(); cp.wb_buf = nullptr;
}
auto teardown = [](IOBufferMemoryDescriptor *&b, IODMACommand *&d) {
if (d != nullptr) {
d->CompleteDMA(kIODMACommandCompleteDMANoOptions);
d->release(); d = nullptr;
}
if (b != nullptr) { b->release(); b = nullptr; }
};
teardown(cp.wb_buf, cp.wb_dma);
teardown(cp.mqd_buf, cp.mqd_dma);
teardown(cp.ring_buf, cp.ring_dma);
cp.wb_bus = 0; cp.wb_cpu = nullptr;
cp.mqd_bus = 0; cp.mqd_cpu = nullptr;
cp.ring_bus = 0; cp.ring_cpu = nullptr;
cp.rptr_cpu = nullptr; cp.wptr_cpu = nullptr; cp.fence_cpu = nullptr;
cp.inited = false;
// KIQ ring + MQD are bump-allocated; not freed.
}
// ----- cp_ring_write: stage PM4 dwords into the ring -----
@@ -158,19 +176,15 @@ uint32_t
cp_ring_write(CPContext &cp, const uint32_t *src, uint32_t dwords)
{
if (!cp.inited || src == nullptr || dwords == 0) return 0;
if (dwords > cp.kiq_ring_size_dwords / 2) {
if (dwords > cp.ring_size_dwords / 2) {
CP_LOG("ring_write: %u dwords exceeds half-ring %u",
dwords, cp.kiq_ring_size_dwords / 2);
dwords, cp.ring_size_dwords / 2);
return 0;
}
// Without a dext-side BAR2 mapping we can only advance the
// wptr counter — the actual ring memory writes happen from
// userspace once we expose BAR2 + a kick-doorbell selector.
// The wptr accounting still has to be correct so userspace
// and dext agree on where the next packet goes.
auto *ring = static_cast<uint32_t *>(cp.ring_cpu);
for (uint32_t i = 0; i < dwords; i++) {
cp.wptr = (cp.wptr + 1) & cp.kiq_ring_ptr_mask;
(void)src[i]; // placeholder for the actual write
ring[cp.wptr] = src[i];
cp.wptr = (cp.wptr + 1) & cp.ring_ptr_mask;
}
return dwords;
}
@@ -206,13 +220,168 @@ cp_emit_eop_fence(CPContext &cp)
return fence;
}
// ----- cp_hqd_program: write CP_RB0_* registers -----
//
// Mirrors gfx_v12_0_cp_gfx_resume (drivers/gpu/drm/amd/amdgpu/
// gfx_v12_0.c). On a fresh device the HQD registers are at reset
// defaults; this routine programs them to match our ring buffer
// location, size, and doorbell mapping so subsequent doorbell
// rings cause the CP to fetch + execute our PM4.
//
// Skips per-pipe GRBM_GFX_INDEX selection — we use the default
// pipe (RB0). Caller is responsible for taking the SRBM mutex if
// multi-context safety is required (Phase 2 concern).
kern_return_t
cp_hqd_program(const DeviceContext &dev, CPContext &cp)
{
if (!cp.inited) return kIOReturnNotReady;
if (!dev.ip.isResolved(IPBlock::GC)) return kIOReturnNotReady;
auto reg = [&](uint32_t off) {
return SOC15_REG_OFFSET(dev, IPBlock::GC, off);
};
// Ring physical base — register holds bits [39:8] (256 B granularity).
WREG32(dev, reg(CPRegs::CP_RB0_BASE),
static_cast<uint32_t>(cp.ring_bus >> 8));
WREG32(dev, reg(CPRegs::CP_RB0_BASE_HI),
static_cast<uint32_t>(cp.ring_bus >> 40));
// CP_RB0_CNTL: RB_BUFSZ = log2(ring_dwords) - 1 (per upstream
// order_base_2(ring_size_bytes/8) where ring_size is bytes).
// For 16 KB ring = 4096 dwords, BUFSZ = log2(4096/2) = 11.
// (Upstream encodes "log2(elements) - 1" where element = 8 bytes.)
uint32_t buf_log2 = 0;
{
uint32_t v = cp.ring_size_dwords / 2; // upstream divides by 2
while (v >>= 1) buf_log2++;
}
uint32_t cntl = (buf_log2 & 0x3F) | ((8u & 0x3F) << 8); // BUFSZ + BLKSZ=8
WREG32(dev, reg(CPRegs::CP_RB0_CNTL), cntl);
// VMID 0 — all kernel-driver submits use system VMID for now.
WREG32(dev, reg(CPRegs::CP_RB_VMID), 0);
// Reset wptr to 0 (CP echoes; we also update software state).
WREG32(dev, reg(CPRegs::CP_RB0_WPTR), 0);
cp.wptr = 0;
*cp.wptr_cpu = 0;
*cp.rptr_cpu = 0;
*cp.fence_cpu = 0;
// RPTR write-back address — GPU writes its current read pointer
// into our WB page at this offset so the CPU can poll it without
// hitting MMIO.
WREG32(dev, reg(CPRegs::CP_RB0_RPTR_ADDR),
static_cast<uint32_t>(cp.rptr_gpu_addr & 0xFFFFFFFCu));
WREG32(dev, reg(CPRegs::CP_RB0_RPTR_ADDR_HI),
static_cast<uint32_t>(cp.rptr_gpu_addr >> 32));
// Doorbell control — index << 2 per upstream encoding, plus
// doorbell-enable bit (we set bit 30 to enable the doorbell).
constexpr uint32_t kDoorbellEnable = (1u << 30);
WREG32(dev, reg(CPRegs::CP_RB_DOORBELL_CONTROL),
kDoorbellEnable | ((cp.doorbell_index & 0xFFFFFF) << 2));
WREG32(dev, reg(CPRegs::CP_RB_DOORBELL_RANGE_LOWER),
(cp.doorbell_index & 0xFFFFFF) << 2);
WREG32(dev, reg(CPRegs::CP_RB_DOORBELL_RANGE_UPPER),
((cp.doorbell_index + 1) & 0xFFFFFF) << 2);
CP_LOG("HQD programmed: ring_bus=%#llx bufsz=%u doorbell=%u",
cp.ring_bus, buf_log2, cp.doorbell_index);
return kIOReturnSuccess;
}
// ----- cp_enable: toggle CP_ME_CNTL.ME_HALT -----
kern_return_t
cp_enable(const DeviceContext &dev, bool enable)
{
if (!dev.ip.isResolved(IPBlock::GC)) return kIOReturnNotReady;
const uint32_t r = SOC15_REG_OFFSET(dev, IPBlock::GC, CPRegs::CP_ME_CNTL);
uint32_t v = RREG32(dev, r);
if (enable) v &= ~kCP_ME_CNTL__ME_HALT_MASK; // halt=0 → running
else v |= kCP_ME_CNTL__ME_HALT_MASK;
WREG32(dev, r, v);
CP_LOG("CP ME_HALT %s (CP_ME_CNTL=%#010x)",
enable ? "cleared (CP running)" : "set (CP halted)", v);
return kIOReturnSuccess;
}
// ----- cp_kick_doorbell: write wptr to BAR5 doorbell slot -----
//
// On GFX12 the doorbell stride is 8 bytes (one u64 per slot). We
// write the low 32 bits — the dext bypasses the userspace
// IOConnectMapMemory64 BAR5 mapping and pokes the doorbell directly
// through PCIDriverKit's MemoryWrite32 on bar5MemIndex.
kern_return_t
cp_kick_doorbell(const DeviceContext &dev, const CPContext &cp)
{
if (!cp.inited) return kIOReturnNotReady;
if (dev.pci == nullptr) return kIOReturnNotAttached;
*cp.wptr_cpu = cp.wptr;
const uint64_t off = static_cast<uint64_t>(cp.doorbell_index) * 8;
dev.pci->MemoryWrite32(dev.bar5MemIndex, off, cp.wptr);
return kIOReturnSuccess;
}
// ----- cp_submit_eop_test: end-to-end submit + fence wait -----
kern_return_t
cp_submit_eop_test(const DeviceContext &dev, CPContext &cp,
uint64_t timeout_us, uint32_t *outFence)
{
if (outFence) *outFence = 0;
if (!cp.inited) return kIOReturnNotReady;
uint32_t fence = cp_emit_eop_fence(cp);
if (fence == 0) return kIOReturnInternalError;
kern_return_t r = cp_kick_doorbell(dev, cp);
if (r != kIOReturnSuccess) return r;
const uint64_t kStep = 1000;
uint64_t elapsed = 0;
while (elapsed < timeout_us) {
uint64_t observed = *cp.fence_cpu;
// Linux uses a 32-bit fence in the low half on simple paths.
if ((observed & 0xFFFFFFFFu) == fence) {
if (outFence) *outFence = fence;
CP_LOG("EOP fence %u observed after %llu µs", fence, elapsed);
return kIOReturnSuccess;
}
IOSleep(1);
elapsed += 1000;
(void)kStep;
}
CP_LOG("EOP fence %u timeout (observed=%llu)", fence, *cp.fence_cpu);
return kIOReturnTimeout;
}
// ----- cp_init_full: BringupStage::CPInit entry -----
kern_return_t
cp_init_full(DeviceContext &dev, GMCContext &gmc, CPContext &cp)
{
kern_return_t r = cp_alloc_storage(dev, gmc, cp);
if (r != kIOReturnSuccess) return r;
CP_LOG("CP storage staged; HQD/doorbell programming pending next chunk");
// Pin doorbell index 0 for the GFX ring on first PM4 — the
// simplest possible assignment. Real driver would allocate from
// a doorbell ID pool.
cp.doorbell_index = 0;
// Skip MMIO programming if IP base isn't resolved (e.g. user
// hasn't loaded the discovery binary yet). Storage stays staged.
if (!dev.ip.isResolved(IPBlock::GC)) {
CP_LOG("CP storage staged; GC IP base unresolved — HQD/CP enable deferred");
return kIOReturnSuccess;
}
// Halt CP while we reprogram registers (safety, matches upstream).
cp_enable(dev, false);
r = cp_hqd_program(dev, cp);
if (r != kIOReturnSuccess) return r;
cp_enable(dev, true);
CP_LOG("CP ready: GFX ring active at doorbell %u", cp.doorbell_index);
return kIOReturnSuccess;
}
+19
View File
@@ -35,6 +35,7 @@ private let kLoadFirmware: UInt32 = 10
private let kSetIPBase: UInt32 = 11
private let kGetIPBase: UInt32 = 12
private let kLoadDiscoveryBin: UInt32 = 13
private let kSubmitTestPM4: UInt32 = 14
private let kMemBAR0: UInt32 = 0
private let kMemBAR2: UInt32 = 2
@@ -354,6 +355,19 @@ func resetDevice(_ conn: io_connect_t) {
print("reset: issued")
}
func submitTestPM4(_ conn: io_connect_t, timeoutUs: UInt64 = 1_000_000) {
print("pm4 test: emitting NOP + RELEASE_MEM (timeout \(timeoutUs) µs)")
let (kr, out) = callScalar(conn, kSubmitTestPM4,
input: [timeoutUs], outputCount: 1)
let fence = out.first ?? 0
if kr == KERN_SUCCESS && fence != 0 {
print("pm4 test: EOP fence \(fence) observed")
} else {
warn("pm4 test: kr=\(String(format: "%#x", kr)) fence=\(fence) "
+ "(needs IP bases resolved + CP HQD programmed; check os_log)")
}
}
// --- Main ---------------------------------------------------------------
let args = CommandLine.arguments
@@ -367,6 +381,7 @@ var discoveryPath: String? = nil
if let i = args.firstIndex(of: "--load-discovery"), i + 1 < args.count {
discoveryPath = args[i + 1]
}
let wantSubmitTest = args.contains("--submit-test")
print("opening MacAMDGPU service…")
let conn = openService()
@@ -403,6 +418,10 @@ if wantInit || sosPath != nil {
}
}
if wantSubmitTest {
submitTestPM4(conn)
}
if wantReset {
resetDevice(conn)
}