Its scanout waits on the same 200 ms flip deadline as
test-display-pipeline, which the runner's software GPU fixture misses.
It still runs on a developer Mac.
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.
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.
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.
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.
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.
The driver's own KMD (upstream amdgpu, KFD, TTM, DRM and the linuxu shims)
compiled with no optimization level: clang's -O0, apart from five objects
whose BUILD_BUG_ONs need folding. Every register access, fence, interrupt
and copy path ran unoptimized. Both the DriverKit library and the host
builds the offline tests link now use the flags Linux builds that code
with (CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE, CONFIG_FRAME_POINTER as arm64
has it): -O2 -fno-strict-aliasing -fno-strict-overflow
-fno-delete-null-pointer-checks -fno-common, frame pointers kept for crash
logs. -funsigned-char stays out: it changes char semantics, not code
generation, from what Apple's signed-char ABI has always run.
The DriverKit objects also turn off the printf-family and string-copy
builtins: at -O2 clang rewrites such calls into others (sprintf, strcpy,
strncpy, vsnprintf, fwrite) that the DriverKit runtime does not export.
The library's external references are then a subset of the -O0 build's.
The offline suite passes as before; three tests fail with and without this
change alike (rg is not installed here, and two sanitizer findings in
test-only code: test-debugfs-lifecycle, test-kmem-cache-lifecycle,
test-upstream-pci-failure).
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.
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.
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).
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.
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.
An async session call to a driver older than this protocol is answered
synchronously and never completed, so a client that awaited it would
wait forever (a new runtime in /usr/local/lib talking to a driver that
is not yet replaced, or whose activation failed).
RuntimeBuild's compiled build (DEXT_RUNTIME_BUILD) is now 243, the first
to serve session calls async (MLG_SESSION_CALLS_ASYNC_BUILD).
host/selector_call.h asks it once per connection
(mlg_selector_call_on) before the first async call and, against an older
driver, fails at once with kIOReturnUnsupported; the HSA runtime keeps
the answer per connection and forgets it on close, libmlg_drm per
process, and both say on stderr that the installed driver is older than
build 243. scripts/mlg_owner_call.py refuses such a driver when it
connects. The Linux-file path needs nothing: an older driver refuses
LX_CALL_ASYNC as an unknown selector at once.
test-selector-call runs selector_call.h against mock drivers: build 242
and a three-word RuntimeBuild fail at once with no async call, a driver
that does not answer is reported gone, a 243 driver gets the async call,
the protocol is asked once per connection, and calls that never sleep
stay synchronous.
DriverKit delivers every client's calls, and the driver's own Stop, on
one thread, and runs each under its target queue with a synchronous
dispatch. Session clients shared the owner's queue, and observers and
Linux-file clients hopped to it synchronously, so a session call that
slept there (a probe, an allocation that evicts, a fence wait, a session
close), or anything queued behind one, held every client; on a GPU that
stopped, forever (build 241).
Every client now has a queue of its own, and nothing on the delivery
thread waits for the owner's queue:
- Selectors that never sleep answer there: Ping, RuntimeBuild (from flags
the session queue publishes; the context is never touched), the cached
QueryInfo tags, the power query and the power wait's registration, and
OWNER_RESULT (88).
- Every other selector must be called with IOConnectCallAsync*: the call
returns at once with a token and runs on the owner's queue, in arrival
order, exactly as it ran there before; it completes with its IOReturn,
scalar outputs and structure output length, and OWNER_RESULT fetches the
structure output once. EVENT_WAIT keeps its own completion; a wait that
does not start completes at once with the reason. A synchronous call of
such a selector is refused (kIOReturnNotPermitted, logged once per
client).
- SysfsRead and DrmInfo stay synchronous but bounded: the read runs on a
wait-pool thread (rt_bounded_run, new) and the call waits at most
250 ms (kIOReturnTimeout; while one overruns, the next is kIOReturnBusy).
The observer's self-test, Retire and ReleaseQuarantine are async calls.
- A session client's Stop, and an observer's FinishStop, run on the owner's
queue after the client's queued calls. Linux-file clients join the
session on the owner's queue with their first open (LX_CALL_ASYNC),
and the first open's InitDevice and HostWindow are async calls.
- CopyClientMemoryForType no longer touches the session: BOMap makes the
BO's descriptor on the owner's queue and the mapping looks it up; the
raw BAR lease takes its own spinlock.
Clients: host/owner_call.h and host/selector_call.h (header-only) call a
selector as the driver serves it, synchronously or as an awaited async
call; the HSA runtime, the host app (callScalar, callStruct, callMethod)
and libmlg_drm use them, and scripts/mlg_owner_call.py does the same for
drm-selftest.py and display-test.py's initialization. A client older
than this driver fails at its first session call that can sleep, with
the reason in the driver log.
Tests: test-owner-call runs the production owner_call machinery
(extracted, DriverKit mocked) against a session call that sleeps: calls
return at once, cached queries and the power wait answer while it
sleeps, later calls queue in order, completions carry the right layout,
OWNER_RESULT once, BO memory is found without the session, and a hung
bounded read times out within its bound. test-bounded covers
rt_bounded_run on the real wait pool; test-session-shutdown checks the
selector rules and runs the Stop paths through the owner's queue.
b4d1555: an ALLOC1 xarray never hands out index 0 (the first syncobj got
handle 0). ec81985: no Linux-file request that can sleep runs on the
driver's incoming-call thread (per-client workers, LX_CALL_ASYNC 105, the
teardown thread), with its test in test-cs-selftest.
Conflicts: MacLinuxGPUXcode.mm keeps both the display gate's lock at Start
and the driver-start event. The installer files (MacLinuxGPUHostApp.swift,
activate.sh, build-installer-dmg.sh) stay as 56165a8 has them, which
already installs libmlg_drm and libdrm_mlg to /usr/local/lib; from
3e4651d only build-radv.sh, which adds /usr/local/lib as RADV's second
rpath after @loader_path.
On 241 a request that waited on a GPU ring that had stopped ran on the
one thread DriverKit delivers every client's calls on: every client froze,
and the driver could not take its own Stop after the GPU was powered off.
Every Linux-file request that can sleep now runs on a worker of the
client's process and completes through AsyncCompletion:
- mlg_lx_cmd_sleeps (lx_describe.c, shared by the client library and the
driver) names the few requests that provably do not sleep: VERSION,
GET_CAP, SET_CLIENT_CAP, the syncobj create, destroy, export, import,
reset, signal, timeline signal, query and eventfd requests, a syncobj
wait that only polls, and KFD GET_VERSION. Everything else is async,
AMDGPU_CS, INFO, GEM and context requests included.
- LX_IOCTL runs only those, through rt_lx_ioctl_nosleep; any other is
refused without running (kIOReturnNotPermitted) and logged with the
request and the process.
- LX_CALL_ASYNC (selector 105) runs open, close, mmap and munmap on a
worker; the synchronous selectors 96, 97, 101 and 103 are retired.
- A Linux-file client's Stop hands its process's exit to a thread of its
own (rt_lx_client_retire) instead of waiting for its calls on the
incoming-call thread; a session close waits for those exits
(rt_lx_retire_drain) before the driver goes. On an unplug the Stop has
already begun removal, which completes the GPU's fences, so the exits
finish.
- An async call holds one of MLG_LX_MAX_ASYNC slots until its result is
delivered: with the completion (the slot frees before it is sent) or by
LX_RESULT, whose result is in place before the completion goes out. The
client library keeps its calls within the limit, waiting on its own
thread. A worker still sending a completion holds no slot, so a call
queues for it instead of failing.
- The transport revision is MLG_LX_ABI 2: libmlg_drm's dylib
compatibility version, and the text MLG_LX_ABI_TAG in the library for
launchers to check. A client library older than this driver fails at
its first sleeping request or open, with the reason in the driver log.
Events reach the unified log; routine lines stay in the retained ring.
The dext logged every line through os_log, and nothing from it reached
the unified log in the boot where 241 hung (probably quarantined for
volume), so the hang's cause was lost with the dext. Now only events go
there, prefixed "mac.linuxgpu: EVENT ": driver start, probe outcome,
removal, quarantine and release, session close, DMA mapping failures,
printk at error level and above (ring timeouts among them), and the head
of a device coredump, which dev_coredumpm now logs before freeing it.
Read them with
log show --predicate 'eventMessage BEGINSWITH "mac.linuxgpu: EVENT"'
Tests: test_lx_files covers the table, the synchronous refusal, the
operations on workers, inline and fetched results and the new slot rules.
blocked_call_check (test-cs-selftest) blocks a client's AMDGPU_CS behind
amdgpu_sched_jobs submissions on a held compute engine and checks that
every call returns at once, the blocked client's non-sleeping request
runs and its sleeping one is refused synchronously, another client opens,
allocates and completes SDMA work, the blocked client's Stop returns at
once and its exit finishes when the engine runs, and, during the surprise
removal check, that removal ends a blocked submission and the client's
exit completes.
On 241 a GPU ring hung (no recovery), and the display agent's OUTPUT then
pinned a framebuffer: TTM evicted, the blit waited for an IB from a pool
whose fences never signal, with no timeout, on the call itself. That was
the driver's incoming-call thread, so every client froze with it, the
observer's reads and Linux-file calls included, and the driver could not
even take its own Stop after the GPU was powered off.
Every display op that can sleep (PROBE, SHOW, OFF, STATUS, MODES, IMPORT,
VERIFY, RELEASE, OUTPUT) now needs an async completion: the call takes the
display gate, queues the op on a wait-pool thread (rt_wait_pool, the
threads that already sleep for event waits) and returns at once with a
token. The thread runs the op, keeps its structure output for RESULT
(op 10, once) in a slot the op shares with the client (an op may end after
the client stopped), and completes the call with the token, the op's
IOReturn, its two scalars and its output length. A synchronous call of
one is refused; one while another runs is kIOReturnBusy.
PRESENT stays synchronous and never sleeps: it takes no display gate, and
rt_display_present and rt_display_stats take the display lock with
trylock, -EBUSY while an op holds it. The agent then carries that frame's
damage (moves as rectangles) to the next PRESENT and forgets its tile
hashes, so no later frame moves or skips rows the driver never drew.
A stopped client's imports and output are released on a pool thread once
the display gate is free (after any op of its own that is finishing).
The daemon skips a STATUS poll that finds the display busy instead of
closing its clients.
The host app's display calls are async: IOConnectCallAsyncMethod with a
notification port, the completion received on the calling thread (up to
60 s, then kIOReturnTimeout), and RESULT for the output.
test-display-async runs the production display_call machinery, extracted
from the dext source, with DriverKit mocked and an OUTPUT that never
finishes: the call returns at once, the op does not run on it, PRESENT
and another client are answered meanwhile, a second op is busy, a stop
waits for the op, the completion and RESULT (once) carry its result, and
a refused thread leaves the display free. With the op run on the call
(the 241 behaviour) it fails within 20 s instead of hanging.
Unplugging the GPU with the display live panicked the Mac on 239 and 240
(LLC bus error, NC write, in the dext). On 240 the panicked thread was in
an atomic commit powering the display down after the agent's framebuffers
were removed: dmub_srv_fb_cmd_execute, with dmub_rb_push_front having
stored the command into DMUB's inbox in VRAM one byte at a time through
the dext's user-space mapping of BAR0. The removal was already under way
(Stop, removal_main, the aperture gate set); the error is reported only
after the store has retired, so no check before a store can prevent it.
Register accesses, through the kernel's IOPCIDevice MemoryRead/Write, ran
in the same commit after the link went down and never faulted.
So every access to the VRAM aperture goes through the kernel:
rt/aperture.h's read/write/copy/fill route through ops the dext installs
with the PCI device (BAR0 MemoryRead/MemoryWrite 8 to 64 bits, BAR0's
index and size read once). linux/io.h's readX/writeX, memcpy_toio,
memcpy_fromio and memset_io, the 64-bit MMIO atomics and the string
functions (memcpy, memset, memmove, memcmp) route aperture addresses
through them; the gate still skips writes and reads all ones once the
device is known gone. The GART page table in VRAM, written with writeq on
every GTT bind, now goes this way too.
dmub_cmd.h's inline dmub_rb_push_front (a byte loop) and
dmub_rb_flush_pending (READ_ONCE) reach the inbox with plain pointer
accesses no shim can route. A declared compile intervention for
dmub_srv.c (rt/dmub_inbox.h) includes dmub_cmd.h first and redirects its
two calls to the same operations written with dmub_memcpy, as upstream's
dmub_rb_out_push_front copies. Upstream sources stay unchanged.
Offline proof: the CS fixture gives the driver VRAM only as a no-access
alias of its pages, reached through the aperture's ops; the host
library's upstream objects alias the string functions as the dext's do.
Any direct load or store through a kernel VRAM pointer now crashes the
offline tests. With the two DMUB helpers redirected, every test passes:
the display pipeline (with its removal check now on the fixture's real
aperture), scanout, surface import, CS selftest, KFD and the rest.
The DART has no fixed DMA budget (the platform's refusal is the limit,
logged), page descriptors grow with RAM, and kmemcheck is compiled only
in debug builds.
Conflicts, both sides kept: the shutdown hold still waits up to
DEXT_DMA_HOLD_DRAIN_MS for operations in flight, now without a budget
argument; test_iokit_dma keeps the in-flight hold, aperture gate and
large-mapping tests; the fence wait-any test keeps one 2 s bound.
kmemcheck painted canaries around every kmalloc and recorded it in a
table under a global lock, and checked both on kfree: a cost on every
allocation of the driver. It is a heap debugging aid, so it now
compiles only with DEBUG defined. A release build keeps a small header
(the payload's size for ksize, and the allocation to free) and goes
straight to the allocator: no canaries, no tracking, no lock.
kmemcheck_enabled() returns 0 and the checks find nothing.
km_clear_sensitive (the wipe in kfree_sensitive) is unchanged.
The define reaches only linuxu sources, never upstream objects: the
dext's linuxu objects include a generated build/gen/mlg_build_mode.h
that `make lib-dext DEBUG=1` fills in (rewritten only when the mode
changes, so they rebuild), and Xcode's Debug configuration defines
DEBUG=1 and passes it to that make. The host library the offline tests
link is always a debug build, and the tests whose leak or corruption
checks rely on kmemcheck build its sources with DEBUG=1.
make check-release builds lib-dext in release and fails if it carries
kmemcheck's symbols (scripts/check-release.sh, whose patterns are first
checked against a debug build), then runs test_kmem_release in both
modes: sizes, alignment, zeroing, ksize, kmemdup and caches behave the
same, and only the debug build reports a write past an object.
- drmMlgPlaceWindow (libdrm-mlg) places one frame: the window's content
and the monitor's screen in global points (CoreGraphics' space), the
output's mode and the image. A screen point is crtc/screen pixels, which
is the backing scale and the mode in one factor. A window that fills the
screen (or is in native full screen there) gets the primary plane;
otherwise an overlay plane at its rectangle in CRTC pixels, clipped to
the CRTC with the matching crop of the image on every edge. A window off
the monitor, or with less of it there than DC's 12-pixel smallest
viewport (which DC would grow without saying), gets nothing, with the
reason. No window or no screen keeps the old rules.
- LX_SCANOUT HIDE: the client's frames off the screen (the desktop back,
the overlay off) while it stays attached and keeps its overlay plane.
- The WSI (radv-macos-display-wsi.patch) reads the window at every
present, in global points, and uses drmMlgPlaceWindow. Off the monitor
it hides once, logs it, keeps the game running paced at the refresh
rate, and shows the frames again when the window comes back; going full
screen on the monitor when the window is elsewhere is gone. A place that
changed is checked with TEST before it is presented; a refusal names the
rectangles and the scale. A layer at another size than the images makes
presents VK_SUBOPTIMAL_KHR, so a resized window or a full-screen toggle
gets new images.
- Tests: test-mlg-place (1x and 2x, screens at any global position, full
screen, clipping on each edge and a corner, a scaled window clipped, off
the screen, the viewport minimum, modes, refusals); test-scanout (HIDE,
a cropped present after it, a crop past the framebuffer refused);
test-radv-scanout (suboptimal presents for a layer of another size).
Host to VRAM (what display frames cross PCIe as), VRAM to host and VRAM
to VRAM, on the transfer queue (SDMA; RADV offers it with
RADV_EXPERIMENTAL=transfer_queue) and the compute queue (a compute
shader copy), timed by GPU timestamps. make vk-copy-bench builds it
against the Vulkan loader; run it with VK_DRIVER_FILES naming the RADV
ICD. Every failing call is reported; nothing is measured in its place.
scripts/build-quake3e.sh (make quake3e) fetches Quake3e at a pinned
commit into build/quake3e/src and builds the client with the Vulkan
renderer only (no OpenGL renderer, so no way to the Apple GPU) and the
SDL2 it bundles for macOS, then checks that the binary loads SDL from
next to itself and links neither OpenGL nor MoltenVK. Game data is the
user's: baseq3 through fs_basepath.
tools/mlg-run runs a program so that it renders with RADV and the GPU
scans its frames out on the monitor the driver's display output drives,
whatever the program would pick: VK_DRIVER_FILES and VK_ICD_FILENAMES
name only RADV's ICD, SDL_VULKAN_LIBRARY the Khronos loader,
MLG_WSI_OUTPUT the output's connector (asked of the driver; --output
checks it) and MLG_WSI_MODE the mode, and SDL keeps full screen in a
window on its own screen. --quake3 adds Quake3e's renderer, vsync, mode
and window placement on the monitor's macOS display (CGDisplayBounds of
the display drmMlgConnectorDisplay finds). A missing ICD, loader, driver
or output is an error naming it; --dry-run prints the plan.
test-mlg-run checks the plan (plan.c): the environment, the Quake3e
settings full screen and windowed, with and without a macOS display, and
the refusals.
patches/mesa/radv-macos-display-wsi.patch: RADV advertises
VK_EXT_metal_surface and swapchains on the macOS platform, and presents
them through libdrm-mlg's drmMlgScanout on the driver's display output.
The images stay in VRAM as framebuffers of the primary node, with
modifiers the output's planes scan out; a present goes on the primary
plane in place of the desktop (the window fills its screen, or is not on
the monitor's screen) or on an overlay plane at the window's rectangle,
or where MLG_WSI_MODE says. MLG_WSI_OUTPUT names the output; without it
the surface reports no presentation support and nothing is presented
another way. FIFO, a syncobj per image signalled at its vblank; the
window is moved to the monitor's screen at swapchain creation; the last
swapchain gives the screen back to the desktop. Failures print the step
and errno and lose the surface.
scripts/build-radv.sh builds the macOS platform. test-radv-scanout runs
RADV on the fixture's display output: no support without MLG_WSI_OUTPUT,
a refused connector, capabilities, FIFO frames of tiled images on the
primary plane, the desktop given back, a windowed overlay.
- The device has a primary node, /dev/dri/card0, next to the render
node: open, stat, node types and names. Its files are never DRM master.
- xf86drmMode.h: resources, CRTCs, encoders, connectors (which never
probe), planes, object properties, properties, blobs and IN_FORMATS
iteration, and framebuffers (AddFB2 with modifiers, RmFB, CloseFB).
- drmMlgScanout: LX_SCANOUT for a primary-node descriptor of the
library. drmMlgConnectorDisplay finds the macOS display that stands for
a connector's monitor: the one with the vendor, model and serial number
the display agent gives a virtual display for that EDID
(drmMlgEdidIdentity computes them as the agent does).
- test-scanout: a libdrm-mlg client on the fixture's DCN 4.0.1 output
(scanout_fixture.c): the primary node without master and the driver's
modeset with it open, KMS queries, framebuffers of dma-buf imports, both
layers with flip syncobjs, held desktop frames, a scaled frame, the
mailbox under held vblanks, detach, admission, and the client's death.
- docs/macos-displays.md: section 4.
System Information builds a PCI GPU's entry from the IOPCIDevice merged
with the properties of its direct children, and properties a dext sets
with SetProperties() reach user space as top-level keys. The dext now
sets the keys it reads on its own service:
model the product name, from libdrm's table (Start)
VRAM,totalMB gmc.real_vram_size (after the probe)
ATY,EFIVersionB the VBIOS part number ("VBIOS Version")
rom-revision the VBIOS version string
so "Display" becomes "AMD Radeon AI Pro R9700" with its VRAM and VBIOS.
A device the table does not list gets no name; Metal and core-count keys
are not published because they would be false.
MacLinuxGPUDevice carries the rest of the identity (IDs, PCIe link, VRAM
type, CUs, ISA target, VBIOS details) and MacLinuxGPUDisplays the DRM
connectors with their monitors' EDID names and modes, updated by the
display operations and removed when the session closes. System
Information cannot list those monitors under this GPU (it only lists
IOFramebuffer kernel objects there), so MacLinuxGPUHost shows the GPU
with its monitors: "MacLinuxGPUHost device", and a GPU panel in its
window, both read from the IORegistry without a user client.
test-device-properties builds the property set with DriverKit container
substitutes, including every allocation failure; test-device-info checks
the host view.
PRESENT hands the frame to the output's worker and returns. The worker
copies the frame's damage (plus whatever the target buffer missed while
off screen) into one of three scanout buffers with SDMA, split in
64-row bands across both SDMA rings when a frame is a MiB or more, and
flips with a nonblocking atomic commit. The copy fences sit in the
buffer's reservation, so the commit waits for them on the GPU's
behalf (the implicit in-fence) and the CPU does not. The flip's
out-fence wakes the worker from the flip interrupt; no thread polls.
A frame that arrives while one is still waiting replaces it and their
damage adds up. Surfaces are reference counted so the worker's hold
outlives a RELEASE. Statistics (version 2) report frames received,
flipped and replaced, bytes and jobs, the worker's submit time, GPU
copy time, and capture-to-flip latency from the vblank timestamp.
PRESENT with no rectangle reads the statistics only.
test_display_pipeline brings up DM on the CS fixture with two SDMA
engines and a vblank thread that raises the HUBP flip interrupt.
When a Linux-file client finds the GPU not initialized, libmlg_drm calls
InitDevice itself, but without placing the host window first (selector
54), so compute start fails with gart status -19: the same gap 84b4002
closed for the host app and drm-selftest.py --init. A RADV or llama.cpp
process that is the first client hits it.
mlg_init_device (libmlg_drm/src/mlg_init.c) does what the HSA runtime
does: query the window size, reserve twice that much of the process's
address space, set the size-aligned base inside it, InitDevice, release
the reservation. A driver that refuses HostWindow from a Linux-file
client, or answers an unusable size, still gets InitDevice as before.
test_mlg_init checks the sequence against a fake user client, including
that the base set lies in the reservation and that it is released.
The dext admits HostWindow from Linux-file clients, next to InitDevice,
which it already admitted. Until a driver with that is installed, the
query is refused and initialization behaves as before.
MacLinuxGPUHost display-agent --dry-run [--once] [--interval ms] [--init]
follows the GPU's connected monitors through an observer client. It polls
the cached connector state (selector 84 STATUS) and, when the hotplug
epoch moves, probes, reads each connected monitor's mode list (MODES)
and EDID (sysfs), and prints the CGVirtualDisplay it would create, then
the add, update and remove changes against what it had. It creates no
display; without --dry-run it refuses.
The plan takes the identity and colour from the EDID: the monitor name
(else PNP ID and product), the PNP ID word as vendor, the product, the
serial (or a stable hash of the serial string), the CIE primaries and
white point. It takes the modes from the driver's list for the link:
progressive only, duplicates dropped, preferred first, and the largest
mode as max pixels. The size comes from the driver's display_info (else
the EDID's). hiDPI is 0. A monitor with no valid EDID or no progressive
mode is reported and skipped.
The model (report/modes/EDID decoding, the plan, the agent's changes)
moves to host/DisplayAgent.swift, Foundation only, which the Xcode
target now builds; test-display-agent compiles it with a test of its
own. docs/macos-displays.md records what of the frame path exists.
rt/surface.h: memory of another process that the platform mapped for the
device (a display agent's IOSurface, mapped by the dext's IODMACommand),
given as DMA segments, is imported the way Linux imports any foreign
buffer: an exporter whose sg_table carries those DMA addresses,
amdgpu_gem_prime_import() (an SG BO), pinned in GTT and bound in the
GART. rt_surface_copy() copies dirty rectangles from it into an amdgpu
VRAM buffer with the SDMA buffer functions on the TTM entity: one copy
packet per contiguous run (whole rows with equal pitches are one range),
up to 1024 packets per job, the last fence added to both buffers and
waited for with a bound. The CPU touches no pixel and no other copy
mechanism exists.
The provider's release runs exactly once, when the dma-buf is released:
after the BO is destroyed, which TTM delays until its fences signalled.
A failed import never runs it.
The DART layer gains imported mappings (linuxu_dart_import): charged to
the budget and live for containment while imported.
test-surface-import runs it on the CS fixture device, whose software
SDMA engine reads system memory through the GART table upstream filled
and faults on anything the DART does not map: a surface in three
separately allocated segments, a whole frame with differing pitches (360
row copies, one job), damage rectangles with clipping, 1100 rectangles
(two jobs), a band with equal pitches (one packet), refused imports and
destinations, and the release after the BO is gone.
Brings in feature/ipad-next (power and robust). The CS fixture keeps both
sides: the DART fault model, narrow BAR, held SDMA, TTM eviction checks and
self-test v2 counters from main, and the R9700 configuration, driver-stream
modeling and BAR memory for the loopback from the Vulkan work.
cs_fixture_bar_memory now maps only the CPU-visible part of VRAM, so a
narrowed BAR is honored. The README keeps main's sleep limitation and notes
that Vulkan has no presentation yet.
display-test.py drives selector 84 through an observer client:
probe [--edid] every connector with status, mode count, preferred
mode and EDID size; --edid reads each connected
EDID from sysfs (drm/cardN/cardN-<conn>/edid) and
decodes vendor, product, serial, name, size and
preferred timing
show [--connector NAME] [--pattern bars|white|gradient] [--seconds N]
the pattern on every connected output, or one;
with --seconds it is turned off afterwards, also on
Ctrl-C
off the recorded configuration restored
--init brings the GPU up through a session client held for the run (a
show then defaults to 30 seconds, since the session ends with the
script). Errors name the failing step's errno; nothing else is tried.
test-display-test runs it against a fake selector.
test-dm-offline now continues past dm_hw_init the way amdgpu_pci_probe
does: drm_dev_register(), with the PCI function as the DRM device's
parent and a client file opened like amdgpu_driver_open_kms opens one
(its VM with CPU page-table updates, a scheduler no job reaches, the
real amdgpu_driver_postclose_kms), so dumb buffers and framebuffers are
amdgpu's own.
Two connectors get a sink the way Linux emulates a monitor (forced on,
a synthetic EDID through drm_edid_override_set, as video=<conn>:e and
debugfs edid_override do): HDMI-A-1 with a CTA-861 HDMI block and DP-2
with a base block only; DP-1 and DP-3 stay empty. The test then checks:
- connector sysfs as Linux shows it under drm/card0: status unknown
before probing, connected/disconnected after, enabled, dpms, the mode
list and the EDID bytes;
- probe: status, mode count, EDID size and the 1920x1080@60 preferred
mode per connector;
- refusals: an unknown pattern (-EINVAL), an output with no sink and a
connector that does not exist (-ENOENT), each leaving nothing behind;
- show on one connector, then on the other, then on every connected
output (each on its own CRTC), with the pattern bytes in VRAM, an OTG
programmed with 2200x1125 totals and a HUBP scanning out the
framebuffer address;
- off: the recorded configuration restored (enabled=disabled, the OTG's
master enable cleared), and the session-close stop;
- drm_dev_unregister() removing the connector and glue directories.
The fixture runs no DMCUB firmware, so DMUB and power-gate waits time
out and a run takes about three minutes.
llama.cpp is the first application of the Vulkan path. third_party/llama.cpp
pins b11379 as an optional, unpatched upstream (sparse, update = none);
scripts/bootstrap.sh --llama-only fetches it and verify-upstream.py checks
it once checked out.
scripts/build-llama-vulkan.sh (make llama-vulkan) builds it with
GGML_VULKAN against the Vulkan loader (Homebrew's or the LunarG SDK's),
Metal, BLAS and libcurl off, into build/llama.cpp/bin: llama-bench,
llama-completion and test-backend-ops. Its shaders need shaderc's glslc.
scripts/llama-radv.sh runs any program with the loader pointed at the RADV
ICD alone, so a MoltenVK installation is not used.
test-llama-offline brings the CS fixture device up inside llama.cpp's own
test-backend-ops (vulkan/tests/fixture_preload.c, inserted through
MLG_PRELOAD) so its Vulkan backend runs on RADV on the software GPU:
llama.cpp lists the R9700, and in performance mode ADD and the Q4_0/Q4_K
matrix multiplications of a feed-forward layer (matrix-vector and
matrix-matrix pipelines) are compiled by ACO, allocated, submitted and
fenced. It skips unless RADV and llama.cpp are built.
scripts/build-radv.sh (make radv) builds RADV from third_party/mesa on
libdrm-mlg: Meson with the ACO compiler and no LLVM, no window-system
platform (headless WSI), no GL, video, zstd or SPIRV-Tools, so the driver
links only the system and libdrm-mlg. It installs a relocatable ICD into
build/radv/install (libvulkan_radeon.dylib, libdrm_mlg.dylib,
libmlg_drm.dylib, share/vulkan/icd.d/radeon_icd.json with a relative
library path) and fails if any symbol other than the weak layer
entrypoints is left unresolved. Mesa's Python generators get a virtualenv
when python3 lacks mako, PyYAML or packaging.
test-radv-offline (vulkan/tests/test_radv_offline.c) loads the ICD as the
loader does and runs it on the CS fixture device through libdrm-mlg and
the loopback transport, against unmodified upstream DRM/amdgpu: instance
and enumeration ("AMD Radeon AI Pro R9700 (RADV GFX1201)", Vulkan 1.4, PCI
bus info), device creation, host-visible memory, an empty submit with a
fence, vkCmdFillBuffer and vkCmdUpdateBuffer executed by the software GPU
and checked through the mapping, a compute pipeline compiled by ACO, and a
dispatch submitted with a timeline semaphore and a fence (the software GPU
runs no shaders, so its result is not checked). It skips when RADV has not
been built.
third_party/mesa is Mesa at mesa-26.2.4, the latest stable release,
declared in patches/manifest.json as an optional upstream: a shallow,
partial, sparse submodule of what a RADV-only Meson build reads (about
60 MB), marked update = none so a recursive clone does not fetch it. Only
the Vulkan build needs it; scripts/bootstrap.sh --with-mesa fetches it
with the rest, --mesa-only alone, and once checked out it is kept at the
pin and patched like the Linux tree.
The patch set, 88 lines added and 9 removed in 8 files:
- radv-macos-build.patch: find libdrm through pkg-config on Darwin when
RADV is built, select addrlib's portable type definitions instead of
the Apple kernel driver's private header, and link RADV with
-undefined dynamic_lookup as KosmicKrisp does.
- drm-file-ops.patch: util/os_drm.h issues requests through drmIoctl and
wraps open, stat, mmap and munmap of DRM nodes and files in libdrm's
drmFile* functions when libdrm defines LIBDRM_FILE_OPS; RADV's six call
sites use the wrappers. Nothing changes for a kernel libdrm.
bootstrap.sh sets up any manifest upstream the same way now (pin fetched
by SHA, sparse before the first checkout, declared patches applied).
verify-upstream.py checks Mesa's pin, sparse set, patches and working tree
once it is checked out, and takes --only linux|mesa; lib-dext verifies the
Linux tree alone (make verify-linux), so local Mesa work cannot block a
driver build, while make verify-source checks every tree.
Mesa's amdgpu drivers reach the kernel through libdrm's core API, through
libdrm_amdgpu (devices, buffers, GPU virtual address ranges) and through a
few system calls on the DRM descriptors. libmlg_drm/libdrm provides the
part of xf86drm.h, amdgpu.h and libsync.h they use, over libmlg_drm, with
libdrm's names, types and return conventions, so RADV's stock amdgpu
winsys and Mesa's native ac_linux_drm path build and run unchanged.
The driver's files live in the dext's per-client Linux process. Each one
the library hands out (an opened render node, and every syncobj,
sync_file and dma-buf descriptor a request returns) is represented by one
end of a socket pair, the library keeping the other end: close, dup,
fcntl and fork work on it as on any descriptor, and when the last copy is
closed a watcher thread sees end-of-file and closes the driver's file, the
lifetime a kernel file has. Requests carrying descriptors are translated
both ways, with O_CLOEXEC in Linux's value. drmFileOpen, drmFileStat,
drmFileMmap and drmFileMunmap, declared under LIBDRM_FILE_OPS, stand in
for the system calls that cannot reach the driver. sync_wait and
sync_merge work through temporary syncobjs of an open render node.
The amdgpu part follows libdrm_amdgpu (MIT), from which its VA manager
and buffer handling are derived: device deduplication, the PRT half-range
reservation, dma-buf import by GEM_OP rather than lseek, no userptr.
LIBDRM_MLG_DEBUG=1 reports refused requests and descriptor lifetimes.
make libdrm-mlg installs build/libdrm-mlg with the uapi headers as the
kernel installs them and libdrm.pc and libdrm_amdgpu.pc for Meson.
test-libdrm-mlg runs it end to end against the CS fixture device. The
Makefile's depfile search now skips the Meson and CMake trees the Vulkan
builds will put under build/.
The runtime now follows the driver's device power state.
While the device is suspending, suspended or resuming the driver
refuses GPU work with kIOReturnOffline, having submitted nothing. The
IOKit transport returns that as HSA_STATUS_ERROR_RESOURCE_BUSY and
keeps the session healthy instead of faulting it. A queue whose
doorbell is refused keeps the highest value rung (its packets are in
the ring already); its service thread polls gently and rings it again
once the device takes work, so a generation in flight pauses and
continues. Allocations, transfers, queue creation and bounded launches
fail with the same retryable status.
Once a host sleep has closed the session the device's memory is gone:
queue error callbacks and the power API report HSA_STATUS_ERROR_FATAL,
which a client takes as "reload": release everything, hsa_shut_down,
hsa_init (the next initialization probes the device afresh), load
again.
mac_hsa_power.h, included by mac_hsa.h, gives clients the agent's power
state (state, generation, flags with VRAM preserved, cause, counters,
queues holding a doorbell); mac_hsa_agent_prepare_low_power, which
stops ringing this process's doorbells, waits a bounded time for the
packets already rung to finish, and asks the driver to quiesce;
mac_hsa_agent_resume, which drops the request and rings what waited;
and a bounded wait for the next power change. The iPad app calls
prepare on willResignActive and resume on didBecomeActive; neither is
needed for correctness, since the driver handles sleep itself.
The fake transport models the driver's power state for the new host
test, which covers paused and replayed doorbells (by the service and
by resume), retryable refusals, prepare and resume, waiting for a
change, and lost memory reported to a queue's error callback. A
transport test covers the IOKit status mapping. The runtime's copy of
the protocol names its state enum PowerState, which no longer collides
with the snapshot's State word.
The driver now handles DriverKit's power changes and gives clients a
power state, a way to ask for low power, and a way to wait for changes.
SetPowerState(Low), the device in a reduced power state while the
system runs, and a client's PowerControl PREPARE quiesce the compute
session through upstream KFD suspend (rt/power.h): every user queue off
MES with its work saved, VRAM untouched. RESUME by the last holder, or
SetPowerState(On), resumes it through upstream KFD resume and the saved
work continues.
SetPowerState(Off), system sleep, takes the Thunderbolt link and with
it the endpoint's state; VRAM cannot survive it on these hosts, and
upstream's only dGPU path evicts all of VRAM to system memory through
SDMA, which neither fits on the iPad nor is safe over the link. The
driver closes the compute session through its ordinary close path
before acknowledging the change; the acknowledgement waits for the close
on the default queue, with a watcher that acknowledges at a deadline so
a stuck close never stalls the sleep. On wake the state is lost if a
session was closed, and the next InitDevice probes afresh and makes it
active again. A quiesced session closes as it is, its queues already
off MES; the KFD suspend is handed back before upstream removal takes
its own, so upstream's suspend count stays balanced across sessions.
A failed quiesce or resume hands the suspend back, so MES maps the
queues again and the close removes them through MES; a GPU that cannot
prove itself idle leaves the session to the existing quarantine rather
than freeing memory it may use.
Clients see state, generation, flags (VRAM preserved among them),
cause, error and counters through QueryInfo tag "LPWR" (observers too)
and the PowerControl selector 83: QUERY, PREPARE, RESUME and an async
WAIT completing at the next generation change. While suspending,
suspended or resuming, selectors that would put work on the GPU are
refused with kIOReturnOffline, which a client retries after resume;
frees, queue destruction and cached queries stay available. A closing
client's waits end and its hold is dropped. Observers may request
transitions only with the session-release entitlement.
power_state.h holds the state machine, the snapshot, the admission
policy and the plan each event leads to, with a host test that also
checks the runtime's copy of the protocol. The session shutdown test
covers the removal hook and the observer policy for the new tag and
selector, and read-driver-log.py prints the power state.
A low-power period that keeps VRAM needs every user queue off the GPU
with its work saved, and the same queues back afterwards. Upstream
amdgpu has no suspend flavour for a discrete GPU that keeps VRAM: S3,
s2idle and BACO/BAMACO runtime PM all run amdgpu_device_prepare and
amdgpu_device_suspend, which evict all of VRAM to system memory through
TTM and SDMA. What it does offer without touching VRAM is the KFD half
of those paths, amdgpu_amdkfd_suspend(adev, true), which on a dGPU is
kgd2kfd_suspend(kfd, true): every KFD process's queues are evicted
through MES (waves saved through CWSR), eviction fences are signaled,
new processes are held off, and the queue managers stop. Its pair,
kgd2kfd_resume(kfd, true), restores the processes' buffers in place and
maps the queues back.
rt/power.h wraps exactly those two calls for the dext and reads
upstream's own state around them: the queue lists, the queue managers'
scheduling flag, and the reset mark kfd_hws_hang() leaves when MES fails
a removal. A failed MES removal is reported as -EIO even though upstream
marks the queue inactive before asking MES, so a queue the GPU may still
be running is never mistaken for a quiesced one. Upstream counts
suspends, so the module keeps its own suspend until it is resumed.
The new fixture test drives both entry points from the unmodified
kfd_device.c over the KFD session fixture: a suspend unmaps the queue
and holds new processes off, work published meanwhile waits, the resume
maps the same queue back and the work runs, a session closed while
suspended issues no MES operation and the resume that follows lets KFD
take processes again, and an injected MES removal failure is reported.
The fixture gains a process restore that replaces the eviction fence as
upstream does, MES removal failure injection, a non-fatal
kfd_hws_hang() reset request after an injected failure, and the SMI
event list kfd_init_node sets up.
Finds the Linux-shim driver by its user class and the RuntimeBuild
handshake instead of one bundle ID, so the iPad app's embedded driver
works, and builds the runtime as a static library for iOS.
Adds the Linux file RPC (user client type 2) that carries DRM and KFD
ioctls with Linux numbering, libmlg_drm for clients, the in-dext command
submission self-test, and fixes the DRM_COMMAND_BASE override in the
linuxu drm.h.
The runtime only accepted the Linux-shim driver under the macOS host app's
bundle identifier, so the same dext embedded in an iPad app (which DriverKit
requires to carry the app's own identifier prefix) was never discovered.
Recognize the shim by its MacLinuxGPU user class under any identifier; the
RuntimeBuild handshake (magic and ABI) already runs before the session is
claimed, so a foreign service sharing the class name is rejected there. The
converted protocol has no such handshake and stays bound to its original
identifier. Tests cover both identifiers and a failed handshake.
Build the runtime for iOS/iPadOS (make hsa-ios): a static archive, since an
app cannot load a runtime from outside its bundle. The iOS SDK withholds
<mach/mach_vm.h>, so the host-window reservations use the equivalent 64-bit
vm_map calls there, and the firmware servicer defaults to the firmware
directory inside the app bundle unless MAC_LINUXGPU_FIRMWARE_ROOT is set.
macOS behaviour is unchanged.
User-client type 2 (MLG_USER_CLIENT_LINUX_FILE) is a Linux process of
its own: LX_OPEN, LX_CLOSE, LX_IOCTL, LX_IOCTL_ASYNC, LX_RESULT, LX_MMAP,
LX_MMAP_COMMIT and LX_MUNMAP (selectors 96-103, rt/lx_abi.h) run its
system calls through lx_files on the client's own dispatch queue, so no
call waits behind another client's. Request frames arrive as structure
input or, above 4096 bytes, as a descriptor; replies go back the same
way. Waits run on workers of the process and complete through
AsyncCompletion with the reply inline when it fits. LX_MMAP memory types
resolve in CopyClientMemoryForType to the buffer's page runs or to BAR
sub-ranges (CPU-visible VRAM, doorbells). Ping, RuntimeBuild, QueryInfo
and InitDevice hop to the owner's queue as observers' calls do; nothing
else of the MacAMDGPU ABI is offered to this type, and types 0 and 1
are unchanged.
The client joins the session at its first call, as a session client
does. Its calls are admitted only while the upstream driver runs; a
session close or quarantine closes the admission, waits for calls in
flight, and makes every client process exit (waits return, files close
through upstream postclose) before anything is removed. A client's Stop
does the same for its own process on its queue, then leaves the session
on the owner's queue.
Observer selector 82 (DrmSelfTest, confirmed with "CSST") runs the CS
self-test and returns its result; one test at a time. A test whose GPU
work never completed keeps its process; a session close reaps it once
idle or quarantines with compute uncertain. scripts/drm-selftest.py runs
it on hardware.