163 Commits
Author SHA1 Message Date
geramyloveless fbe6efb46f Offline tests pass on the CI runner's bash and timing
The runner's bash is macOS's 3.2, where expanding an empty array under
set -u is an unbound-variable error: test-kmem-release, test-kfd-session
and test-kfd-power expand theirs only when set.

test_aql_reset's concurrency check stored the queue's write index with a
plain store while the reset thread reads it, which TSan reports as a race.
The test now publishes it with a release store, as the HSA runtime does.

tests/KNOWN_FAILURES.md lists the tests skipped for a known reason, and
scripts/known-failure.sh gates their recipes on it. Three timing tests
whose windows the shared CI VM misses are skipped there only (CI set):
test-mutex-completion, test-iokit-dma and test-display-pipeline. They
still run on a developer Mac. MAC_LINUXGPU_RUN_KNOWN_FAILURES=1 runs them.
2026-10-08 15:45:05 -07:00
geramyloveless dc0229043a Display agent: close a mirroring process's pipe at end of file
The daemon read each mirroring process's output with a readabilityHandler
that ignored end of file. At end of file availableData is empty and the
handler fires again at once, so the handler spun and the read descriptor
stayed open after every child exit. A daemon up for 29 hours ran at
170-260% CPU holding 2,556 pipes, and the child output stopped reaching
the log.

followOutput (DisplayAgent.swift) closes the read end and clears the
handler at end of file, after the last chunk. The termination handler no
longer clears the readability handler, which could drop the last lines
and leave the descriptor open. A pipe whose process failed to start is
closed.

A mirroring process no longer ends when its STATUS poll is answered
kIOReturnBusy: the daemon's STATUS and PROBE and the child's own IMPORT
share the driver's display gate, and a collision ended the mirror, which
the daemon restarted 10 s later. IMPORT is asked again for up to 2 s on
kIOReturnBusy. The daemon logs a mirroring process's exit status.

test-display-agent runs 20 short processes through followOutput and
checks every byte arrives, the end is seen once, no descriptor is left
open and nothing spins afterwards.
2026-10-08 13:03:11 -07:00
geramyloveless b190c105a8 Kernel arguments in CPU-visible VRAM, published with the HDP flush
HRX on Linux keeps a queue's kernel arguments in CPU-visible VRAM and
publishes them with the HDP flush register when the HSA runtime reports
HSA_AMD_AGENT_INFO_HDP_FLUSH and lets the CPU at the device coarse pool.
This brings that path to the Mac, where a CPU store to a GPU that stopped
answering can panic the machine, so every such store is bracketed under
the client's gate.

patches/linux/amdgpu-mmio-remap-4k-hole.patch: the NBIO/NBIF HDP flush
remap stays in the 4 KiB register hole the hardware leaves unused,
whatever the host page size (upstream moved it with PAGE_SIZE and turned
it off for pages over 4 KiB). KFD's own MMIO paths still refuse large
pages; nothing upstream maps the page into a process.

linuxu (kfd_session.c): rt_kfd_session_hdp_flush gives the host page of
the register BAR holding the remap page, after checking that no register
block of the device starts in the rest of it. VRAM can take a window VA,
and rt_kfd_bo_make_cpu_visible pins such a buffer in the CPU-visible
window: unmapped from the GPU, off the eviction fence, pinned with
CPU_ACCESS_REQUIRED, the move waited for, mapped again at the same VA.
rt_kfd_bo_bar_ranges reports its BAR ranges; a free unpins it first.

dext (hdp_flush.h): QueryInfo MLG_QUERY_BAR_WRITES lets a KFD client
opt in. It gets its gate (published, so every power transition, reset,
quarantine, fault, removal and close closes it and drains), the HDP
flush page as client memory, and CPU access to hostable VRAM: BOAlloc
flag DEXT_COMPUTE_BO_FLAG_HOSTABLE, then BOMap pins it and hands out its
BAR ranges. A client that never asks gets none of it. A retired gate is
marked so the client knows it never reopens. Closes that stop the device
answering (the session's close, quarantine, reset) wait up to 1 s for
an open bracket. Build 265.

HSA runtime: mac_hsa_bar_writes_enable, mac_hsa_bar_write_begin and
mac_hsa_bar_write_end. After enable the agent reports HDP_FLUSH, the CPU
agent's access to the VRAM pool is DISALLOWED_BY_DEFAULT, VRAM is
allocated hostable, and hsa_amd_agents_allow_access with a CPU agent maps
an allocation write combined at its own address, as ROCr does on a
large-BAR device; nothing else is CPU-mapped. begin waits while the gate
is held and fails once the device is gone, after replacing every BAR
mapping of the process with host memory (bar_mapping_retire.h); kicks
that find the GPU disconnected do the same.

libmlg_drm: a transport that says the device is gone has every mapping
retired the same way, so Vulkan clients' stores through mapped VRAM and
doorbells land in host memory too.

Tests: the session test pins hostable VRAM, checks its BAR ranges, a
full window and the HDP page with and without a register block beside
it; the production test enables BAR writes, maps hostable VRAM and
ranges it; hsa-bar-writes checks what is reported before and after
enable, the CPU grant, nested brackets, a held gate and a lost device;
the gate and libmlg_drm tests check retired gates and mappings.
2026-10-06 19:29:29 -07:00
geramyloveless 3ea54712bc Client BAR stores as one gate bracket, and a client's own revocation
Prototypes for letting HRX write kernel arguments into CPU-visible VRAM
and publish them with the HDP flush register on this platform, where a
CPU store to a GPU that left the Thunderbolt link panics the Mac.

doorbell_gate.h: mlg_bar_write_begin and mlg_bar_write_end bracket a
submission's several stores into the BARs (a memcpy into the VRAM kernarg
ring, the HDP store and its read back, the doorbell) under the client's
existing gate, with the same Dekker protocol as mlg_doorbell_ring.
Brackets nest, so a doorbell rung inside one is a nested bracket. End
completes the stores (DSB ST) before counting out, since the driver may
power the device down the moment busy reads zero. mlg_doorbell_ring is
unchanged.

hsa/src/bar_mapping_retire.h: DriverKit cannot revoke a mapping it gave
a client, so the client maps zero-filled anonymous memory over its BAR
range in one step (mmap MAP_FIXED) once it learns the device is going:
every later store from any thread lands in host memory and every load
reads zero, as Linux's dummy page after drm_dev_unplug.

Tests (make test-bar-write-safety): submitters copying kernargs, storing
and reading back the HDP register and ringing the doorbell race power and
reset holds, client closes and session closes under ThreadSanitizer and
AddressSanitizer, and no store lands after a close returns; writers with
no gate store into a shared mapping while it is retired, and none reaches
the underlying pages afterwards, none faults, and the range reads zero.
2026-10-06 18:33:31 -07:00
geramyloveless 4fe23bc535 A client rings its KFD queues' doorbells itself
A doorbell cost the submitting thread a trip through the driver: 14.7 us
for the synchronous AQLQueueKick of build 263 (20 us async before it), on
the one delivery thread every client's calls share. On Linux a process
writes the doorbell page it mmaps from /dev/kfd: one store. From build 264
the runtime does the same.

- The client maps its KFD process's doorbell slice (MLG_DOORBELL_MEMORY_TYPE,
  uncached): the page of the doorbell BAR KFD gave that process
  (rt_kfd_session_doorbells), holding only its own doorbells, as libhsakmt
  maps it. AQLQueueCreate asked for three outputs answers the queue's
  doorbell in it (out[2]), or MLG_DOORBELL_NONE for a queue rung through
  AQLQueueKick (a legacy queue). A KFD queue whose doorbell cannot be
  mapped is destroyed again and the call fails.
- A store to the GPU's BARs once it stops answering can panic the Mac, so
  every doorbell write goes through a gate (doorbell_gate.h): a page the
  driver and the client share (MLG_DOORBELL_GATE_MEMORY_TYPE). The client
  counts itself busy, writes only while the gate is open, and counts itself
  out; the driver closes the gate and waits until busy is zero (Dekker's
  protocol, sequentially consistent both sides), so once a close returns
  the client writes nothing. A closed gate writes nothing: the runtime
  then sends the doorbell as AQLQueueKick, which answers what the device
  can take (Offline while it suspends: the doorbell waits for resume, as
  before; NoDevice once it is gone).
- The driver closes every gate for a power transition (power_set), and for
  a device reset's whole window (the recovery hooks, before upstream halts
  the device until the PCI restore put the BARs back; a failed reset
  wedges and keeps them closed). Both doorbell paths, the clients' and the
  delivery thread's kick table, now hold a set of reasons instead of one
  flag, so a power change inside a reset opens nothing. A client's gate
  is retired (closed, drained, forgotten) at its close, its KFD process's
  release (whose doorbell slice may go to another process), the session's
  close or quarantine, a transport fault and a removal. The wait is a
  bounded spin (it may run on the delivery thread): a client stopped
  inside a write for 20 ms is named in the log.
- Runtime: the queue keeps its doorbell and gate from creation until
  inactivate; a write never lowers the doorbell (as the driver's paths).

Measured on the R9700 over Thunderbolt 5 (lat.cpp, display mirroring):
doorbell store 14.7 -> 0.38 us median; empty dispatch round trip 43.9 ->
32.4 us (Linux on the same card: 31.3); back-to-back wall per dispatch with
a doorbell each 16.8 -> 12.7 us. LemonSeed Engine decode is GPU-bound:
plain 28.2 -> 28.7 tok/s, DFlash2 51.3 -> 51.4.

Tests: test-doorbell-gate races client threads ringing through their gates
against power holds, device-reset holds inside them, client closes and
session closes, under ThreadSanitizer and AddressSanitizer; a doorbell
written after a close returns fails it (dropping the drain does). It also
names a client stopped mid-write. test-kfd-session checks the slice (a
page of BAR 2, the process's own) and that the client's offset is the word
the driver's kicks write; test-dext-compute-production the doorbell
lookup, gate publish, power and reset holds and retire at the client's
release; test-kick-table holds and releases both reasons;
test-hsa-power-transport the runtime's maps, its direct store, a closed
gate, and the failures that destroy the queue again.
2026-10-06 17:18:27 -07:00
geramyloveless 3e81415e0f Session cycles past IP discovery from a local card capture
The session cycle test's probe stops in IP discovery, before upstream
takes the DMA mappings, pages and threads the cycle checks watch. With
the card's IP discovery binary and VBIOS it gets further:

- test_session_cycles --deep: upstream reads the discovery binary as a
  file (amdgpu_discovery=2) and the VBIOS through SMUIO's ROM_INDEX and
  ROM_DATA registers, as on the card ("Fetched VBIOS from ROM"); VRAM
  (BAR0) and the doorbells (BAR2) map; registers keep what was written
  to them. Each cycle must read the whole VBIOS, and every resource must
  return to its baseline as in the shallow mode.
- scripts/capture-r9700-fixtures.py records the inputs from a running
  driver, read-only, through upstream's own exports: the ip_discovery
  sysfs tree and AMDGPU_INFO_DEV_INFO through the observer,
  mem_info_vram_total, AMDGPU_INFO_VBIOS on the render node through
  libmlg_drm (only after the observer reads show the driver running),
  and the BAR sizes from the I/O Registry. The driver exports the raw
  discovery binary only in debugfs, so scripts/ip_discovery_builder.py
  rebuilds it from the sysfs export (no variant or sub-revision, no
  harvest/VCN/MALL/NPS table, gc_info v1.0 from DEV_INFO).
- The capture goes to tests/fixtures/local/r9700/, which git ignores:
  the VBIOS is AMD's copyrighted image and the repository is public.
  tests/fixtures/local/README.md says how to capture.
- scripts/test-session-cycles.sh runs the deep cycles when a capture is
  present and prints SKIP otherwise (as on CI). On every run it also
  self-checks the deep harness with a synthetic RDNA4-shaped table and
  a ROM without ATOM tables: upstream must find SMUIO, read the whole
  ROM, refuse it and unwind the same way every cycle.
2026-10-06 17:18:27 -07:00
geramyloveless 2dd02645b6 AQL queues are mapped again after a device reset
The driver's persistent AQL queues are legacy kernel queues MES maps;
a device reset takes them with MES's state. Upstream's device recovery
now carries them across:
- As upstream halts the device, a DRM client of the device (the hook
  upstream gives everything outside amdgpu that must stop before its IPs
  suspend) marks every mapped queue unmapped. Kicks are refused until
  it is mapped again.
- Once the reset has succeeded and the schedulers run again (where KFD
  restores its queues), before the new reset generation is published,
  each queue's storage block is written again with an MQD upstream
  builds afresh, positioned at the producer's write_dispatch_id, the
  reader is moved there, and the queue is mapped. Packets not finished
  were lost with the GPU's state; the generation tells clients. The
  restore writes the storage through SDMA, so it cannot run from the DRM
  client's resume, which precedes the schedulers' restart.
- A queue that cannot be mapped again is retained, and its owner's next
  call freezes the session. A queue destroyed after a reset that was not
  followed by a restore (the device wedged) is freed without an MES unmap.

The hooks run on the reset domain's thread while the owner queue serves
calls, so dext_aql keeps its own list of mapped queues under a lock held
only across bounded steps (MES map/unmap, storage writes), never across a
wait the reset must finish. Without it a restore could write a queue a
destroy had just freed.

The fixture's device-reset-recovers check failed intermittently: the
fixture's ASIC reset zeroed its engines' read pointers while the driver's
rings kept their write pointers (the fixture's IP blocks had no resume),
and an engine could also carry on mid-batch from the cleared position.
The SDMA engine then executed its stale ring from the start, old fence
values included; amdgpu_fence_process took the lower sequence for a wrap
and signalled every pending fence, so a new client's IB ran before its
page-table update and faulted. The ASIC reset now stops each engine at a
packet boundary, and the fixture's GFX and SDMA blocks resume their rings
at 0 as gfx_v12_0 and sdma_v7_0 do. The check now also asserts both
resumes ran.

Tests: test-aql-reset builds the real dext_aql.mm against a mock MES and
checks restore at the producer's position, kicks refused in between, the
wedged destroy, a failed restore, and the hooks on their own thread
against 300 rounds of create/kick/destroy under ASan and TSan (without
the lock it reports a use-after-free). The production-backend scenarios
cover the hooks' installation and the freeze on a failed restore; the
fixture's device-reset-recovers covers upstream's recovery running the
hooks around a real reset.
2026-10-06 17:18:27 -07:00
geramyloveless b856a93f95 GPU recovery: device resets behind a gate, bounded; RESET_WAIT
A hang the queue reset cannot end now runs upstream's device reset
(amdgpu_device_gpu_recover, mode1 on gfx12) when the platform allows it
(rt_recovery_set_full_reset_gate), and wedges the GPU otherwise. The
driver's gate allows it only when the personality enables device resets
(MacLinuxGPUDeviceReset, absent = off until a reset is validated over
Thunderbolt) and no client maps one of the GPU's BARs: neither a raw BAR
lease nor any Linux-file mapping through a BAR (rt_lx_bar_mappings),
since a client store into a BAR that stops decoding can take the Mac
down. Every refusal is logged with its reason as the wedge's.

Upstream's own recovery runs unchanged, with three bounds around it:
the ASIC reset is wrapped so one recovery makes at most two attempts
(upstream retries a reset whose IB tests fail without limit on bare
metal); a device reset that fails (reset_domain->reset_res) wedges the
GPU, where upstream would leave its schedulers stopped with no event;
and one that succeeds advances the reset generation, with
RT_RECOVERY_LAST_VRAM_LOST when the VRAM-lost counter moved. The KFD
and user-queue reset works go through the same path.

RESET_WAIT (selector 91, observers and session clients, registration on
the delivery thread) completes when the reset generation differs from
the one the caller knows, with the generation and MLG_RESET_FLAG_*; a
client's waits end with it. The host's daemon re-arms it to post its
notification.

Tests: device_reset_check (the CS fixture, which now has soc24's reset
method and an ASIC reset that restarts its engines) allows device
resets and hangs a queue whose reset fails: upstream's
amdgpu_device_gpu_recover runs, the GPU does not come back (no VBIOS),
the device wedges after one ASIC reset and nothing retries. test-owner-
call covers RESET_WAIT (new generation, stale generation, cancel) and
the gate (personality, raw lease, client BAR mappings);
test_lx_files counts a client's BAR mapping.
2026-10-06 17:18:27 -07:00
geramyloveless c3c8521137 PCI restore puts back the BARs and MSI-X a device reset clears
A mode1 reset clears the GPU's configuration (BARs, command, MSI-X) and
nothing in macOS writes it again; upstream caches it before the reset
and restores it after (amdgpu_device_cache_pci_state/load_pci_state).
pci_restore_state refused any BAR change (-ESTALE, the transport-fault
latch) and never restored MSI-X, so a device reset could only end in a
quarantine.

The saved state now also holds the MSI-X capability's control word and
the table entries DriverKit programmed (read from the table's BAR
through the kernel, dext_pci_bar_read32), the vectors in use first.
Restore checks it is the same function with the same capability layout,
then writes back the header as the host assigned it (cache line and
latency, BAR0-5, the ROM BAR, the interrupt line) with memory decode off
until every BAR reads back its value, the PCIe controls, MSI-X (function
masked while the table is written, each entry verified, then the saved
control), and the command last. A BAR or table entry that does not take
its value fails the restore as before. The values are the host's own
assignment: nothing moves behind the host bridge.

test_pci_dext covers a reset that cleared the BARs, ROM and command, a
BAR that does not take its value, MSI-X saved and written back, and a
table entry that does not take its value.
2026-10-06 17:18:27 -07:00
geramyloveless 6a8305facd The host reads the GPU's Resizable BAR capability
MacLinuxGPUHost rebar prints, for each resizable BAR, the sizes the
device can decode and the size it decodes now. It reads the device's
configuration space through the sysfs "config" file as an observer,
like the pcie command, so it writes nothing and works beside a session.

The parser walks the extended capability list from 0x100 and accepts
the capability only as linuxu's pci_rebar_read does: version 1, one to
six entries inside the space, distinct BARs, and a selected size the
BAR supports. test-device-info checks it against the R9700's capability
(BAR0 256 MB of 256 MB to 32 GB, BAR2 2 MB of 2 MB to 256 MB) and
against malformed lists.

macOS sizes every BAR and the bridge windows above it once, when it
enumerates the device. IOPCIFamily never programs this capability and
takes no BAR above 1 GB, and DriverKit has no call to resize one, so
the size shown as now is the one the driver works with.
2026-10-06 16:10:58 -07:00
geramyloveless 2122b9b1c1 The CP write-pointer polling experiment, off by default
KFD's GFX 12 MQD already points CP_HQD_PQ_WPTR_POLL_ADDR at each queue's
write index (amd_queue_t.write_dispatch_id). Upstream leaves the global
CP_PQ_WPTR_POLL_CNTL.EN off (gfx_v12_0_kiq_init_register writes it for
the KIQ only), and MES takes each queue's write-pointer address in
ADD_QUEUE and handles unmapped queues through CP_UNMAPPED_DOORBELL. Nothing
upstream says whether MES firmware writes the polling register. With EN
set, the CP would read the write indexes itself every PERIOD, and a
client's own store to its write index would start its work with no
doorbell and no CPU store to the BAR at all.

rt/wptr_poll.h:
- Observation, always on: the register is read once after each KFD queue
  is created, when MES has mapped it and compute is active (KFD keeps
  GFXOFF off then), and logged whenever its value changed. The first runs
  show whether MES writes it.
- The experiment, off unless the dext's personality sets
  MacLinuxGPUWptrPollPeriod (1-255, the field's raw value, whose unit is
  undocumented): EN and PERIOD are written, re-written if MES clears them,
  and reported in session state (WPTR_POLL).
- The runtime skips doorbells only with MAC_HSA_DOORBELL=poll and only
  while the driver reports polling; otherwise it says why and the queue
  fails.

GFX 12.0 only (the gc_12_0_0 register headers); nothing else changes.
2026-10-06 15:39:53 -07:00
geramyloveless 5607122bec AQLQueueKick on the delivery thread
A doorbell cost the submitting thread an async session call: about 20 us,
twice a synchronous call through the driver (a Ping is 10 us), because an
async call sets up its completion and hops to the session queue. From
build 263, AQLQueueKick called synchronously rings the doorbell on the
delivery thread itself.

DriverKit delivers every client's calls on that thread, which must never
sleep (build 241). The doorbell there takes no session lock and reads none
of the session queue's tables:
- kick_table.h: the KFD queues that may be rung on the delivery thread, by
  handle and owner, under a spinlock nothing holds across a sleep. The
  session queue publishes a queue once it exists and retires it before
  anything of it goes: its DESTROY_QUEUE, its owner's close, the device's
  stop. A ring holds the lock across its doorbell write, so once retire
  returns no doorbell of the queue is written and its memory may go. The
  table also closes for power transitions (power_set), which waits for a
  write in progress.
- rt_kfd_queue_kick_nowait: the doorbell under the session's kick
  spinlock alone. A queue is ringable from its creation until its
  DESTROY_QUEUE (queue_release_locked clears it under that lock first,
  since the doorbell is then released to other queues). Both doorbell
  paths share the highest value written, and neither writes a lower one.
  As on Linux, where the process writes its doorbell page itself, the
  value is not checked against the write index.
- The PCI access gate under the doorbell write is a spinlock and atomic
  counters, so nothing on that path sleeps. The store to the BAR stays in
  the driver, behind its removal gate; nothing is mapped into the client.

What the fast path cannot vouch for (a legacy queue, a busy or closing
session, an unpublished queue) it answers kIOReturnUnsupported, and the
runtime sends that doorbell as the async session call. Offline,
VMError, NoDevice and BadArgument answer as the async call does.

Tests: test-kick-table races four delivery threads against queues
published, retired and freed at once, client closes and power gates, under
ThreadSanitizer and AddressSanitizer. No ring reaches a retired, freed,
foreign or gated queue. The delivery threads kept ringing while the
session thread slept (a slow DESTROY_QUEUE): rings during the sleeps 2830
under TSan, 29100 under ASan. Longest wait for the lock 137 us under TSan,
38 us under ASan. test-kfd-session covers the nowait path on the real KFD
session code: written, never lower, refused from DESTROY_QUEUE on, -EFAULT
after a GPU fault. test-dext-compute-production covers publish, owner,
gate and retire on destroy and on client close. test-hsa-power-transport
covers the runtime's synchronous form and each answer.
2026-10-06 15:39:53 -07:00
geramyloveless 3b10f769bb An upgrade hands over without Retire: ShutdownGPU, remembered until idle
Since the device stays up across clients (248), a previous instance whose
last client left keeps its session, and with it the GPU, open. It can
leave only once that session is closed, and Retire, the installer's way to
close it, needs the session-release authorization the signed app does not
have (kIOReturnNotPrivileged). So every upgrade stayed "terminating for
upgrade via delegate" until someone killed the old driver, which panics the
Mac, or power-cycled the GPU.

The installer now hands over without Retire when Retire is refused. It
opens a session client of its own on each previous instance and asks
ShutdownGPU, which any session client may ask and which closes the session
when no other client uses it. The display agents are already stopped for
the upgrade. The installer keeps asking until the instance is gone, and
says which programs still hold it.

When other clients still use the GPU, the driver now remembers the request
(s_closeWhenIdle, session state flag CLOSE_WHEN_IDLE): the last client's
leaving closes the session, even after the installer has given up. The
request goes with the session. Nothing about Retire's authorization
changes. Disconnect GPU uses the same path when its Retire DISCONNECT is
refused.

Tests: test-session-shutdown runs the production code for the upgrade with
no client left (ShutdownGPU closes the session at once, IOKit's Stop then
finishes) and with a client that leaves afterwards (refused, remembered,
closed by that client's leaving, then Stop). test-display-agent covers
reading ShutdownGPU's answers. A previous instance from before build 263
does not remember the request: the installer then asks again after the
clients leave.
2026-10-06 15:39:53 -07:00
geramyloveless 0aa38c6719 Production test reads the serving build from the driver
test-dext-compute-production asserted RuntimeBuild's out[2] was 258, so it
failed once DEXT_RUNTIME_BUILD moved on (262). It now compares against the
compiled build the driver reports (RuntimeBuild's out[3]).
2026-10-06 15:32:52 -07:00
geramyloveless 7d48fe5a28 Copies between system pages and VRAM by SDMA through TTM's GART windows
hsa_memory_copy and hsa_amd_memory_async_copy reached about 3 GB/s on a
link where RADV's SDMA copies reach 6.9 GB/s. A copy between a client's
system pages and VRAM went 1 MiB at a time through the driver's GART-bound
staging buffer: a CPU copy of the pages (the driver's device-safe memcpy)
and a waited SDMA job per step, after the runtime's own CPU copy into its
mapped staging.

rt_kfd_bo_copy now copies between a GTT buffer and VRAM with
amdgpu_ttm_copy_mem_to_mem on TTM's move entity, as amdgpu_move_blit moves
a buffer on Linux: the system pages are mapped through the entity's GART
windows and SDMA copies them directly, one fence for the whole range,
with no CPU copy. A copy that fails or outlives its timeout keeps the
buffers until its fence signals, as the staging path does (copy_wait).
Buffers SDMA cannot reach that way (no DMA addresses, not GTT) keep the
staging path. patches/linux/amdgpu-ttm-copy-mem-export.patch makes the
function callable and leaves its resv argument optional.

BOCopy (selector 48) takes up to 16 MiB a call, and DEXT_RUNTIME_BUILD is
262. The HSA runtime asks for that limit from build 262 on, and copies
between a shared (GPU-mapped) host buffer and a device buffer through the
driver directly, with no CPU copy through its staging buffer.

Host tests: test-kfd-session covers GTT to VRAM and back through the
windows (across page boundaries, from offsets), and a windowed copy that
outlives its timeout. Not yet run on hardware.
2026-10-06 14:13:37 -07:00
geramyloveless 1e2edc1224 The display agent keeps a driver trail on disk
After a panic, the unified log is often missing its last seconds, and the
driver's retained ring dies with the driver. The display agent daemon
(always running) now polls, once a second on its own queue:
- the driver instances in the registry: a line when one appears, and an
  INSTANCE GONE line when one leaves, with the last state read from it and
  the last ring byte read;
- over its own observer client, the cached probe, session, power and reset
  state (a line when it changes) and the new bytes of the driver's log
  ring, read with the LLOG snapshot query exactly as read-driver-log.py
  reads it (bytes the ring overwrote first are counted, never hidden);
- a heartbeat every 30 s.
Lines are appended to ~/Library/Logs/MacLinuxGPU-driver-trail.log and
fsynced at once; the file rotates to .1 past 4 MB. After Disconnect GPU the
trail holds no client, like the rest of the agent, and records instances
only. Observer reads are cached and never claim PCI.

The model (TrailFile, TrailState, TrailLogReader, TrailLineBuffer) is
tested by test-display-agent against a synthetic ring.
2026-10-06 13:16:52 -07:00
geramyloveless 66593d0727 Driver events read in the unified log; Stop and power changes are events
Upstream errors (printk level 3 and worse) went to the unified log as
IOLog("mac.linuxgpu: EVENT %s"), and the DMA seam's events as IOLog("%s"):
both arrive as <private>. They now go through os_log with %{public}s, as
MACLINUXGPU_EVENT already did. printk.c cannot include os/log.h next to
the Linux headers, so the dext registers the sink (klog_set_event_sink)
from a constructor; the level filter is unchanged, so nothing new reaches
the unified log in release beyond events. dext_close's refusal is logged
with literal text instead of a %s argument.

New events, each rare: the driver's Stop (DriverKit has no willTerminate;
Stop is how the driver learns that it or its PCI provider is being
terminated) with the session state, FinishStop letting go of the provider,
and every SetPowerState with the power state it arrived in. A device that
left the bus was already an event.

test-klog registers a sink as the dext does; the session-shutdown fixture's
Stop section bound grows by ten lines for the Stop event.
2026-10-06 13:16:52 -07:00
geramyloveless 6a3111f49c A dext that ends itself closes its PCI session first
A dext process that ends with its IOPCIDevice session open panics the Mac:
IOUserServer::clientClose sends the provider ClientCrashed(), and
IOPCIBridge::childClientCrashRecoveryGated reads through the NULL range of
the R9700's expansion ROM entry (IOPCIFamily+0x19b5c). With the session
closed first, the recovery is skipped.

fatal_close.h gives every way the process can end itself a close-first
step, in plain code with no signal handler and no system call of its own
(build 259's sigaction was killed by the DriverKit sandbox):
- assert(): __assert_rtn is defined in the dext, so every reference in the
  binary and its static library binds to it;
- std::terminate: a terminate handler, set by a constructor and again in
  dext_set_pci, before any session can open;
- libc++ hardening: std::__libcpp_verbose_abort, which libc++ lets a
  program replace;
- a smashed stack: __stack_chk_fail is defined in the dext, so the
  stack-protector calls bind to it.
Each closes the session once (the first thread closes, any other waits for
it), logs one public FATAL event, then calls abort(), so the crash is
still the crash. The close is 259's lock-free close: admission closes, the
open flag is taken, the provider is closed once. BUG(), panic() and
linuxu_fatal() still park the thread and never end the process; no other
abort() call is compiled into the dext.

Hardware faults, libmalloc and FORTIFY aborts (inside libsystem) and an
outside SIGKILL do not pass through this code.

test-pci-call-guards gains a fatal mode: child processes that end by
assert, std::terminate, a libc++ hardening assertion and a real stack
overrun, also with the PCI control lock held elsewhere and on two threads
at once, close the session exactly once and still die of SIGABRT; after a
normal close there is no second Close. Without the close the cases fail.
2026-10-06 13:16:52 -07:00
geramyloveless 73685bdaa0 The context-save area of a KFD queue lives in VRAM
Every queue create allocated its CWSR context-save area in GTT: about
30.8 MB on a 64-CU gfx1201 (0x75000 bytes of wave state per CU, plus the
control stack and debug area). Populating and DMA-mapping that much host
memory costs about 0.22 ms per MB, so queue create took about 6 ms and
destroy about 3.4 ms. Every process paid it on its first signal
operation, when the GPU signal service creates its queue, and that was
the 7 ms "first dispatch".

libhsakmt registers the save area as an SVM range prefetched to the GPU
node, so on Linux it starts in VRAM. The area now goes to VRAM, as there.
KFD clears it before MAP_MEMORY_TO_GPU returns, and the header goes
through the staging buffer and SDMA. A CWSR save no longer writes the
waves' state across the link either.

The test fixture's fake VRAM reuses freed space (first fit over the live
BOs), as the VRAM manager does, instead of a bump allocator that 32 MB
save areas run out of.
2026-10-06 12:46:56 -07:00
geramyloveless c9b08c5b79 No crash-close handler: the DriverKit sandbox kills a dext that installs one
Build 259 installed fatal-signal handlers with a raw sigaction system call
before opening the PCI session, so that a dying dext would close the
session first. The DriverKit sandbox does not allow that call. It
SIGKILLed the dext on every open, before the session opened, so the GPU
never came up: no compute, no display.

The install, its handler and pci_crash_close.h are removed, with nothing
attempted in their place. A crash-close mechanism has to be one DriverKit
permits; that is separate work. The PCI call validator, the close drain
and everything else from that change stay. test-pci-call-guards keeps
its guard and close-fence cases and drops the crash cases.
2026-10-06 12:11:14 -07:00
geramyloveless 6b573a0595 Tests follow SysfsWrite, the KFD fault path and the VRAM MQD
- test-owner-call and test-client-transports compile the dext's bounded
  observer runner, which now also calls observer_sysfs_write: each test
  gets a stub, as it has for observer_sysfs_read.
- test-kfd-power links the KFD session fixture, which delivers GPU page
  faults through kfd_int_process_v11: the script links that source too, as
  test-kfd-session does.
- test-queue-partition links the patched kfd_mqd_manager_v12.c, which
  allocates compute MQDs with amdgpu_bo_create_kernel
  (patches/linux/kfd-v12-mqd-vram.patch): a stub that aborts, as for the
  other allocation entry points the AQL path never reaches.
2026-10-06 11:49:41 -07:00
geramyloveless 2518db49d4 A dext that dies closes its PCI session first; every PCI call validated
The panics of 2026-10-01 (a quarantined dext killed) and 2026-10-06
(build 258.3, 40 s after it attached) are one kernel bug. When a dext
process ends with its IOPCIDevice session open, IOUserServer::clientClose
sends the provider ClientCrashed(), and IOPCIDevice::ClientCrashed_Impl
runs IOPCIBridge::childClientCrashRecoveryGated. Its BAR-restore loop
walks IODeviceMemory and indexes configEntry->ranges[] with
(register - 0x10) >> 2. The R9700's fourth entry (index 3) is its
expansion ROM, register 0x30, so the index is 8, the bridge
prefetchable-window slot, NULL on an endpoint (the ROM is slot 6).
range->start is read through it: ldr w2, [x27] with x27 = 0 at
IOPCIFamily(2.9)+0x19b5c, x22 = 0x30, x23 = 8, x25 = 3, and
x21 = 0x280000, the ROM BAR as read. IOPCIFamily gives every
display-class function with a ROM BAR a ROM range, so any death of this
driver with its session open panics the Mac, whatever it did first.

The 258.3 process died of a fault of its own (an experiment's CPU access
to VRAM past the BAR window, fixed separately), and the kernel bug turned
that into a panic. A session closed before the process ends makes
ClientCrashed_Impl skip the recovery.

pci_crash_close.h: the signals whose default action ends the process
(SIGKILL aside) and that nothing else handles get a handler that closes
the session, then takes the default action: a fault recurs and is
reported as itself, a sent signal is sent again. The close takes no lock
(the failing thread may hold one): admission closes, the open flag is
taken, and the provider is closed once; IOPCIDevice::handleClose turns
bus mastering and memory decode off, as the recovery would have. A dext
links only against DriverKit.framework, which exports no signal call, so
sigaction, sigreturn and kill are the system calls themselves, with the
trampoline ABI of xnu's arm sendsig. The driver logs which signals are
armed, and loudly if the kernel refused one. SIGKILL still cannot be
caught: a dext must never be killed.

The calls themselves (dext_main.mm):
- the memory index and size of each BAR come from GetBARInfo once, right
  after Open; a MemoryRead/MemoryWrite is made only with one of those
  indices, inside that BAR, aligned, on an open session. Anything else is
  a transport fault with its offset, never a kernel call. Register
  tokens, the VRAM aperture (BAR0) and dext_copy_bar_memory use that
  table; the aperture's out-of-window accesses, silently dropped before,
  are now logged and recorded;
- dext_close closes admission, waits up to a second for admitted
  operations and for raw calls, then closes and reopens admission; a
  refusal (a fault, a reset, accesses that do not leave) is logged
  instead of silent. dext_pci_device_present, which reads config space
  outside admission, holds the session for its call and asks only an
  open session.

test-pci-call-guards compiles dext_main.mm whole against a DriverKit
substitute whose IOPCIDevice flags any call outside the kernel's
contract: invalid memory indices (the ROM's, none), accesses outside the
token, outside the BAR and misaligned, aperture accesses outside BAR0,
and every accessor after Close are refused before a call and recorded;
in-window aperture stores (a CPU-visible VRAM MQD) make exactly one call;
Close waits for an access and a raw config read in flight and admits
nothing meanwhile; child processes dying of SIGSEGV, SIGTRAP, SIGABRT
and SIGTERM, also with the PCI control lock held elsewhere, close the
session exactly once first and still die of that signal. Without each
guard the matching case fails.
2026-10-06 11:34:15 -07:00
geramyloveless b633e68a13 No kernel mapping of VRAM past the CPU-visible window
amdgpu_ttm_io_mem_reserve gave every contiguous VRAM resource a
premapped address, aper_base_kaddr plus its offset, although
aper_base_kaddr maps only the visible window (256 MiB of BAR0 on the
R9700). A kernel BO made without AMDGPU_GEM_CREATE_CPU_ACCESS_REQUIRED,
as amdgpu_amdkfd_alloc_kernel_mem makes them, is placed top-down at the
end of VRAM, and its kmap pointed far past the BAR0 mapping. The dext
treats an address outside the aperture as process memory, so the first
CPU store went to whatever was mapped there, or faulted and killed the
driver process. The VRAM MQD of the grid-penalty experiment (build
258.3) was such a BO.

patches/linux/amdgpu-ttm-visible-kmap.patch gives the premapped address
only when amdgpu_res_cpu_visible holds. Otherwise TTM ioremaps the bus
range; rt_ioremap now says loudly that the range is outside every BAR
and refuses it, and the kmap fails with an error the caller reports.
CPU-visible VRAM (amdgpu_bo_create_kernel, CPU_ACCESS_REQUIRED) maps
exactly as before and is reached through the aperture's kernel
accesses.

visible_kmap_check, in the CS selftest (BAR of 64 MiB, 256 MiB of
VRAM): a contiguous BO without CPU_ACCESS_REQUIRED validated past the
window has no kernel mapping; a CPU_ACCESS_REQUIRED BO maps at
aper_base_kaddr plus its offset, inside the window. Without the patch
the first kmap returns aper_base_kaddr + 254 MiB and the check fails.
2026-10-06 11:33:44 -07:00
geramyloveless deae4a3615 CodeSync (selector 90): a code-object load's cache invalidate, without a launch
Each hsa_executable_load_agent_code_object invalidated the GPU's code
caches by running a ComputeDispatch of an s_endpgm kernel. That cost
9.8-10 ms on an idle R9700, and a new LSE pass width loads 55-60 code
objects. The dispatch did three things:
1. rt_compute_cache_sync: the compute ring's upstream ACQUIRE_MEM, which
   invalidates and writes back the instruction, scalar, vector, GL1 and
   GL2 caches, waited for on its fence.
2. A KFD queue created for the launch (MES ADD_QUEUE), the kernel kicked,
   and its completion polled in 1 ms sleeps.
3. The queue destroyed again (MES REMOVE_QUEUE).
Only the first is cache work. The GCR invalidates it issues reach the
caches every queue uses, which the old path already relied on, since its
launch ran on a queue of its own.

CodeSync runs only that: rt_compute_cache_sync with the caller's timeout,
as a session client's async call. It touches no client memory, so a ring
that does not finish in time is reported as ETIMEDOUT and left to the
ring's own timeout and recovery, without freezing the device.
DEXT_RUNTIME_BUILD becomes 258, from which the runtime uses it.

test-dext-compute-production code-sync: one cache sync and no launch,
the timeout bounds, and a sync that times out reported without freezing
the device.
2026-10-06 10:31:02 -07:00
geramyloveless 04ee55a519 SysfsWrite takes any observer client; every write is logged
The session-release entitlement is in Host.entitlements, but the signed
host app does not carry it: local signing with the approved profiles
leaves it out, in both the installed build and this one. Gating SysfsWrite
on it would refuse the menu's every write. Any process can already run
GPU work through a session client, so an observer client may make these
writes too. The allowlist bounds what can be set (four levels, a profile
index), and the driver logs each write with the client that made it.
2026-10-06 09:30:59 -07:00
geramyloveless 1912fd1e4e Menu bar: Performance controls, kept and set again whenever the GPU comes up
The menu bar's new Performance submenu has:
- Performance level (Auto, High, Peak, Low), which maps to
  power_dpm_force_performance_level (Peak is profile_peak).
- Power profile, listing every profile the card reports in
  pp_power_profile_mode except CUSTOM, which takes parameters. The list is
  read from the card, with friendly names for the known ones (Default,
  3D Fullscreen, Power Saving, Compute, ...).
- A live line with the current GFX and memory clocks, the temperature and
  the power, refreshed each second while the menu is open.
- A place for the runtime power-management modes still to come.

A choice is written at once through SysfsWrite and read back, then kept
in the display prefs (performanceLevel, and the profile by its card name).
A refused write is shown in the submenu, with the driver's reason, and
beeps. The display daemon writes the kept choices again whenever the GPU
comes up: when it opens the GPU (after a probe, a power cycle or an
upgrade) and after a reset that lost VRAM. A profile the card no longer
lists is an error that is shown, never a default. Nothing chosen means
nothing written, so the driver's Auto applies, as on Linux, since pinning
clocks costs idle power.

CLI: "MacLinuxGPUHost performance-level auto|high|peak|low",
"power-profile <name>" (a card name, menu title or index), and
"performance", which prints the current and kept settings and the live
line.

test-display-agent covers the levels and their sysfs spellings, parsing
the R9700's pp_power_profile_mode and the older one-line layout, profile
lookup, the live line, prefs persistence including files from before
these settings, and the reapply plan.
2026-10-06 09:27:35 -07:00
geramyloveless 79036bbc8f SysfsWrite: the performance level and power profile, through upstream's store()
On Linux, root writes power_dpm_force_performance_level and
pp_power_profile_mode, and amdgpu_pm.c's store() applies them. This
driver had no sysfs write path: its observer client only reads.

Selector 89 (SysfsWrite) takes an attribute id and a value and runs that
attribute's own store(), through linuxu_sysfs_write (as kernfs, one
store() of a NUL-terminated page). It is limited to:
- An allowlist in session_state.h: power_dpm_force_performance_level
  with auto, low, high or profile_peak, and pp_power_profile_mode with a
  bare profile index, 0-99. Manual, the other profile_* levels and custom
  profile parameters are not offered.
- Observer clients that carry the session-release entitlement, which is
  the host app's, as for Retire and the quarantine release.
- Synchronous and bounded on the observer reads' driver thread, never the
  delivery thread, with admission as for SysfsRead.
store()'s result comes back as the bytes taken or a negative Linux errno.
A value outside the allowlist is NotPermitted, a missing entitlement is
NotPrivileged, and a store() still running at 250 ms is Timeout.

Tests: test-sysfs-read writes through a device attribute's store(), and
checks the NUL-terminated buffer, store()'s own errno, and the read-only,
missing and empty cases. test-session-shutdown checks the observer
policy, that the call is synchronous but not on the delivery thread, the
paths, and the value allowlist (every offered level and index, with and
without a newline, and the levels, spellings and parameters it refuses).
2026-10-06 09:27:35 -07:00
geramyloveless f786e8cc0e A queue the CP stopped is a status, and a fault seen a moment later wins
On the R9700, the faulting process got HSA_STATUS_ERROR rather than
HSA_STATUS_ERROR_MEMORY_FAULT. The CP stops the queue and writes an error
code to its inactive signal before KFD's interrupt work signals the
process's memory event. The queue service took the code for a broken
scratch request and failed with -EIO, the selector answered
kIOReturnNotReady, and the runtime faulted the whole connection before
the fault report could arrive.

Now dext_kfd_queue_service returns -ENOEXEC with the code for a
non-scratch inactive value, and selector 59 answers kIOReturnIOError with
the code in output 1, which is an answer, not a failed call. The runtime
keeps polling such a queue for up to 250 ms. If the fault report
(kIOReturnVMError) arrives it reports the fault, address and reason as
before. Otherwise it reports HSA_STATUS_ERROR_EXCEPTION and prints the
code. Nothing waits in the driver.

test_dext_kfd checks the code is returned with -ENOEXEC. The
production test's kfd-fault-isolated scenario checks the stopped queue is
answered with the code without freezing the device, before the fault
itself arrives.
2026-10-06 09:20:08 -07:00
geramyloveless 0bf25fe71e A faulted queue left on the command processor is reset, not left to wedge
The fault repro on build 256 wedged compute twice. KFD evicted the
faulting process's queues, MES reported each removal done, and no removal
failure was logged. After the process closed, though, the CP wrote again
for the dead PASID, and from then on no launch of any new process
completed until a power cycle. A CP stalled on the faulting access keeps
running the queue on its HQD after MES lets it go.

The session now reads every compute HQD (kfd2kgd hqd_dump; the dump is
the register image of the compute MQD from cp_mqd_base_addr_lo, which
GFX 11 and 12 share). It does this when it first sees the fault, and
again at close before any queue is destroyed or any memory freed:
- An HQD still active with one of the session's queues, matched by MES
  doorbell and MQD address, is reset through MES's hung-queue reset (the
  session's existing queue_recover), and the HQDs are read again.
- A queue that survives that makes the session request a GPU reset
  (amdgpu_amdkfd_gpu_reset), record step RT_KFD_STEP_CP_STUCK and stay
  uncertain. A close keeps its memory, and no second reset is requested.
  A settle or close that finds the HQDs clear lets it go.
- HQDs that cannot be read are handled the same way. A removed device has
  nothing running.

The reported fault address is also fixed. KFD's GFX 11/12 handler shifts
the IH's page number, which counts 4 KiB GPU pages, by the CPU's
PAGE_SHIFT, so on linuxu's 16 KiB pages the address came out four times
too large (0x20001070000 for 0x800041c000 on the R9700). Arm64 Linux with
16 KiB pages has the same bug upstream. The session converts with
AMDGPU_GPU_PAGE_SHIFT.

The fixture now models this case. Its HQDs come from the CP model behind
hqd_dump. A faulted queue can stay on its HQD after MES removes it and
reports success, and then either MES's hung-queue reset or only a GPU
reset (which can be held back) takes it off. Its IH entries count 4 KiB
pages, as the hardware's do. test-kfd-session runs three cases while a
second client dispatches throughout:
1. Stuck through MES's removal: found when the fault is seen and cleared
   by the hung-queue reset, with no GPU reset.
2. Stuck through the hung-queue reset too: one GPU reset is requested,
   the close is refused while the reset is pending, and a settle then
   clears the session and the close succeeds.
3. Never polled before the program leaves: the close itself finds the
   queue and resets it first.
The ordinary fault case also asserts that the HQDs were read and were
clear, and that the reported address is the exact 4 KiB GPU page.
2026-10-06 09:20:00 -07:00
geramyloveless 6662021e46 Driver ABI build 256: the queue service reports GPU memory faults
The runtime asks AQLQueueService for the fault's flags and address (four
outputs) only from kQueueFaultDriverBuild (256) on. The driver now
reports that build in RuntimeBuild, so this runtime takes the new
answer, and older runtimes keep asking for two outputs.
2026-10-06 00:47:45 -07:00
geramyloveless 1ce2a2c272 A client's GPU page fault stays that client's: no quarantine, no lost GPU
A program that destroyed a completion signal while its dispatch was
still queued made the CP's signal write fault (gfxhub, client CPC, its
own PASID). The driver then quarantined the session and isolated the GPU
for every program until a power cycle. Upstream KFD had already done
what Linux does: its interrupt handler (kfd_int_process_v11) evicted the
faulting process's queues and signaled its memory events. The damage
came from the dext.

The faulting program's queues no longer ran, so the next program's
code-object load timed out in its cache-sync launch. That launch's queue
was destroyed cleanly through KFD, but dext_compute_dispatch froze the
device anyway, as for a DriverKit HQD, because the launch's kernel-ring
cache sync had been submitted. With the device frozen for a non-KFD
cause, every client release returned -EBUSY (-11006), the close
quarantined the session, and closing a quarantined session isolates PCI.
That isolation is what the log called "PCI transport fault 4: the GPU no
longer answers"; the GPU had not left the bus.

Now:
- A failed launch on a KFD queue no longer freezes the device. The cache
  sync is an upstream kernel-ring job that touches no client memory and is
  covered by the ring's own timeout and recovery. An unconfirmed queue
  destroy still freezes, scoped to KFD as before. DriverKit HQDs are
  unchanged.
- Each KFD session creates the memory-exception event libhsakmt creates
  (CREATE_EVENT, KFD_IOC_EVENT_MEMORY). rt_kfd_session_fault polls it
  without sleeping and keeps what KFD reported: address, not-present,
  read-only, no-execute, imprecise. A faulted session refuses kicks and
  new queues with -EFAULT, and its close is an ordinary close.
- AQLQueueService (59) answers status kIOReturnVMError for such a queue.
  With four outputs requested (build 256 on), it adds the fault flags and
  the faulting page's address. AQLQueueKick (57) answers kIOReturnVMError.
  Other clients and the display are not involved.
- Fault 4 is logged as the driver's own isolation of a quarantined session,
  and the device-lost line no longer claims the device stopped answering.

Tests:
- The KFD session fixture delivers UTCL2 faults the way the IH does,
  through kfd_int_process_v11's ISR and then its work handler on a
  workqueue. Its CP raises one itself, and stalls, when a completion
  signal it must write is unmapped. test-kfd-session: one client frees a
  signal and then runs the dispatch that names it, while another client
  dispatches throughout. KFD evicts exactly the faulting queue (one MES
  remove), the fault is reported and sticky, kicks fail with -EFAULT, the
  bystander keeps completing, and both closes are clean.
- test-dext-compute-production kfd-fault-isolated: a client's launch
  times out after its cache sync, and its queue then reports the fault,
  while a second client runs on. The device never freezes and both
  releases succeed. The scenario fails on the old freeze.
2026-10-06 00:45:31 -07:00
geramyloveless eb16490b9c PCIe: give amdgpu the port above the GPU's switch, so the link can leave Gen2
Host to VRAM copies on the R9700 behind a TB5 enclosure top out at
1.65 GB/s (1.83 GB/s back), whatever the engine, chunk size or number of
queues: the Gen2 x4 rate. IOPCIFamily shows why. The enclosure's
downstream port (8086:5786, Link Capabilities 16 GT/s x4) and the GPU's
switch upstream port (1002:1478) are linked at 5 GT/s x4.

amdgpu_device_partner_bandwidth walks pci_upstream_bridge() past the
dGPU's own switch ports and takes the platform's speed from the first
other port's Link Capabilities. Our pci_upstream_bridge() returned NULL,
so amdgpu_device_get_pcie_info took the platform speed as unknown and set
the platform mask to Gen1|Gen2, and the SMU's PCIe DPM table is clamped to
that: the link is held at 5 GT/s by policy, not by the hardware.

DriverKit gives no configuration access past the endpoint, but the
registry carries what IOPCIFamily read from each port. At Start the dext
reads vendor-id, device-id, IOPCIExpressCapabilities and
IOPCIExpressLinkCapabilities along its provider chain
(CopyProviderProperties), skips the AMD entries as upstream does, and
hands the first other port to the PCI shim
(linuxu_pci_set_upstream_partner). pci_upstream_bridge() then returns a
read-only stand-in for that port: vendor and device, and the PCIe
Capabilities and Link Capabilities registers through
pcie_capability_read_word/dword, so pcie_get_speed_cap,
pcie_get_width_cap and pci_pcie_type answer for it. Every configuration
access in the shim reaches the GPU endpoint whatever device it is given,
so the stand-in refuses all of them rather than read or write the GPU's
registers under the port's name. When the chain cannot be read, or has no
such port, the dext says so in its log and amdgpu keeps its Gen1/Gen2
default.

The other upstream callers stay as they were: the switch save/restore in
amdgpu_device_cache_switch_state requires an AMD downstream port above the
endpoint and returns on the stand-in's vendor, and
amdgpu_device_gpu_bandwidth falls back to the endpoint's own capability as
before.

test-pci-dext covers the stand-in: absent until set, the registry's
16 GT/s x4 reported instead of the endpoint's 32 GT/s x16, downstream
port type, no configuration reads or writes through it, cleared again.
Not yet run on hardware: it needs a dext build, and the check is
pp_dpm_pcie listing a 16 GT/s level and the host to VRAM rate rising past
1.65 GB/s.
2026-10-05 16:46:33 -07:00
geramyloveless bd6a89ec7a Selector 41 (GetReBARInfo) is retired
GetReBARInfo was never implemented. The dext answered NotReady from a
permanent stub, and the host build routed it to GPU op 9, the memory
usage query, which is the wrong operation. macOS sizes BARs at
enumeration and DriverKit cannot resize one, so the selector is now
Unsupported like the other retired methods. dext_compute_get_rebar is
removed, along with its power-admission entry and its not-ready check. A
read-only ReBAR capability report is separate work.
2026-10-05 16:46:33 -07:00
geramyloveless a6f59666d5 The driver's Stop and Retire never wait forever behind a session call
Stop and Retire run on the session queue, behind whatever session call
runs there. On 250 a CPU-access pin that had to evict a compute client's
buffers waited forever. The session queue stayed blocked, and the
instance lingered in "terminating for upgrade via delegate" until the
user killed it; it could neither stop nor hand over to the next version.

owner_job_main now records the running session call's selector and
start. When a Stop or Retire is asked for, a watchdog on a queue of its
own (one watch at a time) checks once a second until it runs. If a
session call has held the queue for MLG_SESSION_BLOCK_BOUND_MS (30 s),
it makes GPU work complete at once, as a removal does (rt_device_lost):
fences complete with -ECANCELED, the call returns, and the Stop or
Retire runs. The device is unusable for this instance from then on. The
session closes with it and the event names the selector that blocked.

session shutdown watchdog-never-returning:
- nothing is forced with no call running, or before the bound;
- past the bound the GPU work is forced once, even when asked twice, and
  the log names the call;
- a freed queue clears it;
- the driver's Stop starts a watch.
2026-10-05 16:46:33 -07:00
geramyloveless ca7bd1958a Top-down VRAM allocations stay top-down when the clear tree is empty
On the R9700, a compute process (LSE) held 245 of the 256 MiB CPU-visible
VRAM window while more than 13 GB of VRAM was free. That forced every
CPU-access allocation (a dumb framebuffer, a kernel BO) to evict it.

amdgpu's KFD VRAM BOs are VRAM_CLEARED and top-down. gpu_buddy's
alloc_from_freetree searches top-down only in the requested tree, the
clear one. When that tree has no block of the order, its fallback to the
dirty tree is a plain smallest-order scan that drops
GPU_BUDDY_TOPDOWN_ALLOCATION.

A diagnostic build logged every top-down allocation landing in the low
256 MiB. All of them had the clear flag and a clear tree holding 0-34
MiB, for example "620800 KiB at 0x1000000; clear_avail 19 MiB -> 5 MiB,
avail 30722 MiB".

patches/linux/gpu-buddy-topdown-fallback.patch makes the fallback search
the other tree top-down when top-down was asked for. Upstream's
dirty-tracker rework of the buddy allocator removes the separate trees;
drop the patch once the pin has it.

test-gpu-buddy: a clear top-down request with the clear tree empty takes
the highest free block (63 MiB of 64), not a low smaller-order one. The
pinned allocator, with both declared patches reversed, takes the low
block as a negative control.
2026-10-05 16:30:21 -07:00
geramyloveless 6cea0111c4 Asking for the host window never opens a KFD process
dext_compute_host_window looked the client's session up through
selected_session(), which decides it on first use. The first HostWindow
call (selector 54) of any session client therefore opened a KFD process
for it. That covered the display daemon, its mirroring child (both
--init) and every Linux-file (RADV) client, none of which computes
through the dext. Each display join created a full KFD process (VM init,
page tables, an eviction fence), and on a loaded device it allocated
under memory pressure.

HostWindow now uses only a session the client already has. Tag 12 or a
compute call decides one, and HSA asks tag 12 before 54, so its window
negotiation is unchanged. A client whose KFD open failed still gets that
error.

dext_compute production host-window-no-session: a client that only
brings the GPU up gets the GART window, stays undecided and opens no KFD
process. After tag 12 it gets its KFD window.
2026-10-05 16:30:21 -07:00
geramyloveless d9df9a3a17 Disconnect GPU closes the device for the programs on it
With the device kept up across programs (248), Disconnect GPU could no
longer bring the GPU down. Once the display daemon let go, the session
stayed up with or without programs. The menu bar said "still in use" for
any program with the driver open, even an observer such as mtopg, and
had no way to close the GPU for programs still using it.

- Retire gets a DISCONNECT op (session_state.h). It closes the session
  now through the normal close, as QUIESCE with FORCE does, whatever
  clients it has. Unlike QUIESCE it keeps admitting sessions, so the next
  program to start brings the GPU up again. A raw BAR mapping still
  refuses, since a close would quarantine. A quarantine is released only
  when provably quiescent, as for Retire. out[2] counts the clients that
  lose the GPU.
- The closed session's clients get kIOReturnNoDevice on every further
  call (session and Linux-file clients alike), and the driver log says
  once per client that the GPU was disconnected. They are never silently
  rejoined to a new session with stale state. HSA maps NoDevice to device
  lost and now says the GPU was disconnected and the program must
  restart.
- The menu bar and `disconnect-gpu` wait for the displays to stop. If the
  driver's session is still up, they close it with DISCONNECT. The GPU is
  safe to unplug once the session is closed, whatever programs still have
  the driver open. Those programs are named: they are told the GPU was
  disconnected if they use it.

Tests:
- session shutdown retire-disconnect: the session closes the normal way
  for every program with nothing refused, the old clients' generation is
  the disconnected one, the call reports IDLE once closed, and the next
  program opens a new session.
- retire-disconnect-raw-bar: refused, nothing changes.
- The observer policy admits the op.
- The display agent's readiness: safe with clients named, an open
  session means apps connected (even none), closing, and the messages.
2026-10-05 16:30:21 -07:00
geramyloveless fbc26b2b12 A transport fault names its caller and ends the session's waits
When a definite PCI transport fault is recorded, admission closes. From
then on nothing this driver waits for on the GPU completes. Fences,
eviction copies and MES requests all wait forever, and they hold the
session queue, which is also where the driver's Stop runs. The three 248
instances from today's hangs never exited after the GPU was power-cycled,
and the upgrade to 249 waited on them until the user killed them.

- The first fault logs where it came from: the frame-pointer return
  addresses above it and record_fault's own address, so atos places them
  in the dext binary. This is what named amdgpu_gmc_set_pte_pde. It runs
  only on that fault.
- dext_pci_set_fault_hook: the session layer reacts once, on the faulting
  thread. transport_lost calls rt_device_lost. That does what a removal
  does: the DRM device counts as unplugged, there is no hardware access,
  and every ring's fences are force-completed with -ECANCELED, now and
  from a thread every 5 ms. So no wait outlives the fault.
  Unlike a removal, the PCI device is not marked disconnected
  (rt_removal_active stays false), so what the GPU may still reach stays
  retained by the fault's DMA quarantine.
- With the GPU unreachable, the last client's leaving closes the session.
  The close quarantines, naming the PCI fault. When the device then
  leaves the bus, the removal releases the session and the driver stops.
  rt_removal_end also stops the lost device's thread, and a new session
  starts with s_deviceLost clear.

session shutdown transport-fault-removal: a fault while a program and the
display run, with one hook reaction even when it fires twice. The program
leaves, the close quarantines on the fault, the power cycle removes the
device, and the instance finishes and stops.
2026-10-05 16:30:21 -07:00
geramyloveless c282a82741 MMIO tokens live in their own address range; process memory is memory
The display's rejoin with LSE loaded knocked the GPU "off the bus" on 248
and 249. The new framebuffers' pin evicted LSE's VRAM, and the eviction's
SDMA copy maps its window through amdgpu_ttm_map_buffer. That calls
amdgpu_gart_map, and amdgpu_gmc_set_pte_pde writes the PTEs into the copy
job's IB, which is ordinary process memory, with writeq(). Linux allows
this. The DriverKit accessors decoded every address outside the BAR0
aperture as a synthetic token (address / 256 GB), so the IB at
0x127849020 became token 0, "a lost mapping". The first such write
recorded a definite MMIO transport fault, which closes PCI admission and
quarantines DMA. Upstream then reported "device lost from bus" with the
GPU still on it, and every client's work hung. The fault's call chain
(next commit) named the site.

The encoding also overlapped real memory in the other direction. A
process mapping above 256 GB decoded as a live token, and a store to it
went to that token's BAR.

Tokens now start at 2^48, above the arm64 user VA ceiling, where no
process memory can be. Token 0's range is never minted. Decoding means
"inside that range", nothing else. readX/writeX, memcpy_toio/fromio and
memset_io go to:
- the BAR0 aperture: the kernel, as before;
- the token range: MMIO for a live token, a loud fault for a stale or
  never-minted one;
- below 4 GB (__PAGEZERO, a null-based bug): a fault, as before;
- anything else: a plain load or store, ordered as Linux orders readX
  and writeX.

test_mmio_dk_accessors checks:
- a live register token goes to MMIO;
- PTE writes into an IB through amdgpu_gmc_set_pte_pde's own expression
  are plain stores, as are memset_io and memcpy_to/fromio on heap memory;
- a process mapping that the old scheme decoded as the live register
  token is plain memory;
- a stale token, token 0's range and a null-based address still fault
  and touch nothing.
2026-10-05 16:30:21 -07:00
geramyloveless cda0670cd9 Client records go with every client, and a missing session is an error
The compute backend keeps one record per runtime client in a fixed table
of 64, and client IDs are never reused. Records were cleared only when a
participant that was not the last one left. The last leaver's session
close, Linux-file clients, session clients that never joined, and the
records of a stopped session all kept theirs. After 64 clients over the
dext's lifetime, a new client got no record: its identity failed
silently, QueryInfo tag 12 said "not ready", HSA went on with the session
unreported on the legacy path, and queue creation failed with
OUT_OF_RESOURCES.

- Every Stop path forgets the client's record: session clients
  (participant or not, including the last leaver whose leaving closes
  the session), Linux-file clients and observers. A client outside the
  session that still owns a KFD process (opened by its QueryInfo)
  releases it. dext_compute_stop forgets every record with no KFD process
  left. A record whose KFD process could not be closed stays, and the log
  says so along with the record count.
- No record for a client is loud. Its identity failure is logged, its
  InitDevice fails with kIOReturnNoResources, and tag 12 fails with
  kIOReturnNoResources.
- A KFD process that cannot be opened on a device that supports KFD is
  that client's error on every compute call (tag 12, tag 10, BO alloc,
  import, queue create, host window). It no longer falls back to the
  legacy path, which may have no HQD at all. The open is not retried, and
  the log carries its errno.
- HSA: a driver that has tag 12 and gives no session fails hsa_init at
  that query, with a message naming it, instead of continuing on the
  legacy path into a queue OOM.

Tests:
- dext_compute production: client-churn runs 256 rounds of every client
  kind through join and leave, plus a kept KFD record; client-churn-close
  runs 256 last-leaver close-and-restart cycles; client-records-full
  checks the loud full-table path; kfd-open-failure now expects the error.
- session shutdown: client-churn drives every Stop path 256 times
  against a 64-record model; last-leaver-churn runs 256 closing last
  clients.
- HSA shim init: a refused or modeless tag 12 fails initialization.

client-churn-close fails on the 7c6afe9 backend at the 65th client, and
both session churn scenarios fail on the 7c6afe9 driver source.
2026-10-05 16:30:21 -07:00
geramyloveless b7370ef645 The GPU stays up across clients
The upstream driver was brought up per session and removed when its last
client left: every program started cold (a probe, about 2-3 s), and
while a session closed, new session clients were refused (the closing
window). Linux keeps amdgpu probed while programs open and close their
files.

Now the device is brought up on first use and stays up. A leaving client
releases only what it owned (dext_compute_release_client: its KFD
process, queues and BOs; a Linux-file client's process exits with its
files), and the next client joins the running device without opening PCI
or probing. The session closes only:
- at the driver's Stop, a device removal, Retire, or ShutdownGPU;
- when it is tainted (a client's release failed, or the GPU's state is
  uncertain), as before;
- when the last client leaves a session that must end with it: the device
  left the bus, a raw BAR mapping's revocation is not proved, the GPU was
  never brought up (what was set before the probe was that client's), or
  the client used the legacy (non-KFD) path, whose host window is the GART
  window placed in its own address space. On the iPad, Studio is that
  path's only client, and each launch places its window and probes again,
  as before. Concurrent legacy clients share the window as they did.

Tests (test-session-shutdown):
- client-exit-reopen: the only client leaves and finishes, nothing
  closes, and the next client joins without a PCI open or a probe.
- client-exit-unprobed, -release-failure, -raw-mapped, -legacy: the last
  client's leaving still closes the session in each case above.
- concurrent-clients: two HSA and two Linux-file programs join and leave
  in overlapping orders, one leaving while another joins, and a program
  starts after all left, with an observer attached; then 1000 rounds of
  two programs at a time. Nothing closes or blocks; the driver's Stop
  closes the device once.
- upgrade stops and surprise removals follow the new order: the clients
  finish, the driver's Stop or the removal closes.
The probe/remove cycles of test-session-cycles keep covering the close.
2026-10-05 16:30:21 -07:00
geramyloveless e317a1fb11 The device spec comes back as a versioned structure
QueryInfo tag 8 was never served by this driver (it declined with
kIOReturnNotReady), and the HSA runtime asked for it as 32 scalar
outputs, twice IOKit's limit, so mac_hsa_agent_get_device_spec always
declined.

The driver now answers tag 8 with a structure output, session_state.h's
struct mlg_device_spec (version 1, the bytes filled, a mask of the field
groups present). An async call gets it through OWNER_RESULT. Every field
is upstream's own:
- the GC geometry (gfx.config) and the KFD node's per-CU properties;
- the CUs, shader arrays and render backends upstream left active
  (gfx.cu_info, backend_enable_mask, num_rbs);
- on GC 12, the shader-array disable registers upstream reads for its
  own SA bitmap, read the same way without a GRBM select.
No register is written. A caller with less room than the structure gets
its first bytes, at least the header.

mac_hsa_agent_get_device_spec keeps its 32-word layout. A group the
driver does not report is zero. Words 23-27 (SH_MEM_CONFIG/BASES, the
shader-array config registers and GRBM_GFX_CNTL) stay zero, since
reading them needs a select, which is a register write. The CU bitmap
words carry two shader arrays for each of four engines. mac_hsa.h says
so.

Tests: test-device-topology checks rt_device_spec against upstream
state and register reads, including no register read off GC 12 or
without hardware access. test-dext-compute-production checks the
structure and its room. test-client-transports checks the HSA runtime
reading it through an owner call and OWNER_RESULT; before this change it
declined (0x1001).
2026-10-05 11:57:22 -07:00
geramyloveless 5a437c81cc HSA runtime: no abort at exit, and a clear status during a session close
Every LemonSeed Engine run on 246 aborted in exit() with "mutex lock
failed: Invalid argument". The runtime's static executable registry
outlived the transport's static mutex (added in 243 with the
session-call protocol check, ff324ff). Its destructor, run by
__cxa_finalize, freed each loaded executable's GPU buffer through the
connection, and the RPC locked the already-destroyed mutex. 242 had no
such mutex on that path. The runtime's process-wide state (registries,
agents, pools, allocations, signals, queues and their mutexes) is now
never destroyed: a client that exits without hsa_shut_down leaves the
GPU memory for the driver to reclaim when its connection closes with the
process. hsa_shut_down still tears everything down.

hsa_init while the driver closes a session failed with
HSA_STATUS_ERROR_INVALID_AGENT, because NewUserClient refuses session
clients then (kIOReturnNotAttached). The runtime now asks an observer
for the session state and:
- waits for a close in progress, bounded by MAC_HSA_SESSION_CLOSE_WAIT_MS
  (60 s by default), saying so on stderr;
- returns HSA_STATUS_ERROR_RESOURCE_BUSY for a close still running at the
  bound, or a retiring driver (an upgrade);
- returns HSA_STATUS_ERROR_FATAL at once for a session that will not
  close (quarantined, restart required, GPU wedged or removed).
hsa_status_string names HSA_STATUS_ERROR_RESOURCE_BUSY.

test-client-transports:
- runs the HSA runtime's IOKit transport, as a process of its own, with
  an executable and a queue loaded and no hsa_shut_down. Before this
  change it aborts in exit() with the same "mutex lock failed".
- runs hsa_init during a close that finishes (it waits), past the bound
  (busy), during a retire (busy) and with a quarantined session (lost).
2026-10-05 11:54:50 -07:00
geramyloveless 22b50726b0 Owner calls carry up to 16 scalar outputs
An async session call's completion holds 16 words: a 4-word header and
at most 12 scalar outputs. host/owner_call.h asked for no more than 12,
and the driver's owner_call capped the selector's outputs at 12. A
selector that answers more refused the call: QueryInfo's compute
topology (tag 10, 16 words) returned kIOReturnBadArgument. The HSA
runtime then never learned the driver's queue slots, fell back to one
queue, and refused the next hsa_queue_create with
HSA_STATUS_ERROR_OUT_OF_RESOURCES before calling the driver. LemonSeed
Engine's hrx creates several queues, so on build 245 its GPU backend
never came up and it ran on the CPU. Build 242 called QueryInfo
synchronously, with 16 outputs.

A caller may now ask for up to 16 scalars (IOKit's limit). Up to 12 come
inline in the completion as before. When there are more, the completion
carries their count and none of them, and OWNER_RESULT returns them
(n * 8 bytes), followed by any structure output. host/owner_call.h,
which the HSA runtime, the host app and libmlg_drm build from, and
scripts/mlg_owner_call.py fetch them so. The Python twin's IOReturn
constants for kIOReturnNotAttached and kIOReturnIPCError are corrected,
and it reports kIOReturnNoSpace by its own value.

test-client-transports (test-lx-transport before) now also runs the HSA
runtime's own IOKit transport, its sources unchanged, against the dext's
extracted dispatch. The GPU's session answers are those the installed
245 driver gave the runtime on an R9700, and each handler refuses a call
that asks for fewer scalars than it answers, as the driver's do. From a
cold GPU the runtime brings the device up (HostWindow, InitDevice), opens
the compute session and creates three MULTI queues with an error
callback, as hrx does. Before this change the second hsa_queue_create
fails with 0x1008 (OUT_OF_RESOURCES) after one queue, as on the
hardware. The test also checks owner_call.h's shapes: 16 scalars, 14
with a structure output, and a caller asking for fewer than a selector
answers getting the driver's refusal. test-owner-call covers the
driver's side of 16 scalars through OWNER_RESULT.
2026-10-05 11:10:24 -07:00
geramyloveless 1c9604f8d4 Merge feature/lx-transport-test (4fc7837) into display-c 2026-10-05 10:17:25 -07:00
geramyloveless 4fc7837142 Linux-file transport tested against the dext's own dispatch
test-lx-transport runs libmlg_drm's IOKit transport, its sources
unchanged, against the dext's Linux-file dispatch extracted from
MacLinuxGPUXcode.mm (ExternalMethod's delivery part, lx_external_method,
the owner calls), with only the Linux process behind it and DriverKit
mocked. A test kernel between them delivers every call on one delivery
thread and returns async completions as Mach messages to the library's
notification port. It fails as soon as an async call returns from the
driver answered with nothing left to complete it. Build 243's
LX_MMAP_COMMIT hang fails it ("selector 102 was called async and the
driver answered it on the call"); the loopback tests could not see it.
It covers the first open of an uninitialized GPU, sync and async ioctls
(inline and LX_RESULT replies), BO maps with LX_MMAP_COMMIT, munmap,
close and LX_SCANOUT, from four threads at once.

It found a second 243 regression: a Linux-file client's first open of a
GPU that is not up failed with ENODEV instead of initializing it. Since
the join moved off the delivery thread, its failure came back as the
open's result, while libmlg_drm initializes the GPU only on a transport
failure (the synchronous join's kIOReturnNotReady). The join's failure
is a transport failure again: its completion carries the IOReturn.

The driver also refuses (kIOReturnBadArgument) an async call of a
Linux-file selector it answers on the call, so a client that sends one
fails at once instead of waiting for good. A 243 library's
LX_MMAP_COMMIT, which it sends async, is then refused, and its mapping
works without it (the commit is optional).
2026-10-05 10:16:13 -07:00
geramyloveless 17d2ec6733 Owner calls never wait without a bound
An async session call waited for its completion as long as the driver
answered Ping, so a selector the driver serves synchronously, sent
async, hung its caller for good (build 243's LX_MMAP_COMMIT). Every
owner call now has a bound: 300 s for InitDevice, ShutdownGPU and
DrmSelftest, 120 s for the rest (mlg_owner_call_bound_ms; a timed call's
0 means the selector's bound). Past it the call returns kIOReturnTimeout
and says on stderr which selector got no completion. The driver bounds
every call well inside these; they only catch a completion that will
never come. scripts/mlg_owner_call.py has the same bounds, and
test-owner-call checks they match.

test-owner-call runs the plain call against a mock driver that answers
Ping and never completes: it times out within its bound, the longer one
for InitDevice, and says so.
2026-10-05 09:58:40 -07:00
geramyloveless 5c3141a727 The Linux-file client's synchronous selectors stay synchronous
From 243 libmlg_drm sends its session selectors through
mlg_selector_call_on, which makes every selector not listed as
synchronous an async owner call. LX_MMAP_COMMIT, which t_mmap calls
after mapping a BO, was not listed: it went out async, the driver's
Linux-file client answered it on the call as it always has and never
completed it, and the library waited for good (its Ping kept
succeeding). Every Vulkan client hung at its first BO map, in
vkCreateDevice.

mlg_call_is_synchronous now treats the Linux-file selectors (rt/lx_abi.h
96..105) as synchronous, except LX_IOCTL_ASYNC and LX_CALL_ASYNC, which
carry their own completion. test-selector-call checks those numbers
against lx_abi.h and that LX_MMAP_COMMIT goes synchronously to a 243
driver; with the range check removed it fails there.
2026-10-05 09:56:09 -07:00
geramyloveless 0dfa5384e5 Merge feature/leak-243 (0ee07c4) into display-c 2026-10-05 00:26:56 -07:00
geramyloveless 0ee07c4401 MMIO token numbers are renewed between sessions
Every DriverKit MMIO mapping takes a token number (1..511) that doubles
as its synthetic pointer. To keep a stale pointer from reaching a
different mapping, an unmapped number was never issued again, so each
session consumed about four for good: the register token, upstream's
register ioremap and the kernel doorbell kmap among them. After roughly
120 session open/close cycles none were left; the doorbell kmap failed
and the probe returned -ENOMEM (242: "kernel bo map failed",
quarantine, restart required).

The numbers are now renewed when the last mapping is unmapped. The
session's register token lives from dext_open to dext_close, so an empty
table means no session, no upstream module and no synthetic pointer
remain. Within a session an unmapped number is still never reissued.

test-session-cycles runs 300 session open/probe/close cycles through the
real upstream probe and the production PCI, MMIO-token and heap code
against a mock IOPCIDevice, and checks after every close that no MMIO
mapping survives and that heap, DART-mapped bytes and mappings, page
descriptors and threads are at their baseline. Before this change it
fails at cycle 255 with the probe returning -ENOMEM. The DriverKit token
bounds test also covers renewal and in-session non-reuse.
2026-10-05 00:25:22 -07:00