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.
With --quake3, --basepath DIR and --basegame NAME become fs_basepath and
fs_basegame, which Quake3e reads at start. mlg-run first checks that
DIR/NAME (baseq3 without --basegame) holds .pk3 files and stops with what
is missing otherwise; both are refused without --quake3. OpenArena 0.8.8,
free data kept outside the repository, runs as --basegame baseoa (its game
VM and maps load in a Quake3e dedicated server from this pin).
test-mlg-run covers the settings and the refusals.
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.
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.
test_iokit_dma links the device string functions and checks that the
gate covers exactly the BAR0 CPU mapping: once the device is gone,
stores into it are refused and loads read all ones, RAM is unaffected,
and a new mapping (a new device) opens it again.
wait_event and its variants, schedule_timeout, completions, contended
mutexes, rw semaphores and semaphores, and dma_fence waits all slept in
1 ms (or 50 us) steps and re-checked, so every sleeping thread woke about
a thousand times a second, waiting or not.
They now park (rt/park.h): a futex over addresses, with condition
variables in hashed buckets, where the waker changes state and unparks
the key and the waiter re-checks under the bucket lock, so no wake is
lost. Tasks park on themselves and linuxu_task_wake unparks them, which
covers wake queues, wake_up_process, signals and kthread_stop.
wait_event queues the task on its wake queue as Linux does; fence waits
add a callback that unparks.
Every wait whose condition it can test is bounded by a backstop that
starts at 2 ms and doubles to 1 s while nothing happens, so an idle
waiter costs about one wakeup a second. A backstop that finds the
condition already true means its producer did not wake it: the wait
site is reported once (file and line, or the caller's address) and
counted. schedule_timeout returns early at the 1 s backstop, a spurious
wake as Linux allows.
test_wait_event checks that a wake_up wakes its waiter at once and not
another, that schedule_timeout ends at wake_up_process, that an idle
300 ms wait wakes 8 times rather than 300, and that the backstop finds
a producer that never wakes (its existing producer is one).
A session creates KFD signal events as libhsakmt does on a dGPU: the
first CREATE_EVENT hands KFD a GTT event page in the session's private
range, and each event reports its id, trigger data and mailbox address
for an amd_signal_t. A completion that names such a signal makes the
command processor write the mailbox and raise the end-of-pipe interrupt,
which KFD turns into the event.
Waits are WAIT_EVENTS on the caller's thread, inside the process but
outside the session lock, each with its own argument VA, so many waits
and the session's other calls run together and nothing polls. Closing
destroys the session's events, which ends every wait, and waits for
them before the process exits.
The fixture's command processor now writes the mailbox and calls
kfd_signal_event_interrupt for interrupt signals (or drops the
interrupt on request). The test checks that the interrupt wakes the
waiter on its event and no other, that a lost interrupt ends at the
timeout with the signal complete, that a signaled auto-reset event
completes a later wait, SET_EVENT, DESTROY_EVENT, and close with a wait
asleep.
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.
The offline DM test's register file, VBIOS builder and EDIDs move to
dcn401_fixture.c so other tests can bring up Display Core on the same
synthetic DCN 4.0.1. The DM test now expects the output to refuse to
start without an SDMA engine, which its fixture has none of.
An activation request that replaces the driver does not stop the running
one, and the new driver attaches only after every old instance is gone. The
installer returned .replace and then checked attachment with a ping, which
the old driver answered. The old process stayed attached until someone
killed it.
The installer (the app's installer window and `activate`) now drives the
handover. It tells instances apart by IOUserServerCDHash against the
bundled dext's code signature:
- Before the activation request, each previous instance closes its session
the normal way and admits no new one (Retire QUIESCE). Apps that still
hold a session are listed.
- Once macOS has accepted the replacement, each previous instance is asked
to terminate (Retire TERMINATE) and the installer waits for it to leave
the registry. If it does not, it says why: the clients still attached, a
BAR mapping, or a quarantine that needs a restart. It also gives the
recovery steps and the systemextensionsctl state, and never kills it. A
driver that predates Retire is named as such, with the enclosure power
cycle (232 and later) or a restart as the way out.
- A failed or deferred replacement resumes the previous driver.
- Attachment is verified against the bundled driver only.
- When the bundled version is already enabled, a previous instance left by
an earlier upgrade is retired as well.
New commands: `instances` lists attached driver instances with their
clients and session state. `retire-previous [--force] [--wait S]` finishes
a stuck upgrade, `resume-previous` cancels a quiesce, and `ping-bundled`
pings the bundled driver only. activate.sh retires the previous driver
after the new one is enabled and checks attachment with ping-bundled.
macOS does not stop a running driver extension when an activation request
replaces it. kernelmanagerd declines to terminate the old version ("being
replaced and cannot be terminated"), sysextd leaves it "terminating for
upgrade via delegate", and the kernel attaches the new version only once
every instance of the old one is gone. Until then a GPU that appears still
matches the old version. Nothing in the driver ever let an instance go
except its GPU leaving the bus, so an upgrade with the GPU attached left the
old process holding it until someone killed it, which can panic the Mac.
Retire (selector 85, entitled, observers may call it) is how the installer
makes an instance go:
- QUIESCE admits no new session and closes an open one through the normal
close: upstream removal, interrupt drain, endpoint reset, provider close.
- TERMINATE also asks IOKit to terminate this driver instance once nothing
of the session is left (IOService::Terminate). IOKit stops the clients,
then the driver, and the process exits.
- RESUME undoes QUIESCE when the replacement failed or was deferred.
Nothing is forced into quarantine. A client's raw BAR mapping refuses the
close, as do other session clients unless FORCE is given. A quarantined
session is released only when it is provably quiescent; otherwise Retire
reports the blocker and the instance stays (restart, never kill). Session
state gains a RETIRING flag.
Stop of a driver with no session (an upgrade, a deactivation, an unplug of
an idle GPU) now releases the provider at once instead of going through an
interrupt drain and a queue hop.
The session-shutdown fixture runs the production MacLinuxGPU::Stop and
Retire. It covers Stop during an upgrade with an idle observer, with an open
session, with a quiescent quarantine and with an uncertain one. It covers
Retire when idle, quiesce and resume, terminate with a session, a raw BAR
mapping, and a releasable and a held quarantine. Each finishes every Stop
and releases the service and provider, or keeps everything and reports a
restart.
With the device removed (rt/removal.h), every display op returns
-ENODEV, and turning a pattern or output off commits nothing: the
recorded configuration is dropped and the buffers and client go as on a
Linux unplug. Surface imports, copies and checks return -ENODEV;
releasing still works and the client's mapping is returned once the
removal has completed the BO's fences.
The dext releases what the display ops hold in one place
(release_display_owners): at a session close unless a quarantine keeps
every owner, or the device is gone; and when a removal releases a
session that was quarantined, before compute stop and upstream removal.
Tests: test-session-shutdown removes the device under a display agent
with an output on screen and two imports, in a plain session, one that
quarantines during the close, and one quarantined before it (released
only by the removal); test-surface-import removes the device with an
import held; test-dm-offline removes it with the pattern on screen and
turns it off without a register write.
Unplugging the eGPU with a session open took the whole iPad down. When
its PCI provider and clients are terminated the device is already gone,
but the close treated it as a GPU that might still run: every teardown
step waited on hardware that never answered, the session quarantined
(retaining the provider, the DMA backing and the upstream driver), and a
dext that dies while it holds the device panics the kernel in
IOPCIFamily's client crash recovery, as on the Mac.
Detect the removal when a client or the driver stops: configuration
space no longer answers (asked on the provider directly, since a fault
may have closed admission). From then on nothing touches the device:
admission closes for good, nothing resets or isolates it, BAR0 CPU
accesses through the io accessors read ~0 and drop writes, and the
runtime's removal begins (GPU work completes with -ECANCELED). A device
off the bus can reach no memory, so DMA safety holds: the DMA seam lifts
a quarantine and its holds and completes retired descriptors at once,
compute stop and client release stop refusing on account of uncertain
GPU work, and no step quarantines. The close runs to the end, removes
the upstream driver after the removal thread stops, releases the BAR0
aperture and closes the provider once nothing is admitted and no
interrupt source is left, then reopens admission so the replugged GPU
probes afresh. A session already quarantined when the removal is seen is
released the same way. New session opens fail with kIOReturnNotAttached
meanwhile.
The power state goes to lost with the new cause "device removed" and
the link-down flag, so clients learn what happened; the session state
has a device-removed flag and read-driver-log.py names both.
Tests: the session shutdown fixture removes the device under a client's
open session whose compute stop fails, and under a session already
quarantined; neither resets, isolates or quarantines, every Stop
finishes, and a new client opens a new session. The production backend
stops a device whose legacy queue could not be removed once it is
removed.
A GPU that leaves the bus (a Thunderbolt unplug) left every waiter on
its work waiting forever: fences of jobs the hardware will never run,
MES requests polled for their full timeout, and sessions that kept their
memory because nothing confirmed the GPU let go.
Give the runtime the state Linux's PCI core and amdgpu_pci_remove give a
surprise-removed device. struct pci_dev gets error_state, set to
pci_channel_io_perm_failure by linuxu_pci_mark_removed, so
pci_dev_is_disconnected and pci_device_is_present answer without
configuration access and amdgpu's removal takes its hot-unplug branches.
rt_removal_begin marks the device, sets no_hw_access, makes the DRM
device count as unplugged for drm_dev_enter (render-node ioctls then fail
with -ENODEV and guarded paths skip the hardware, GART writes among
them), and force-completes every ring's fences with -ECANCELED, as
amdgpu_fence_driver_hw_fini does for an unplugged device; a removal
thread keeps doing so for work submitted while the sessions close, until
rt_removal_end. MES requests then fail at once.
A removed device can reach no memory: a KFD session drops a queue whose
removal fails and a copy that never finished, the compute context
releases memory a timed-out copy left poisoned (and its fence), and the
CS self-test reaps a parked test once the device is gone.
Tests: on the CS fixture the device is removed with a compute job held,
an SDMA copy held and waited on without a timeout, a parked self-test
and an open render-node client; every wait returns with -ECANCELED, both
processes exit, new opens fail and nothing touches the hardware. A KFD
session closes cleanly after removal with MES dead and a copy pending,
and the compute context frees its poisoned memory.
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.