18 Commits
Author SHA1 Message Date
geramyloveless 3fe89e1ace Scale GPU buffers and integrate validated HSA signals with LSE
Grow and reclaim BO metadata in64-entry pages, raise client capacity to4096 handles, and prevent VRAM free-range metadata exhaustion. Add GPU activity history, bounded sensor sampling and clock/counter reporting.

Select the qualified GPU-owned signal mailbox by default while gating native mixed atomics on original PCIe evidence. Include native HRX/LSE adapters, guarded compute tests, reproducible signing and local build/server guides linked to Lemon Seed Engine.

Hardware validation covers1024 live buffers with fragmented reuse, pooled HRX allocations and2GiB boundaries, shared signal lifecycle, Q6 projection and680 exact convolution outputs. Full-model token generation remains blocked on the missing Loom repeat template.
2026-09-23 17:52:41 -07:00
geramyloveless 0844f74f65 Select compute VMID through GFX IBs and expose cached SMU metrics
Submit each compute checkpoint through an explicitly addressed VMID 0 IB after build 175 faulted on shader instruction fetch under VMID 3. Retain distinct verified IB storage until completion or reset.

Retain SMU table staging and add bounded owner sampling with a cached observer ABI for amdgpu_mtop. Invalidate samples during teardown, reject stale data, and keep periodic collection disabled pending hardware validation.

Bump host and driver to 176, record hardware evidence, and pin the HSA interface requirements to the HRX revision used by LSE. All 24 regression suites, the Debug build and strict signatures pass.
2026-09-22 23:29:32 -07:00
geramyloveless 682ca7c553 Bring up RDNA4 command queues and verified host-memory transfers
Correct firmware acknowledgements, GPU address translation, MES queue setup, SDMA and CP submission, and driver session teardown. Add runtime identity checks, host diagnostics, checked GART mapping lifetime, and reusable aligned aperture reservations.

Record build 172 hardware acceptance and build 173 allocator validation. Add 19 regression suites covering packet layouts, firmware sequencing, command-ring reuse, mapping failure retention, and lifecycle behavior.
2026-09-22 22:28:00 -07:00
geramyloveless 3bdeed2de9 v0.1.48: SDMA engine actually running — NBIF v6.3.1 + per-IP-version regs + MMIO WPTR mode
First version where the SDMA engine actually processes ring submissions
on this hardware. v0.1.0 through v0.1.46 had multiple cascading bugs;
this commit consolidates the chain of fixes uncovered by a line-by-line
re-audit against upstream amdgpu.

NBIO/NBIF
- Replaced the wrong nbio_v7_11 funcs with a full nbif_v6_3_1 port.
  Our chip reports NBIF v6.3.1 in discovery (hw_id=108), not NBIO 7.11.
  Different doorbell-routing model: S2A entries with explicit AWID/
  AWADDR/RANGE_OFFSET/RANGE_SIZE per port, direct MMIO at BASE_IDX 2
  (no PCIE_PORT indirect needed for the entry table). Ported:
    nbif_v6_3_1_remap_hdp_registers      (BX0 0x012d/0x012e @ BASE_IDX 2)
    nbif_v6_3_1_init_registers           (RCC_DEV0_EPF2_STRAP2)
    nbif_v6_3_1_ih_control               (BX0 INTERRUPT_CNTL)
    nbif_v6_3_1_enable_doorbell_aperture
    nbif_v6_3_1_enable_doorbell_selfring_aperture  (BX_PF0)
    nbif_v6_3_1_sdma_doorbell_range      (S2A ENTRY_2, AWID=0xe AWADDR=0x3)
    nbif_v6_3_1_ih_doorbell_range        (S2A ENTRY_1)
    nbif_v6_3_1_gc_doorbell_init         (ENTRY_0=0x30000007, ENTRY_3=0x3000000d)
- PCIE_PORT_RREG32/WREG32 helpers via BIF_BX_PF1_RSMU_INDEX/DATA
  (NBIO BASE_IDX 1), distinct from existing SMN path via PCIE_INDEX2.
- BAR2 PCIe phys addr captured in ensure_open, fed into SELFRING base.
- doorbell_init() was defined but never invoked — fix.
- Ordering: SELFRING enabled last (matches soc24_common_late_init).
- IP-version-aware base/_nbif_4_10 register dispatch.

SDMA register correctness
- All QUEUE0_* and UTCL1_* offsets were pulled from gc_12_1_0_offset.h
  (a different chip, GFX 12.1) and were systematically 0x180 higher
  than the correct gc_12_0_0_offset.h values for our R9700 (GFX 12.0.1).
  Every ring-program write — RB_BASE, RB_CNTL, RB_WPTR, DOORBELL,
  DOORBELL_OFFSET, WPTR_POLL_ADDR — has been hitting wrong GC registers
  since v0.1.0. Corrected.
- sdma_reg_offset now uses GC BASE_IDX 1 for the hyp-dec range
  [0x5880..0x589a] per upstream sdma_v7_0_get_reg_offset (line 125).
  MCU_CNTL (0x588e) was being read/written at GC[0]+0x588e — a random
  unrelated register — for the entire driver lifetime. HALT/RESET
  writes had no effect; the symptomatic MCU_CNTL=0x92929292 was the
  garbage at the wrong address. Corrected.
- RB_CNTL.MCU_WPTR_POLL_ENABLE = 1 (was 0). Without this the MCU
  doesn't react to WPTR updates even with a valid doorbell signal.
- Removed the defensive HALT=1 at SDMA init step 1 — bare-metal
  upstream path doesn't halt; halting tears down PSP-autoloaded MCU
  firmware state.
- STATUS_REG bit positions corrected in both dext (sdma_log_status)
  and Swift (testLiveStatus) decoders per gc_12_0_0_sh_mask.h:142-161.

Per-IP-version register tables
- IPBaseTable now stores IPVersion[block], populated by discovery.
- SDMARegs is no longer a namespace — it's a SDMARegOffsets struct with
  per-chip tables: kSDMARegOffsets_gc_12_0_0 (R9700 / GFX 12.0.x) and
  kSDMARegOffsets_gc_12_1_0 (gfx1250 / GFX 12.1.x). sdma_pick_reg_table
  selects at runtime. All call sites converted to sdma_regs(dev).FIELD.
  nbif_is_ip_7_11_4(dev) now reads the actual discovered NBIO version
  for the _nbif_4_10 register-variant dispatch.

SDMA kick — MMIO WPTR mode (AS+TB5 deviation)
- BAR2 doorbell aperture writes via IOPCIDevice::MemoryWrite64 do not
  reach the SDMA MCU on Apple Silicon + Thunderbolt 5. Verified across
  v0.1.30-v0.1.46 with every NBIF routing variant, SELFRING base from
  PCI config, WC-flush readback, and engine-side DOORBELL_OFFSET combo.
- sdma_kick_doorbell now does the full four-step kick:
    1. sysmem WPTR shadow write (upstream atomic64_set)
    2. HDP flush
    3. BAR2 doorbell write (upstream WDOORBELL64 — inert on AS+TB5)
    4. MMIO RB_WPTR write (upstream use_doorbell=false branch — the
       functional path on this platform)
- v0.1.47 verified: SDMA Copy returns status=0 with RPTR=WPTR=0x40
  (engine consumed 16 dwords and wrote the fence).

GART soft-gate (defensive)
- GARTContext.reads_supported flag (defaults false) — GART page table
  is fully programmed but GPU-initiated reads through DART return zero
  on AS+TB5. gart_init populates GARTContext from GMC's just-enabled
  aperture and sets the flag with logged platform reasoning.
- BOAlloc(domain=kBODomainGTT) returns kIOReturnUnsupported when the
  flag is false, so clients fail fast instead of allocating a BO that
  silently misbehaves on every engine read. When Apple exposes a
  working sysmem-mapping primitive, flipping the flag in gart_init
  lights up the GTT path automatically with no other changes.

Version bumps 0.1.33 through 0.1.48 collapsed into this commit.
2026-05-22 15:35:28 -07:00
geramyloveless b04bf9777a v0.1.22: full GPU bringup — all 15 stages pass on R9700
Five-version diagnostic chain landing on a state where every IP block
initializes on hardware (IPDiscovery → SDMAInit). The decisive fixes:

v0.1.21 — port minimal smu_smc_hw_setup
  PMFW must enable DPM before the IMU autoload state machine fires.
  GetDriverIfVersion + SetDriverDramAddrHigh/Low (64KB VRAM slot via
  fwBuf bump) + RunDcBtc + EnableAllSmuFeatures. PMFW returns
  UnknownCmd for SetAllowedFeaturesMaskLow/High on this build, so the
  mask-set is non-fatal — EnableAllSmuFeatures with the IFWI-baked
  default mask is what trips the gate. running_features = 0x488f19e_
  0x38fffcfb (DPM_GFXCLK + DPM_FCLK + DPM_UCLK + …) and BOOTLOAD_STATUS
  transitions 0 → 0x8000003f within < 1 ms.

v0.1.22 — pin VRAM bump allocator to LOW BAR0-mapped region
  BAR0 on R9700 + Apple Silicon + TB5 maps the BOTTOM 256 MB of VRAM
  (FB_LOCATION_BASE = vram_start), not the top like most desktops. The
  bump allocator was initialised with visible_base = vram_start +
  (real_vram_size - visible_vram_size) which produced gpu_va near
  vram_start + 32 GB — far outside BAR0. CSB write through
  bar0_memcpy_to_vram page-faulted and killed the dext immediately
  after autoload printed success. Fix: visible_base = vram_start, with
  the first 24 MB reserved for PSP's hardcoded slots.

Also in this commit (work since v0.0.63):
  - PSP TA bin parser + psp_asd_initialize (LOAD_ASD cmd_id 0x4) wired
    between AUTOLOAD_RLC and psp_rl_load (v0.1.19)
  - PSP ring KM=2, rb_frame 5-field-only, HDP flush+readback,
    fw_pri-memset-before-memcpy (v0.1.14–0.1.18)
  - Per-IP firmware extractors (RLC v2.x, MES uni_mes, GFX RS64,
    SDMA v7), bump-allocated fwBuf slots per LOAD_IP_FW frame
  - GMC + MMHUB + GFXHUB gart_enable port (mmhub_v4_1_0 / gfxhub_v12_0),
    GART PT in VRAM at vram_start + 0x700000, CONTEXT0 enable
  - RLC autoload wait + CSB content fill + SRM enable + CSIB program
  - CP / MES / SDMA / GFX stage handlers (microcode signed off, no
    live PM4 yet)

README updated to reflect v0.1.22 state. Deleted stale WORKLIST.md,
ROADMAP.md, and docs/PORTING_NOTES.md / docs/*PLAN*.md per session
cleanup; docs/ is gitignored going forward (audit-2026-05-22/ lives
there locally with the synthesis + per-agent reports + v0.1.19/0.1.20
plans).

Next frontier: first PM4 packet on a live ring (KIQ NOP smoke test) or
SDMA VRAM→VRAM copy. Bringup itself is solved.
2026-05-21 20:15:36 -07:00
geramyloveless f33c4c90fa Merge branch 'worktree-agent-a5d04a4b9de1fabbd' 2026-05-15 16:15:32 -07:00
geramyloveless bf723fba5c Agent D: bringup reorder + gmc_v12_0.cpp rewrite + IFWI poll fix 2026-05-15 16:04:10 -07:00
geramyloveless 6dbef31030 Agent C: complete GFX/CP/MES/RLC/IMU bringup (audit #7) 2026-05-15 16:04:09 -07:00
geramyloveless c8d224e93f PSP ring: KM=2 fix, GART+NBIO HDP remap, BASE_IDX support → SMU+GMC online
The headline fix: PSP_RING_TYPE__KM was 1 (= PSP_RING_TYPE__UM, the
SR-IOV / RBI ring), upstream is 2 (= GPCOM kernel ring). With KM=1
psp_v14_0_ring_create wrote `1<<16 = 0x10000 = INIT_RBI_RING` to
C2PMSG_64, PSP responded OK but never honored C2PMSG_67 wptr
doorbells — every ring submit silently dropped. KM=2 sends
`0x20000 = INIT_GPCOM_RING` and PSP starts processing frames.

Other audit-driven fixes that compounded the bring-up issues:

- MMHUB register offsets corrected to mmhub_4_1_0_offset.h:
  FB_OFFSET 0x04c7, AGP_TOP/BOT/BASE 0x0556/0x0557/0x0558,
  SYSTEM_APERTURE_DEFAULT_LSB/MSB 0x04c8/0x04c9, L2_CNTL4 0x04fd,
  L2_CNTL5 0x0503, INVALIDATE_ENG0_ADDR_RANGE 0x05ab/0x05ac.
- PTE format: add AMDGPU_PTE_IS_PTE (bit 63) to PTEFlags::SYSMEM_RW
  — mandatory on GFX12 with PAGE_TABLE_DEPTH=0 or every PTE faults.
- LoadIPKeyMgrDrv corrected to 0xF0000 (was 0x110000, a bogus value
  PSP rejected mid-bootloader).
- NBIO `remap_hdp_registers` programmed during IPDiscovery
  (BAR5 byte 0x44000 was a no-op without this).
- SOC15 multi-BASE_IDX support: IPBaseTable now stores up to 5 bases
  per IP, discovery reads them all, SOC15_REG_OFFSET_BIDX(...) added.
  SMU mailbox now uses MP1 BASE_IDX 1 (was hitting wrong reg).
- psp_query_fw_reservation: sends GFX_CMD_ID_FB_FW_RESERV_ADDR + EXT
  after ring_create (matches upstream for SOS fw_version ≥ 0x3a0e14).
- psp_setup_tmr: skip on psp_v14_0_x (boot_time_tmr by SOS) per
  upstream psp_skip_tmr.
- LoadFirmware (post-SOS): parse common_firmware_header and pass
  (gart_mc_addr + ucode_array_offset_bytes, ucode_size_bytes) to
  psp_load_ip_fw instead of the whole .bin file. fw_type table:
  add SDMA_UCODE_TH0 (71), CP_MES (33), CP_MES_DATA (34), RS64
  PFP/ME/MEC + P0..P3 stack variants (87-97).
- psp_load_ip_fw: drop spurious 4 KB alignment check (upstream
  doesn't enforce it; ucode_array_offset_bytes is dword-aligned).
- rb_frame: leave cmd_buf_size at 0 after memset (was 0x400, which
  PSP treated as a corrupt frame).
- HDP flush: write + readback (mirrors amdgpu_hdp_generic_flush +
  nbio.get_memsize, the latter being the PCIe-write serialization
  barrier we were missing).
- Host initializeGPU(): reorder to LoadFirmware(SMU) before SMUInit
  stage so the smu_test_message has a live PMFW to talk to.

Untrack docs/ via .gitignore — internal porting notes / audit
reports are not for the public tree; keep them local-only.

Verified on a real R9700 over Thunderbolt 5: bringup now reaches
GMCInit (8 stages green). Next blocker is multi-component firmware
parsing for SDMA v3 / RLC sub-bins / uni_mes (PSP returns
TEE_ERROR_BAD_PARAMETERS because our simple "skip 32-byte common
header" doesn't fit those layouts).
2026-05-15 15:22:24 -07:00
geramyloveless 8c4664994f Phase 1B chunk 22: MES v12_1 storage + enable (items 251-252)
First MES port chunk — storage allocation and the CP_MES_CNTL
state machine for the uni_mes path.

amdgpu_mes.h / mes_v12_1.cpp:
  • MESInstance per pipe with EOP (2K), MQD (4K), ring (64K),
    cmd buffer (16K) — all DART-mapped sysmem, 16K-aligned.
    Matches upstream sizes (MES_EOP_SIZE=2048).
  • mes_alloc_storage(dev, inst): port of
    mes_v12_0_allocate_eop_buf + mqd_sw_init + ring_init storage
    chunks. Idempotent.
  • mes_enable(dev, mes, enable): port of mes_v12_0_enable for
    uni_mes pipe 0. enable=true sequence:
      1) GRBM select me=3 pipe=0 queue=0 vmid=0
      2) pulse CP_MES_CNTL.MES_PIPE0_RESET
      3) write CP_MES_PRGRM_CNTR_START{,_HI} with
         uc_start_addr >> 2
      4) write CP_MES_CNTL with MES_PIPE0_ACTIVE=1
      5) GRBM deselect (me=0 pipe=0 queue=0 vmid=0)
    enable=false halts + resets + invalidates icache.
  • mes_set_uc_start_addr(): called by LoadFirmware after a
    successful psp_load_ip_fw for the MES blob. Returns NotReady
    from mes_enable if the start_addr is still 0.
  • grbm_select() helper inline in the header — same shape as
    upstream soc21_grbm_select.

MacAMDGPU.cpp:
  • LoadFirmware now parses the mes_firmware_header_v1_0 layout
    when fwType ∈ { RS64_MES (76), RS64_KIQ (78) }: the
    common_firmware_header is 10 dwords, then the MES-specific
    fields land mes_uc_start_addr_lo at dword 16, _hi at 17.
    The 64-bit composed value is handed to mes_set_uc_start_addr
    on the matching pipe (Sched vs KIQ).

Bringup:
  • BringupContext gains MESContext mes.
  • MESInit stage now calls mes_init_full instead of returning
    Unsupported. Storage allocation is unconditional; the
    enable step only runs after sched_ucode_loaded becomes true.

Deferred to next MES chunks (still [ ] in WORKLIST):
  • mes_v12_1_queue_init (HQD program for the SCHED ring,
    253) — needs the v12_compute_mqd struct + field defs.
  • mes_v12_1_set_hw_resources (254) — API msg marshalling.
  • mes_v12_1_submit_pkt_and_poll_completion (255) and the
    rest of the API surface (256–258).

Source citations:
  drivers/gpu/drm/amd/amdgpu/mes_v12_0.c
    (mes_v12_0_allocate_eop_buf, mes_v12_0_enable,
     mes_v12_0_set_ucode_start_addr)
  drivers/gpu/drm/amd/amdgpu/amdgpu_mes.c
    (amdgpu_mes_init_microcode — fw header field offsets)
  drivers/gpu/drm/amd/amdgpu/amdgpu_ucode.h
    (mes_firmware_header_v1_0 layout)

Build clean; UNTESTED on real hardware.
2026-05-13 22:24:09 -07:00
geramyloveless 76472aafd0 Phase 1B chunk 20: SDMA v7_0 ring bringup (items 270-273)
Ports the SDMA0/SDMA1 queue resume path. Each instance allocates
its own 16 KB ring + 16 KB write-back page in DART-mapped sysmem
(16 KB-aligned for the AS DART page granularity), then on
SDMAInit:

  • sdma_engine_halt + sdma_gfx_stop_instance  — defensive
  • sdma_gfx_resume_instance — port of upstream
    sdma_v7_0_gfx_resume_instance(restore=false):
      - QUEUE0 RB_CNTL: RB_SIZE=log2(dwords), RB_PRIV=1,
        RPTR_WRITEBACK_ENABLE=1, MCU_WPTR_POLL_ENABLE=1,
        WPTR_POLL_ENABLE=0
      - RB_BASE = ring_bus>>8, BASE_HI = ring_bus>>40
      - RPTR_ADDR_LO/HI = wb_bus
      - DOORBELL.ENABLE=1, DOORBELL_OFFSET.OFFSET=index
      - MINOR_PTR_UPDATE handshake around WPTR write
      - WATCHDOG_CNTL.QUEUE_HANG_COUNT=1, UTCL1_CNTL
        RESP_MODE=3 + REDO_DELAY=9, UTCL1_PAGE policy bits
      - MCU_CNTL.HALT=0 to unhalt the engine
      - RB_ENABLE=1 then IB_ENABLE=1
  • sdma_ring_test — FENCE-only smoke packet that writes a
    known sentinel to the WB page at +0x80 then polls.

Reg addressing follows upstream sdma_v7_0_get_reg_offset:
non-hyp-dec range uses GC base + (SDMA1_REG_OFFSET=0x600 *
instance); hyp-dec range (0x5880..0x589a, contains MCU_CNTL
at 0x588e) adds SDMA1_HYP_DEC_REG_OFFSET=0x20 per instance.

LoadFirmware now flips bringup.sdma.microcode_loaded after a
successful psp_load_ip_fw for SDMA0 (gfxFwType 9) or SDMA1
(gfxFwType 10), so SDMAInit can detect when it's safe to run
gfx_resume vs. just allocate storage and wait.

BringupContext gains an SDMAContext and the SDMAInit stage now
calls sdma_init_full instead of returning Unsupported.

Source citations:
  drivers/gpu/drm/amd/amdgpu/sdma_v7_0.c (resume_instance,
    enable, gfx_stop, get_reg_offset)
  drivers/gpu/drm/amd/include/asic_reg/gc/gc_12_0_0_offset.h
  drivers/gpu/drm/amd/include/asic_reg/gc/gc_12_0_0_sh_mask.h

Build clean; UNTESTED on real hardware.
2026-05-13 22:05:22 -07:00
geramyloveless 34470dd89c Phase 1B chunk 18: on-die IP discovery — the way amdgpu does it
Replaces the LoadDiscoveryBin-as-primary-path shortcut with proper
runtime IP discovery, exactly mirroring drivers/gpu/drm/amd/amdgpu/
amdgpu_discovery.c:amdgpu_discovery_get_tmr_info.

Bootstrap registers (absolute BAR0 dword offsets — no IP base
needed; this is the chicken-and-egg solver):
  mmRCC_CONFIG_MEMSIZE = 0x0DE3  (VRAM size in MB)
  mmDRIVER_SCRATCH_0   = 0x0094  (TMR offset LO — PSP-written)
  mmDRIVER_SCRATCH_1   = 0x0095  (TMR offset HI)
  mmDRIVER_SCRATCH_2   = 0x0096  (TMR size, 0 if no sysmem override)

These legacy "mm" aliases resolve to the same physical registers
on every gen including RDNA4 — amdgpu uses the same constants
unconditionally for discovery bootstrap. NBIO's SOC15-routed
register (regRCC_DEV0_EPF0_0_RCC_CONFIG_MEMSIZE = 0x00C3) needs
the NBIO IP base which we don't have yet at this stage, so the
legacy path is the right one.

amdgpu_regs.h adds two helpers:
  RREG32_abs(dev, reg)            — BAR0 read at absolute offset
                                    (bypasses SOC15 entirely)
  RBAR2_32(dev, byte_offset)      — 32-bit MMIO read from BAR2 at
                                    a given byte offset (used to
                                    read the discovery binary out
                                    of VRAM)

amdgpu_discovery.{h,cpp} gains discover_ips_on_die(dev, *result):

  Step 1: read mmRCC_CONFIG_MEMSIZE absolute → VRAM size in MB.
  Step 2: read mmDRIVER_SCRATCH_2. If non-zero, PSP placed the
          discovery binary in sysmem at (SCRATCH_1|<<32 | SCRATCH_0)
          with size SCRATCH_2. That path requires mapping a
          host-physical sysmem range from the dext, which AS
          PCIDriverKit doesn't expose; log the address + bail
          with kIOReturnUnsupported so the caller can fall back
          to LoadDiscoveryBin.
  Step 3: VRAM-resident TMR. Compute
          offset = (vram_mb << 20) - kDiscoveryTMROffset (1 MB).
          If that offset is outside the BAR2 visible window
          (likely on small-BAR setups), retry at
          (visible_size - 1 MB) — many discrete AMD configurations
          on small-BAR systems place the TMR at the top of the
          visible aperture instead.
  Step 4: read kDiscoveryTMRSize (64 KB) bytes from BAR2 + offset
          via 32-bit MMIO. Sanity-check the binary signature
          before parsing.
  Step 5: call discovery_parse() — same parser we already had,
          which populates dev.ip with the per-IP base addresses.

BringupStage::IPDiscovery now actually does discovery:
  - Calls discover_ips_on_die first.
  - On success, runs the existing bringup_ip_discovery() (which
    pins R9700 version constants).
  - On failure, checks whether IP bases are already set (i.e.
    the caller used LoadDiscoveryBin or SetIPBase as the escape
    hatch) and treats that as success. Otherwise propagates the
    error.

The LoadDiscoveryBin and SetIPBase selectors stay as documented
escape hatches for the "PSP placed TMR in sysmem" path and for
debugging — but the production path is now on-die discovery just
like amdgpu does it.

Build still clean: ** BUILD SUCCEEDED **.

Hello PM4 prerequisites on real hardware now reduce to:
  1. Load + activate dext (entitlement granted)
  2. InitDevice(IPDiscovery)   — runs on-die discovery automatically
  3. LoadFirmware(SOS); InitDevice(PSPLoadSOS)
  4. InitDevice(PSPRingCreate); InitDevice(TMRSetup)
  5. LoadFirmware(PMFW); InitDevice(SMUInit)
  6. LoadFirmware for RLC_G, CP_PFP/ME/MEC, MES via PSP LOAD_IP_FW
  7. InitDevice(GMCInit); InitDevice(IHInit);
     InitDevice(RLCInit); InitDevice(CPInit)
  8. SubmitTestPM4 → fence value returned
2026-05-13 16:30:59 -07:00
geramyloveless f517262610 Phase 1B chunk 16: CP infrastructure + PM4 packet builders + dispatcher repair
(1) CP/KIQ storage layer landed:

  amdgpu_pm4.h    — hand-rolled PM4 packet builders.
                    pm4_header(op, count), pm4_nop(), and the
                    field bits for WRITE_DATA + RELEASE_MEM:
                      kPM4OpNop / WriteData / ReleaseMem
                      kPM4WriteDataDstSelMemory, _EngineME
                      kPM4RMEventCacheFlushAndInvTS,
                      _EventIndexFence, _GCRGL2WB, _GCRSeq,
                      _CachePolicyBypass, _DataSel32/64, _IntSel*

  amdgpu_cp.h     — CPContext + storage layout constants.
                    kCPRingDefaultBytes=16K, kCPMQDBytes=4K,
                    kCPWBPageBytes=16K. WB offsets: rptr=0x000,
                    wptr=0x040, fence=0x080.

  cp_v12_0.cpp    — cp_alloc_storage allocates:
                      KIQ ring  (16 KB, VRAM via vram_alloc)
                      KIQ MQD   (4 KB,  VRAM via vram_alloc)
                      WB page   (16 KB, DART-mapped sysmem)
                    Populates volatile rptr_cpu / wptr_cpu /
                    fence_cpu pointers + their GPU-side bus addrs.
                    cp_ring_write stages PM4 dwords (tracks wptr —
                    actual ring-memory writes come once userspace
                    maps BAR2 + KIQ ring page).
                    cp_emit_eop_fence builds NOP + RELEASE_MEM
                    with INT_SEL_SEND_INT so the fence travels
                    through the IH ring to userspace.

  BringupContext gains CPContext. BringupStage::CPInit now wired
  to cp_init_full (allocates storage only — actual HQD/doorbell
  register programming lands in the next chunk).

(2) Pre-existing dispatcher bug repaired:

  run_stage's switch had stale fall-throughs — SMUInit /
  GMCInit / IMUInit had no case bodies and silently fell through
  to IHInit. The TMRSetup case was missing entirely from both
  stage_name and run_stage despite TMRSetup having shipped two
  chunks ago. Build passed (cases without bodies are legal C++)
  but the runtime behaviour was wrong.

  Restored:
    TMRSetup  → psp_setup_tmr (was missing entirely)
    SMUInit   → smu_test_message + smu_get_version (had no body)
    GMCInit   → gmc_init                            (had no body)
    IMUInit   → still Unsupported (PSP autoload handles IMU
                microcode load; the orchestrator stage was meant
                to be a no-op anyway, but flagging explicitly)
  stage_name also gained the missing TMRSetup entry.

Build still clean: ** BUILD SUCCEEDED **.

Next chunk: KIQ HQD register programming (CP_RB0_BASE/CNTL/
WPTR/RPTR + doorbell control), CP enable (CP_ME_CNTL ME0_ACTIVE),
and a userspace selector to submit a packet through the staged
cp_ring_write. After that the "Hello PM4" path is end-to-end
testable on real hardware.
2026-05-13 16:19:18 -07:00
geramyloveless 6464258a31 Phase 1B chunk 15: RLC v12 — clear-state buffer + autoload wait
First user of the VRAM bump allocator. The RLC subsystem owns
the GFX shader-engine clear-state buffer (CSB), which lives in
visible VRAM. amdgpu_rlc.h + rlc_v12_0.cpp port two pieces:

  1. rlc_alloc_csb — calls GMCContext.vram_alloc.alloc(16 KB,
     kASPageSize) to carve the CSB off the top of visible VRAM.
     Allocation tracked in RLCContext.clear_state (gpu_va, size).
     Content stays zero-filled for now — Linux fills it via
     amdgpu_gfx_rlc_setup_csb_buffer (a per-asic cs_section_def
     table that's needed for power-gating state save/restore but
     not for a simple NOP/RELEASE_MEM submit).

  2. rlc_wait_for_autoload_complete — port of
     gfx_v12_0_wait_for_rlc_autoload_complete. Polls regCP_STAT
     (0x0F40) and regRLC_RLCS_BOOTLOAD_STATUS (0x4E7C) bit 31
     until both signal "done" (CP_STAT==0 + BOOTLOAD_COMPLETE=1).
     5-second budget — first cold-boot autoload after the PSP
     loads RLC + PFP + ME + MEC + MES microcode can take seconds.

BringupStage::RLCInit wires to rlc_init_full (alloc CSB + wait
for autoload). Was a stub returning Unsupported before.

BringupContext gains an RLCContext.

Build still clean: ** BUILD SUCCEEDED **.

Next: CP init (cp_gfx_resume + KIQ MQD) → first PM4 submit.
That's the "Hello PM4" milestone — one more meaningful chunk
of porting away.
2026-05-13 16:14:47 -07:00
geramyloveless 69d413789f Phase 1B chunk 13: IH v7 ring + drain (interrupt handler subsystem)
Ports drivers/gpu/drm/amd/amdgpu/ih_v7_0.c + amdgpu_ih.c into our
dext per docs/port_plans/IH_v7.md.

What this commit gets us:
  - A 256 KB IH ring buffer in DART-mapped system memory, 16 KB-
    aligned (AS page rule). 256 KB / 32 B per entry = ~8K entries
    — same as upstream's default.
  - A separate 16 KB AS-aligned page that the GPU uses as the
    wptr shadow (avoids a slow BAR read every interrupt).
  - IH_RB_BASE / IH_RB_CNTL / IH_RB_WPTR_ADDR registers programmed
    with the right bus addresses + cntl bits: WPTR_WRITEBACK_ENABLE,
    MC_SPACE = IOMMU (4), RPTR_REARM, MC_SNOOP, WPTR_OVERFLOW_ENABLE.
  - MSI storm + flood + per-client storm protection programmed
    (storm DELAY=3, matches upstream default).
  - ih_drain() walks (rptr → wptr) decoding each 8-dword entry into
    IHEntry (client_id, src_id, ring_id, vmid, timestamp, pasid,
    src_data[0..3]) and calling a caller-provided dispatcher.
    Handles overflow bit clearing.
  - BringupStage::IHInit now wired (was a stub returning Unsupported).
    Runs: ih_init (alloc) → ih_toggle(false) → ih_enable_ring →
    ih_program_msi_storm → ih_toggle(true).

New files under dext/amdgpu/:
  amdgpu_ih.h    IHContext, IHEntry, IHSourceID namespace (CLIENT_GFX,
                 SRC_CP_EOP=0xB5, SRC_UTCL2_FAULT, SRC_SDMA_TRAP, etc.),
                 IHRegs namespace (OSSSYS register offsets:
                 IH_RB_BASE=0x0083, _CNTL=0x0080, _RPTR=0x0081,
                 _WPTR=0x0082, _WPTR_ADDR_LO=0x0086, _ADDR_HI=0x0085,
                 _DOORBELL_RPTR=0x0087, _STORM_CLIENT_LIST_CNTL=0x00AA,
                 _INT_FLOOD_CNTL=0x00AB, _MSI_STORM_CTRL=0x00AC),
                 IH_RB_CNTL field shifts.

  ih_v7_0.cpp    ih_init / ih_release / ih_toggle / ih_enable_ring /
                 ih_program_msi_storm / ih_drain / ih_init_full.

BringupContext gains an IHContext alongside DeviceContext / PSPContext /
GMCContext.

Deferred to next chunk:
  - Wiring ih_drain into MacAMDGPUUserClient::InterruptOccurred.
    Currently the IH ring fills but nobody walks it; this is the
    last piece before EOP fences from a first PM4 submit can route
    through to userspace.
  - Per-source dispatch table (currently ih_drain logs entries via
    the caller's dispatch fn; the dispatcher itself is the user's
    responsibility).
  - Doorbell-based rptr advance (currently MMIO; saves a slow BAR
    write per drain pass).

Build still clean: ** BUILD SUCCEEDED **.
2026-05-13 16:07:54 -07:00
geramyloveless b44a79f036 Phase 1B chunk 3: buildable Xcode bundle + SwiftUI host + xcodegen
Project is now buildable end-to-end. \`scripts/build.sh\` generates
the .xcodeproj via xcodegen and runs xcodebuild against both targets.
Verified on this machine with Xcode 26.4.1 and DriverKit SDK 25.4:
both MacAMDGPU.dext and MacAMDGPUHost.app build clean (and
strip-link clean once the namespace fixes below landed).

Build outputs (Debug-driverkit / Debug):
  MacAMDGPU.dext            arm64 / DEXT / 126 KB
  MacAMDGPUHost.app         arm64 / app with embedded dext

How to build:
  scripts/build.sh            # gen + build (Debug)
  scripts/build.sh --open     # open in Xcode
  XCODE_TEAM_ID=ABCDE12345 scripts/build.sh   # signed build

New files:
  project.yml                 xcodegen spec (2 targets)
  scripts/build.sh            generate + build orchestrator
  Host/MacAMDGPUHostApp.swift SwiftUI host with Install/Remove buttons
                              + OSSystemExtensionRequest plumbing +
                              event log
  Host/Info.plist             NSSystemExtensionUsageDescription
  Host/Host.entitlements      com.apple.developer.system-extension.install

Compile/link fixes (the dext was source-only until now — these are
real errors uncovered by an actual DriverKit-SDK build):

  - Renamed our \`namespace MacAMDGPU\` -> \`namespace amdgpu\`. The
    IIG generator emits a top-level \`class MacAMDGPU\` from
    MacAMDGPU.iig; the namespace collided with the class. The new
    name also matches the Linux source we're porting (drivers/gpu/
    drm/amd/amdgpu). All references in dext/MacAMDGPU.cpp and
    dext/amdgpu/* updated.

  - amdgpu_psp.h now explicitly includes IOBufferMemoryDescriptor.h
    and IODMACommand.h (previously relied on a transitive include
    that doesn't exist under the real SDK).

  - amdgpu_regs.h poll_reg: replaced \`for (volatile int i…)\` busy
    spin (which trips -Wdeprecated-volatile in C++20) with an
    equivalent register-read fold.

  - project.yml: dept target links against PCIDriverKit.framework
    via dependencies + OTHER_LDFLAGS. Without this the IOPCIDevice
    symbols are undefined at link time.

.gitignore: xcodegen-generated MacAMDGPU.xcodeproj is now ignored
(regenerate locally with scripts/build.sh).

User-side next steps to apply for the DriverKit transport.pci
entitlement (Apple Developer portal):

  1. export XCODE_TEAM_ID=<your team>
  2. scripts/build.sh --open
  3. In Xcode: Signing & Capabilities for both targets — confirm
     team auto-selected. The first build attempt will round-trip
     the bundle IDs (com.example.MacAMDGPUHost + .MacAMDGPU) to
     the Apple Developer portal; rename the bundle prefix in
     project.yml first if "com.example" collides with existing IDs.
  4. In developer.apple.com → Certificates, Identifiers & Profiles
     → Identifiers → MacAMDGPU dext bundle ID → Capabilities →
     enable "DriverKit (development)" then "DriverKit Transport
     PCI" — that pops the entitlement-request form. Match scope
     should be 0x75511002&0xFFFFFFFF (R9700) as already declared
     in dext/MacAMDGPU.entitlements.
2026-05-13 15:00:24 -07:00
geramyloveless 9910e4f2d4 Phase 1B chunk 2: PSP bootloader components + KM ring create
Rounds out the pre-SOS bootloader surface and gets the PSP command
ring online. After this commit the PSP subsystem can accept
ring-based commands (the door for SMU PMFW load + TMR setup).

amdgpu/amdgpu_psp.h:
  PSPContext gains ring fields (ringBuffer, ringDMACommand,
  ringBusAddr, ringCPUAddr, ringSize, ringCreated).
  New decls: psp_bootloader_load_component, psp_ring_create.

amdgpu/psp_v14_0.cpp:
  + psp_bootloader_load_component — port of
    psp_v14_0_bootloader_load_component. Generic for KDB / SPL /
    SysDrv / SocDrv / IntfDrv / DbgDrv (= HADDrv on v14) / RASDrv /
    IPKeyMgrDrv. Skips if SOS already alive.
  + psp_ring_create — port of psp_v14_0_ring_create (non-SR-IOV
    path). Allocates 4 KB DART-mapped ring buffer, programs
    C2PMSG_69..71 + C2PMSG_64, waits on response flag in
    C2PMSG_64 (mask 0x8000FFFF, expected 0x80000000).
  psp_release now tears down the ring buffer as well as fw_pri.

amdgpu/amdgpu_ip.h:
  + C2PMSG_69/70/71/102/103 offsets.
  + GFX_FLAG_RESPONSE / GFX_CMD_*_MASK (0x80000000 / 0x0000FFFF).
  + MBOX_TOS_RESP_FLAG/MASK combined constants.
  + kPSPRingTypeKM = 1, kPSPKMRingSize = 0x1000.

amdgpu/amdgpu_init.{h,cpp}:
  + BringupStage::PSPRingCreate (inserted as stage 4, bumps
    SMUInit→5 and following stubs).

dext/MacAMDGPU.cpp:
  LoadFirmware switch extended with new fw type tags:
    KDB(1), SPL(2), SysDrv(3), SocDrv(4), IntfDrv(5), DbgDrv(6),
    RASDrv(7), IPKeyMgrDrv(8). Each routes through
    psp_bootloader_load_component with the matching bl_cmd.

scripts/macamdgpu_ping.swift:
  Stage + fw-type constants updated to match.

What this still doesn't do (next chunks):
  - IP base addresses for R9700 — bringup remains gated on these
    being populated via SetIPBase (or future on-die discovery).
  - SMU v14_0_3 mailbox handshake — needs the MP1 IP base and
    the PSP ring (to load PMFW). Will be the next port.
  - TMR (Trusted Memory Region) — programmed via the PSP ring
    after PMFW; sits in VRAM.
2026-05-13 14:10:14 -07:00
geramyloveless da1828bb35 Phase 1B start: PSP v14 SOS load orchestrator
Begins porting amdgpu lifecycle code from upstream/linux/drivers/
gpu/drm/amd/amdgpu/. First subsystem online: the PSP v14 bootloader
SOS load path. After SOS is alive on the GPU, subsequent firmware
loads (KDB, sysdrv, socdrv, etc.) and the SMU mailbox become usable.

New module layout under dext/amdgpu/:
  amdgpu_ip.h        IP version pinning + IP base address table.
                     R9700 versions hardcoded; bases sentinel until
                     read from the on-die discovery binary or set
                     via the SetIPBase selector (one-time bootstrap).
  amdgpu_regs.h      RREG32 / WREG32 over BAR0 (calls
                     IOPCIDevice::MemoryRead32 / Write32);
                     SOC15_REG_OFFSET helper; poll_reg helper for
                     PSP / SMU mailbox waits.
  amdgpu_psp.h       PSPContext + bootloader interface.
  psp_v14_0.cpp      Direct port of psp_v14_0.c functions:
                       psp_init             — fw_pri DMA buffer alloc
                       psp_is_sos_alive     — check C2PMSG_81
                       psp_wait_for_bootloader — C2PMSG_35 bit31 poll
                       psp_load_sos         — full bootloader handshake
                     Citations to Linux source line numbers in each
                     function header.
  amdgpu_init.h /.cpp  Bringup orchestrator: a 12-stage ladder
                     (IPDiscovery, PSPInit, PSPLoadSOS, then 9
                     stubs for SMU/GMC/IMU/RLC/CP/MES/IH/GFX/SDMA).
                     bringup_to(target) runs stages incrementally;
                     idempotent.

New selectors in MacAMDGPUUserClient (kept ordering compatible —
all Phase 1A selectors keep their values):
  9 InitDevice(target_stage) -> reached_stage
  10 LoadFirmware(type, size_bytes)  — reads from this client's
                                        DMABuffer
  11 SetIPBase(block_id, base)       — bootstrap path
  12 GetIPBase(block_id) -> base, resolved

Per-driver BringupContext lives on MacAMDGPU_IVars (not per-client).
Populated when the first client opens the PCI device — DeviceContext
captures pci pointer + BAR memIndex/size for BAR0/BAR2/BAR5. The
small-BAR-on-AS reality is visible immediately in bar2VisibleVRAMSize
(expect 256 MB without ReBAR, ~1 GB with the partial ReBAR the user
mentioned).

Swift CLI extended:
  --init                  runs IPDiscovery + PSPInit (PSPLoadSOS will
                          fail until firmware is provided)
  --load-sos <path>       loads psp_14_0_3_sos.bin from path into the
                          DMABuffer and calls LoadFirmware(type=SOS),
                          which kicks psp_load_sos
  showIPBases             enumerates resolved-vs-missing IP base
                          addresses for diagnostics

Known gaps (next commits):
  - IP base addresses for R9700 — need a one-time host-side dump or
    on-die discovery port. Until set, PSPLoadSOS returns NotReady.
  - SMU v14_0_3 mailbox handshake (smu_v14_0.c port)
  - GMC v12 VRAM detect + GART setup
  - MES v12_1 queue manager
2026-05-13 13:56:58 -07:00