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.
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.
Build 262 copies every system-pages/VRAM range through TTM's GART windows.
Bulk copies went 3.0 -> 6.3-6.5 GB/s on hardware, but small ones got
slower: the windows add a mapping job before the copy (4 KiB 108 -> 126 us,
64 KiB 121 -> 138 us). From 256 KiB a copy takes the windows (1 MiB
380 -> 282 us); below it, the staging buffer's single SDMA job, whose CPU
copy is now fast. RT_KFD_WINDOW_MIN_BYTES; the offline test sets it to 1
so it exercises the windows with small buffers.
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.
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.
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.
- 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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).
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).
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).
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.
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.
Build 242's host started display ops without a structure output, and the
driver refused PROBE, SHOW, OFF, STATUS and MODES for it; the test of the
driver's side offered 4096 bytes in every mocked call, so nothing showed
it.
The start of a display op moves into host/display_call.h
(mlg_display_call_start), which the host app calls: an async call of the
display selector carrying MLG_DISPLAY_REPORT_MAX bytes of structure
output, every op's largest. test-display-async builds that header with
IOConnectCallAsyncMethod replaced by a capture, hands the driver's own
display_call what the kernel would (scalars, structure input, output
capacity, completion) for every op that can sleep, and requires each to
be accepted and completed; the same call without an output capacity is
refused. With the header passing no output the test fails.
An instance that publishes MacLinuxGPUSessionCalls = "async" but never
completes a Retire would hold the upgrade, and the observer client the
instance waits on, for as long as it answers Ping. Retire now waits at
most 60 s (mlg_owner_call_timed, new in host/owner_call.h: the same wait
with a deadline, kIOReturnTimeout past it; a late completion is dropped
with the call's port). The installer reports which op timed out on which
instance.
test-owner-call also runs the host header against a driver that answers
Ping and never completes: the timed call returns kIOReturnTimeout on
time, and a driver that stops answering Ping ends an untimed wait.
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.
With amdgpu_gpu_recovery off, a job on a hung ring never completed and
every wait on it lasted forever (build 241). Recovery is now upstream's
default: a job that times out resets its queue (amdgpu_job_timedout ->
ring->funcs->reset: a MES queue reset for compute and gfx, an SDMA queue
reset), the guilty job's fence gets -ETIME, its context reports the reset
(AMDGPU_CTX_QUERY2_FLAGS_RESET) and refuses further work, and the work
queued behind it from other contexts runs.
A device reset (mode1 on gfx12, after a failed queue reset, on a ring
without one, or requested by KFD or a user queue) needs platform work not
done yet over Thunderbolt: the PCI configuration's restore with its BARs,
MSI-X, client BAR mappings in the reset window. Until then
(rt_recovery_full_reset_available), rt/recovery.h turns every request for
one into what Linux ends in when a reset fails: the device wedges. The DRM
device is unplugged (new requests fail with -ENODEV), hardware access and
bus mastering stop, every ring's fences complete with -ECANCELED and keep
completing, and KFD's waiters get its reset event. Nothing waits forever
and nothing loops on resets.
rt_recovery_attach hooks this in after the probe without changing
upstream: each scheduler's timeout handler and each queue reset are
wrapped (upstream's run unchanged inside; every recovery handler runs on
the reset domain's one ordered queue), and the KFD and user-queue reset
works are redirected to the wedge. Each queue reset that succeeds, and
the wedge, advance a reset generation. The driver publishes it as
QueryInfo "LRST" (generation, wedged and VRAM-lost flags, queue resets,
VRAM-lost counter, last result), sets MLG_SESSION_FLAG_GPU_WEDGED in the
session state, logs both as unified-log events, and the host app and
read-driver-log.py say to power-cycle the GPU when it is wedged.
The CS fixture resets queues as MES does (fx_ring_reset, with a ring test
that runs on the engine). queue_reset_check hangs a compute job: the
timeout fires, the queue resets without a device reset, another
process's job behind it runs, the guilty context reports the reset and
refuses work, a new context works and the generation advances.
wedge_check (a process of its own) makes the queue reset fail: the device
wedges, blocked work and a wait with no deadline end, new requests fail
with -ENODEV, and no device reset is tried. ttm_evict_check's stalled
move now ends with an SDMA queue reset.
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.
The Linux-file client libraries speak the driver's RPC, so they must match
the installed driver; folders that bundle their own copies (RADV for
llama.cpp, mlg-run) broke whenever the driver's transport changed. The app
now carries them in Contents/Resources/Runtime with the HSA runtime and
installs them to /usr/local/lib with the same staging, signature and team
checks and rollback; activate.sh --install-hsa builds and installs them
too, and the disk image checks them. RADV's install gets /usr/local/lib as
a second rpath after @loader_path, so a tree without its own copy loads
the driver's.
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.
The Linux-file client library (libmlg_drm) and the libdrm over it
(libdrm_mlg, which RADV and other DRM clients load) now ship in the app's
runtime payload, signed by the team like the HSA runtime, and the
installer puts them in /Library/MacAMDGPU/runtime and /usr/local/lib in
the same transaction (staged, backed up, restored on failure), so local
apps pick up the libraries that match the driver on every update. Both
have @rpath install names, as before. activate.sh --install-hsa builds
them (make libdrm-mlg); the DMG check and the installer's validation
accept and verify exactly these files.
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.
llama.cpp: graph inputs queued in the Vulkan stream with no empty submits
(3dc1b9a), and the patch measuring where host copies leave the compute
stream (37aa287): the patch files and their manifest.
The DART layer refused any mapping past a hard-coded 1.5 GiB of live
DMA bytes. Every dext page is DMA-backed, so GTT objects failed with
ENOMEM at 1439 MiB (97 MiB already mapped at start) although amdgpu
reports 64 GiB of GTT; llama.cpp's 1 GiB staging buffer and pinned host
buffers could not be allocated.
The limits that exist are the platform's: memory and wiring (the user
wire limit here is 108.8 GiB of 128 GiB, with 19.2 GiB kept for the
kernel), and the DART's IOVA window for the device, which the device
tree gives a Thunderbolt port's dart-apciec as 2047 MiB (IOVAs from
2 GiB). DriverKit enforces both: IOBufferMemoryDescriptor::Create or
PrepareForDMA fails. So:
- dart.c only accounts live-mapped bytes (used/peak); a mapping fails
when the seam fails it. linuxu_dart_budget and rt_dart_ceiling are
gone (rt_dart_peak reports the high-water mark).
- The seam logs each refusal with its size, the refusing call, its
IOReturn and what is already mapped (a run of identical refusals
logs its first and every 256th).
- The shutdown and probe holds take no ceiling. They count the bytes
mapped at their start and those mapped during them; retired mappings
keep their DART IOVA until the endpoint reset, so the DART refuses a
teardown mapping that would not fit beside them. A ceiling at the
live total would refuse every probe allocation (nothing is mapped
when the probe hold starts).
- The dext's mapping table and dart.c's streaming slots were fixed at
4096 entries, another wall: both grow in chunks that never move.
test_iokit_dma models the DART window and adds large mappings: a
1.5 GiB + 16 KiB mapping, a refused 512 MiB one (logged), 4500 live
mappings, and a teardown mapping refused beside retired ones under
the shutdown hold. test_session_shutdown closes a session with 6 GiB
mapped. test_dma_dart maps 3 GiB and 6000 live mappings.
The page pool was fixed at 131072 descriptors (2 GiB of 16 KiB pages),
sized for a 1.5 GiB DART budget test. Descriptors now come in chunks of
16384 pages as allocations need them, for at most hw.memsize in pages.
A chunk never moves, so struct page pointers stay valid; the chunk
array is sized once for the maximum, so lockless readers (page_address)
index it safely. In the dext the VA lookup is rebuilt as chunks are
added. A block lies within one chunk; orders above a chunk fail, as
Linux cannot give that much contiguous memory either.
What bounds pages now is the platform: in the dext each non-CPU page is
DMA-mapped, so the DART refuses first (logged by the seam); CPU-only
pages are bounded by RAM. test_page_alloc holds 2176 MiB of pages at
once. Host builds of DriverKit-mode sources get IOSysCtlByName from
linuxu/tests/iosysctl_host.c.
Each request to the GPU is a round trip to the driver process, and
llama.cpp's Vulkan backend made about thirty per decoded token outside
the graph itself: every graph input was written with a blocking
set_tensor (a submission, a fence wait and a reset each, since no VRAM
is CPU-visible on Apple silicon), and ggml_vk_synchronize signalled its
fence with an empty submission, which RADV turns into eight syncobj
requests when it also waits for the transfer queue.
patches/llama.cpp/sched-staged-inputs.patch adds an optional backend
function that queues a write of host data after the backend's pending
work and copies the data before it returns; the scheduler uses it for
user inputs. Vulkan stages the data in host memory owned by the
backend context and copies it in the compute stream. The fence goes
with the last compute submission, transfer-only work is waited for on
the host, and small host copies stay in the compute stream. The new
test-backend-sched-inputs checks that inputs are taken when the graph
is queued and ordered against the device's queued work.
bootstrap.sh gains --reset-llama and removes the files patches add
when it resets a tree; verify-upstream.py accepts patches that add
files.
A trivial request costs about 27 us through the installed driver, of
which an IOKit call into the Linux-file client accounts for 9.5 us,
and AMDGPU_CS 60 to 100 us, but the same requests take 1 us and 25 us
in the host build. To see where the dext spends the rest, the user
client and lx_files.c now time every hop of a request: admission,
argument setup, frame check and copy, argument pages, copy in,
entering the Linux process, the ioctl, leaving, copy out, page
release, and the reply; for waits, the time until the worker starts.
The device's sysfs file mlg_lx_timing (read-sysfs.py mlg_lx_timing)
shows the mean of each hop per request number, and first the cost of
the runtime's primitives measured where it runs: clock, malloc, 16 KiB
kzalloc, mutex, spinlock, RCU read section, current and errno.
T2 on 239: Quake3e's bundled SDL2 2.24.1 refused RADV as its Vulkan
library ("Installed Vulkan Portability library doesn't implement the
VK_MVK_macos_surface extension"); its Cocoa backend requires that
extension at load, and every window creation failed ("Couldn't get a
visual"). RADV now also advertises VK_MVK_macos_surface on the macOS
platform; vkCreateMacOSSurfaceMVK takes an NSView backed by a
CAMetalLayer, or the layer, and makes the same Metal surface (a view
without one is refused). test-radv-scanout checks the extension, both
kinds of pView and the refusal.