Its scanout waits on the same 200 ms flip deadline as
test-display-pipeline, which the runner's software GPU fixture misses.
It still runs on a developer Mac.
The previous README change replaced everything from the performance
section to the firmware note in the license section, dropping What
works through License. They are back unchanged; only the performance
section carries the LemonSeed Engine 0.5.8 numbers.
The performance section shows LSE 0.5.8 measured from its macOS release
archive on driver build 266 with the bundled HSA runtime: decode for
DFlash2 (adaptive, draft trees), MTP=3 and plain on code, essay, 2K and
4K prompts with acceptance and mean verify width, prefill at 1K to 32K,
and warm load, replacing the v0.5.4 table and its comparisons.
The HSA runtime gains hsa_amd_queue_create with its descriptor, full CU masks, the vmem access query, unknown-OS target ids, and the MEMORY_PROPERTIES and PM4_EMULATION agent queries, which current HRX main calls at initialization. make hsa-test: 19/19.
The runner's bash is macOS's 3.2, where expanding an empty array under
set -u is an unbound-variable error: test-kmem-release, test-kfd-session
and test-kfd-power expand theirs only when set.
test_aql_reset's concurrency check stored the queue's write index with a
plain store while the reset thread reads it, which TSan reports as a race.
The test now publishes it with a release store, as the HSA runtime does.
tests/KNOWN_FAILURES.md lists the tests skipped for a known reason, and
scripts/known-failure.sh gates their recipes on it. Three timing tests
whose windows the shared CI VM misses are skipped there only (CI set):
test-mutex-completion, test-iokit-dma and test-display-pipeline. They
still run on a developer Mac. MAC_LINUXGPU_RUN_KNOWN_FAILURES=1 runs them.
The display daemon closes each mirroring process's pipe at end of file
instead of spinning on it, and a mirroring process no longer ends when
its STATUS poll is answered kIOReturnBusy. Installed on the R9700 Mac as
a host-app-only update (driver 0.1.162 build 266 unchanged): the daemon
held 2 pipes at 0.0-0.3% CPU over 9 minutes with the DP-4 mirror up
throughout, against 170-260% CPU and 2,556 pipes before.
The daemon read each mirroring process's output with a readabilityHandler
that ignored end of file. At end of file availableData is empty and the
handler fires again at once, so the handler spun and the read descriptor
stayed open after every child exit. A daemon up for 29 hours ran at
170-260% CPU holding 2,556 pipes, and the child output stopped reaching
the log.
followOutput (DisplayAgent.swift) closes the read end and clears the
handler at end of file, after the last chunk. The termination handler no
longer clears the readability handler, which could drop the last lines
and leave the descriptor open. A pipe whose process failed to start is
closed.
A mirroring process no longer ends when its STATUS poll is answered
kIOReturnBusy: the daemon's STATUS and PROBE and the child's own IMPORT
share the driver's display gate, and a collision ended the mirror, which
the daemon restarted 10 s later. IMPORT is asked again for up to 2 s on
kIOReturnBusy. The daemon logs a mirroring process's exit status.
test-display-agent runs 20 short processes through followOutput and
checks every byte arrives, the end is seen once, no descriptor is left
open and nothing spins afterwards.
Code objects whose target is spelled amdgcn-amd-amdhsa-unknown-<isa>
(the ROCm device library's gfx12-generic object, for one) now load on
an agent whose ISA is amdgcn-amd-amdhsa--<isa>; the two spellings name
the same target.
HSA_AMD_AGENT_INFO_MEMORY_PROPERTIES returns an empty property set and
HSA_AMD_AGENT_INFO_PM4_EMULATION returns false for the GPU agent. The
current HRX AMDGPU HAL queries both while opening a device.
Current HRX System creates its AQL queues with hsa_amd_queue_create and
always states the queue's CU set with hsa_amd_queue_cu_set_mask; its HSA
symbol table also requires hsa_amd_vmem_get_access. The runtime exported
neither entry point, so libhsa failed to load.
hsa_amd_queue_create takes version-1 descriptors. A compute descriptor is
an hsa_queue_create of queue_size_bytes/64 packets with the descriptor's
queue type, scratch size and error callback, and default group segment
sizing. Device-memory placement, SDMA and AIE engines, cooperative queues
and non-normal priorities are not available on this transport and fail
that descriptor with HSA_STATUS_ERROR_INVALID_QUEUE_CREATION; malformed
descriptors (unknown version, non-power-of-two or non-packet-multiple
size, nonzero reserved fields) are INVALID_ARGUMENT. In a batch, created
queues stay valid, a failed descriptor's queue is NULL, and the first
error is returned.
hsa_amd_queue_cu_set_mask accepts a mask that enables every CU the device
reports, which is the set the queue already runs on. A mask leaving a CU
out still fails with HSA_STATUS_ERROR_INVALID_QUEUE: queues cannot be
narrowed without a synchronized MQD update.
hsa_amd_vmem_get_access reports a mapping's permissions: the CPU has what
hsa_amd_vmem_set_access last granted it, and a GPU agent has none, since
set_access never grants one on this transport.
The vendored HSA headers move to hsa-runtime-headers 4285513, the
revision HRX System pins, which declares the descriptor types; it adds
amd_launch_descriptor.h, which hsa_ext_amd.h now includes.
hsa-queue covers descriptor creation, CU masks, rejected requests and
batches; the new hsa-vmem-access test covers the access query.
Each hsa_executable_load_agent_code_object gave its image a VRAM buffer
of its own and wrote it at once. On build 265 a load cost 0.44-0.50 ms
and 6 IOKit calls: the device snapshot (RuntimeBuild and three QueryInfo
tags), BOAlloc (a KFD allocation and its GPU mapping) and an SDMA BOCopy
from the staging buffer. Destroying one cost 0.36 ms and a BOFree. Every
code object held one of the driver's buffer slots: 8192 slots shared by
every client of the GPU, linear-scanned on each buffer call. HRX takes a
second slot per executable for its kernel-args table, so LSE loading one
kernel per executable ran out near 4,000 executables.
Code objects now come from a per-connection code heap (code_heap.h), as
ROCr's loader carves code segments out of its code pools. Its chunks are
4 MiB of VRAM (an image that does not fit gets a chunk of its own),
divided by CodeRangeAllocator: best fit on the device address at the
alignment the image's segments ask for, sizes rounded to 4 KiB so ranges
handed out in turn are adjacent, freed ranges coalesced and reused. A
chunk left empty goes back to the driver, but for one standard chunk
kept for the next loads. A heap that cannot grow fails the load and says
why on stderr.
A load reserves its range, relocates the image to it and stages it in a
4 MiB host-mapped buffer, with no driver call. Before the next doorbell
of the connection's queues, or a driver launch, everything staged is
uploaded by one SDMA copy per run of adjacent ranges, then the one
CodeSync that load owes runs as before. A full staging buffer flushes
on its own, and an image larger than it is written at once after what
was staged before it. Drivers before CodeSync upload and sync each load,
as before. The device snapshot is read once per connection. Address
queries and a new load's overlap check use an address-ordered index.
On the R9700 with build 265's driver, 1000 small code objects load in
0.009 ms each with 0.02 IOKit calls each (was 0.437 ms and 6.2), 262 of
LSE's packed code objects in 3.4 ms (was 130 ms), and destroying 1000
takes 1.2 ms (was 438 ms). 20,000 code objects load in one process and
their kernels run. LSE's 262 executables hold 5 chunks instead of 262
buffers.
test_code_heap: the allocator (alignment, best fit, reuse, coalescing,
20,000 random loads and unloads checked against a model), the heap
against the fake transport (one copy per batch, staging overflow, large
images, reuse before upload, chunk release) and the loader on drivers
with and without CodeSync (250 loads in one chunk, bytes on the device,
address queries, reuse after destroy, a driver launch naming the chunk
and offset).
Connection::copyBuffers takes the source first and the destination
second, and every caller passes them that way. The fake named its
parameters the other way round and copied the destination over the
source. No test looked at the bytes a copy moved, so nothing caught it.
The fake also counts its VRAM allocations and copies
(allocationCount, copyCount) for tests that check how many driver
calls a path makes.
A KFD client that brackets its BAR stores may now keep kernel arguments
in CPU-visible VRAM and publish them with the HDP flush register, as HRX
does on Linux: the HDP flush page and hostable VRAM mapped for the CPU,
behind its gate, with mappings retired once the device is gone (also for
Linux-file clients).
On the R9700 (build 265), LSE master with the bracket patch against LSE
master without it, two interleaved rounds: DFlash2 640-token decode
52.6-53.0 -> 54.2 tok/s, plain 30.4-30.7 -> 31.7-31.8, MTP=3 53.6 ->
54.0-55.4; warm TTFT unchanged; acceptance and temperature-0 output
identical.
HRX on Linux keeps a queue's kernel arguments in CPU-visible VRAM and
publishes them with the HDP flush register when the HSA runtime reports
HSA_AMD_AGENT_INFO_HDP_FLUSH and lets the CPU at the device coarse pool.
This brings that path to the Mac, where a CPU store to a GPU that stopped
answering can panic the machine, so every such store is bracketed under
the client's gate.
patches/linux/amdgpu-mmio-remap-4k-hole.patch: the NBIO/NBIF HDP flush
remap stays in the 4 KiB register hole the hardware leaves unused,
whatever the host page size (upstream moved it with PAGE_SIZE and turned
it off for pages over 4 KiB). KFD's own MMIO paths still refuse large
pages; nothing upstream maps the page into a process.
linuxu (kfd_session.c): rt_kfd_session_hdp_flush gives the host page of
the register BAR holding the remap page, after checking that no register
block of the device starts in the rest of it. VRAM can take a window VA,
and rt_kfd_bo_make_cpu_visible pins such a buffer in the CPU-visible
window: unmapped from the GPU, off the eviction fence, pinned with
CPU_ACCESS_REQUIRED, the move waited for, mapped again at the same VA.
rt_kfd_bo_bar_ranges reports its BAR ranges; a free unpins it first.
dext (hdp_flush.h): QueryInfo MLG_QUERY_BAR_WRITES lets a KFD client
opt in. It gets its gate (published, so every power transition, reset,
quarantine, fault, removal and close closes it and drains), the HDP
flush page as client memory, and CPU access to hostable VRAM: BOAlloc
flag DEXT_COMPUTE_BO_FLAG_HOSTABLE, then BOMap pins it and hands out its
BAR ranges. A client that never asks gets none of it. A retired gate is
marked so the client knows it never reopens. Closes that stop the device
answering (the session's close, quarantine, reset) wait up to 1 s for
an open bracket. Build 265.
HSA runtime: mac_hsa_bar_writes_enable, mac_hsa_bar_write_begin and
mac_hsa_bar_write_end. After enable the agent reports HDP_FLUSH, the CPU
agent's access to the VRAM pool is DISALLOWED_BY_DEFAULT, VRAM is
allocated hostable, and hsa_amd_agents_allow_access with a CPU agent maps
an allocation write combined at its own address, as ROCr does on a
large-BAR device; nothing else is CPU-mapped. begin waits while the gate
is held and fails once the device is gone, after replacing every BAR
mapping of the process with host memory (bar_mapping_retire.h); kicks
that find the GPU disconnected do the same.
libmlg_drm: a transport that says the device is gone has every mapping
retired the same way, so Vulkan clients' stores through mapped VRAM and
doorbells land in host memory too.
Tests: the session test pins hostable VRAM, checks its BAR ranges, a
full window and the HDP page with and without a register block beside
it; the production test enables BAR writes, maps hostable VRAM and
ranges it; hsa-bar-writes checks what is reported before and after
enable, the CPU grant, nested brackets, a held gate and a lost device;
the gate and libmlg_drm tests check retired gates and mappings.
Prototypes for letting HRX write kernel arguments into CPU-visible VRAM
and publish them with the HDP flush register on this platform, where a
CPU store to a GPU that left the Thunderbolt link panics the Mac.
doorbell_gate.h: mlg_bar_write_begin and mlg_bar_write_end bracket a
submission's several stores into the BARs (a memcpy into the VRAM kernarg
ring, the HDP store and its read back, the doorbell) under the client's
existing gate, with the same Dekker protocol as mlg_doorbell_ring.
Brackets nest, so a doorbell rung inside one is a nested bracket. End
completes the stores (DSB ST) before counting out, since the driver may
power the device down the moment busy reads zero. mlg_doorbell_ring is
unchanged.
hsa/src/bar_mapping_retire.h: DriverKit cannot revoke a mapping it gave
a client, so the client maps zero-filled anonymous memory over its BAR
range in one step (mmap MAP_FIXED) once it learns the device is going:
every later store from any thread lands in host memory and every load
reads zero, as Linux's dummy page after drm_dev_unplug.
Tests (make test-bar-write-safety): submitters copying kernargs, storing
and reading back the HDP register and ringing the doorbell race power and
reset holds, client closes and session closes under ThreadSanitizer and
AddressSanitizer, and no store lands after a close returns; writers with
no gate store into a shared mapping while it is retired, and none reaches
the underlying pages afterwards, none faults, and the range reads zero.
Clients ring their KFD queues' doorbells themselves behind a gate the
driver closes for power transitions, device resets, closes and removal;
device resets behind a gate with PCI restore (off unless the personality
sets MacLinuxGPUDeviceReset). Installed and smoke-tested as 0.1.160 (264).
A doorbell cost the submitting thread a trip through the driver: 14.7 us
for the synchronous AQLQueueKick of build 263 (20 us async before it), on
the one delivery thread every client's calls share. On Linux a process
writes the doorbell page it mmaps from /dev/kfd: one store. From build 264
the runtime does the same.
- The client maps its KFD process's doorbell slice (MLG_DOORBELL_MEMORY_TYPE,
uncached): the page of the doorbell BAR KFD gave that process
(rt_kfd_session_doorbells), holding only its own doorbells, as libhsakmt
maps it. AQLQueueCreate asked for three outputs answers the queue's
doorbell in it (out[2]), or MLG_DOORBELL_NONE for a queue rung through
AQLQueueKick (a legacy queue). A KFD queue whose doorbell cannot be
mapped is destroyed again and the call fails.
- A store to the GPU's BARs once it stops answering can panic the Mac, so
every doorbell write goes through a gate (doorbell_gate.h): a page the
driver and the client share (MLG_DOORBELL_GATE_MEMORY_TYPE). The client
counts itself busy, writes only while the gate is open, and counts itself
out; the driver closes the gate and waits until busy is zero (Dekker's
protocol, sequentially consistent both sides), so once a close returns
the client writes nothing. A closed gate writes nothing: the runtime
then sends the doorbell as AQLQueueKick, which answers what the device
can take (Offline while it suspends: the doorbell waits for resume, as
before; NoDevice once it is gone).
- The driver closes every gate for a power transition (power_set), and for
a device reset's whole window (the recovery hooks, before upstream halts
the device until the PCI restore put the BARs back; a failed reset
wedges and keeps them closed). Both doorbell paths, the clients' and the
delivery thread's kick table, now hold a set of reasons instead of one
flag, so a power change inside a reset opens nothing. A client's gate
is retired (closed, drained, forgotten) at its close, its KFD process's
release (whose doorbell slice may go to another process), the session's
close or quarantine, a transport fault and a removal. The wait is a
bounded spin (it may run on the delivery thread): a client stopped
inside a write for 20 ms is named in the log.
- Runtime: the queue keeps its doorbell and gate from creation until
inactivate; a write never lowers the doorbell (as the driver's paths).
Measured on the R9700 over Thunderbolt 5 (lat.cpp, display mirroring):
doorbell store 14.7 -> 0.38 us median; empty dispatch round trip 43.9 ->
32.4 us (Linux on the same card: 31.3); back-to-back wall per dispatch with
a doorbell each 16.8 -> 12.7 us. LemonSeed Engine decode is GPU-bound:
plain 28.2 -> 28.7 tok/s, DFlash2 51.3 -> 51.4.
Tests: test-doorbell-gate races client threads ringing through their gates
against power holds, device-reset holds inside them, client closes and
session closes, under ThreadSanitizer and AddressSanitizer; a doorbell
written after a close returns fails it (dropping the drain does). It also
names a client stopped mid-write. test-kfd-session checks the slice (a
page of BAR 2, the process's own) and that the client's offset is the word
the driver's kicks write; test-dext-compute-production the doorbell
lookup, gate publish, power and reset holds and retire at the client's
release; test-kick-table holds and releases both reasons;
test-hsa-power-transport the runtime's maps, its direct store, a closed
gate, and the failures that destroy the queue again.
The session cycle test's probe stops in IP discovery, before upstream
takes the DMA mappings, pages and threads the cycle checks watch. With
the card's IP discovery binary and VBIOS it gets further:
- test_session_cycles --deep: upstream reads the discovery binary as a
file (amdgpu_discovery=2) and the VBIOS through SMUIO's ROM_INDEX and
ROM_DATA registers, as on the card ("Fetched VBIOS from ROM"); VRAM
(BAR0) and the doorbells (BAR2) map; registers keep what was written
to them. Each cycle must read the whole VBIOS, and every resource must
return to its baseline as in the shallow mode.
- scripts/capture-r9700-fixtures.py records the inputs from a running
driver, read-only, through upstream's own exports: the ip_discovery
sysfs tree and AMDGPU_INFO_DEV_INFO through the observer,
mem_info_vram_total, AMDGPU_INFO_VBIOS on the render node through
libmlg_drm (only after the observer reads show the driver running),
and the BAR sizes from the I/O Registry. The driver exports the raw
discovery binary only in debugfs, so scripts/ip_discovery_builder.py
rebuilds it from the sysfs export (no variant or sub-revision, no
harvest/VCN/MALL/NPS table, gc_info v1.0 from DEV_INFO).
- The capture goes to tests/fixtures/local/r9700/, which git ignores:
the VBIOS is AMD's copyrighted image and the repository is public.
tests/fixtures/local/README.md says how to capture.
- scripts/test-session-cycles.sh runs the deep cycles when a capture is
present and prints SKIP otherwise (as on CI). On every run it also
self-checks the deep harness with a synthetic RDNA4-shaped table and
a ROM without ATOM tables: upstream must find SMUIO, read the whole
ROM, refuse it and unwind the same way every cycle.
The driver's persistent AQL queues are legacy kernel queues MES maps;
a device reset takes them with MES's state. Upstream's device recovery
now carries them across:
- As upstream halts the device, a DRM client of the device (the hook
upstream gives everything outside amdgpu that must stop before its IPs
suspend) marks every mapped queue unmapped. Kicks are refused until
it is mapped again.
- Once the reset has succeeded and the schedulers run again (where KFD
restores its queues), before the new reset generation is published,
each queue's storage block is written again with an MQD upstream
builds afresh, positioned at the producer's write_dispatch_id, the
reader is moved there, and the queue is mapped. Packets not finished
were lost with the GPU's state; the generation tells clients. The
restore writes the storage through SDMA, so it cannot run from the DRM
client's resume, which precedes the schedulers' restart.
- A queue that cannot be mapped again is retained, and its owner's next
call freezes the session. A queue destroyed after a reset that was not
followed by a restore (the device wedged) is freed without an MES unmap.
The hooks run on the reset domain's thread while the owner queue serves
calls, so dext_aql keeps its own list of mapped queues under a lock held
only across bounded steps (MES map/unmap, storage writes), never across a
wait the reset must finish. Without it a restore could write a queue a
destroy had just freed.
The fixture's device-reset-recovers check failed intermittently: the
fixture's ASIC reset zeroed its engines' read pointers while the driver's
rings kept their write pointers (the fixture's IP blocks had no resume),
and an engine could also carry on mid-batch from the cleared position.
The SDMA engine then executed its stale ring from the start, old fence
values included; amdgpu_fence_process took the lower sequence for a wrap
and signalled every pending fence, so a new client's IB ran before its
page-table update and faulted. The ASIC reset now stops each engine at a
packet boundary, and the fixture's GFX and SDMA blocks resume their rings
at 0 as gfx_v12_0 and sdma_v7_0 do. The check now also asserts both
resumes ran.
Tests: test-aql-reset builds the real dext_aql.mm against a mock MES and
checks restore at the producer's position, kicks refused in between, the
wedged destroy, a failed restore, and the hooks on their own thread
against 300 rounds of create/kick/destroy under ASan and TSan (without
the lock it reports a use-after-free). The production-backend scenarios
cover the hooks' installation and the freeze on a failed restore; the
fixture's device-reset-recovers covers upstream's recovery running the
hooks around a real reset.
A hang the queue reset cannot end now runs upstream's device reset
(amdgpu_device_gpu_recover, mode1 on gfx12) when the platform allows it
(rt_recovery_set_full_reset_gate), and wedges the GPU otherwise. The
driver's gate allows it only when the personality enables device resets
(MacLinuxGPUDeviceReset, absent = off until a reset is validated over
Thunderbolt) and no client maps one of the GPU's BARs: neither a raw BAR
lease nor any Linux-file mapping through a BAR (rt_lx_bar_mappings),
since a client store into a BAR that stops decoding can take the Mac
down. Every refusal is logged with its reason as the wedge's.
Upstream's own recovery runs unchanged, with three bounds around it:
the ASIC reset is wrapped so one recovery makes at most two attempts
(upstream retries a reset whose IB tests fail without limit on bare
metal); a device reset that fails (reset_domain->reset_res) wedges the
GPU, where upstream would leave its schedulers stopped with no event;
and one that succeeds advances the reset generation, with
RT_RECOVERY_LAST_VRAM_LOST when the VRAM-lost counter moved. The KFD
and user-queue reset works go through the same path.
RESET_WAIT (selector 91, observers and session clients, registration on
the delivery thread) completes when the reset generation differs from
the one the caller knows, with the generation and MLG_RESET_FLAG_*; a
client's waits end with it. The host's daemon re-arms it to post its
notification.
Tests: device_reset_check (the CS fixture, which now has soc24's reset
method and an ASIC reset that restarts its engines) allows device
resets and hangs a queue whose reset fails: upstream's
amdgpu_device_gpu_recover runs, the GPU does not come back (no VBIOS),
the device wedges after one ASIC reset and nothing retries. test-owner-
call covers RESET_WAIT (new generation, stale generation, cancel) and
the gate (personality, raw lease, client BAR mappings);
test_lx_files counts a client's BAR mapping.
A mode1 reset clears the GPU's configuration (BARs, command, MSI-X) and
nothing in macOS writes it again; upstream caches it before the reset
and restores it after (amdgpu_device_cache_pci_state/load_pci_state).
pci_restore_state refused any BAR change (-ESTALE, the transport-fault
latch) and never restored MSI-X, so a device reset could only end in a
quarantine.
The saved state now also holds the MSI-X capability's control word and
the table entries DriverKit programmed (read from the table's BAR
through the kernel, dext_pci_bar_read32), the vectors in use first.
Restore checks it is the same function with the same capability layout,
then writes back the header as the host assigned it (cache line and
latency, BAR0-5, the ROM BAR, the interrupt line) with memory decode off
until every BAR reads back its value, the PCIe controls, MSI-X (function
masked while the table is written, each entry verified, then the saved
control), and the command last. A BAR or table entry that does not take
its value fails the restore as before. The values are the host's own
assignment: nothing moves behind the host bridge.
test_pci_dext covers a reset that cleared the BARs, ROM and command, a
BAR that does not take its value, MSI-X saved and written back, and a
table entry that does not take its value.
The backend check still asserted the design before the VRAM aperture:
no SIMD register anywhere and no external reference at all. Neither has
held since the aperture's bounce buffers (4968adb): the DriverKit target
builds with Apple's default stack protector, which guards them and adds
___stack_chk_fail and ___stack_chk_guard, and -ftrivial-auto-var-init
clears them with vector stores to the stack. Since ff661c6 normal memory
is copied with NEON on purpose. Device memory reaches the backend only
through linuxu_aperture_*.
The check now asserts that design at -O0 and -O2: no DC ZVA anywhere; no
vector load or store off the stack in the aperture functions (device
accesses stay in general registers); and the only external references
are the stack protector's, with __stack_chk_fail defined by the dext's
close-first handler (fatal_close.h) and ___stack_chk_guard exported by
DriverKit's libSystem. The stack protector stays on: the dext handles it
deliberately and the bounce buffers are what it is for.
The test compiles iokit_bridge.mm whole, and since the BAR0 mapping
publishes itself as the VRAM aperture (linuxu_aperture_set and
linuxu_aperture_set_ops, linuxu/src/kmem/device_string.c), the link
failed on both. The test now builds device_string.c and links it, as
test-iokit-dma and test-pci-call-guards do.
The display calls were extracted from the start of displayResults up to
the ExternalMethod banner, on the assumption that display_call was the
last function before it. Build 263 put kick_on_delivery (the synchronous
AQLQueueKick) there, and the extraction pulled it in with the session,
power and kick-table state it reads, none of which the display mocks
provide. The section now ends at display_call's closing brace, so code
the dext adds after it stays out, with the same line bound.
MacLinuxGPUHost rebar prints, for each resizable BAR, the sizes the
device can decode and the size it decodes now. It reads the device's
configuration space through the sysfs "config" file as an observer,
like the pcie command, so it writes nothing and works beside a session.
The parser walks the extended capability list from 0x100 and accepts
the capability only as linuxu's pci_rebar_read does: version 1, one to
six entries inside the space, distinct BARs, and a selected size the
BAR supports. test-device-info checks it against the R9700's capability
(BAR0 256 MB of 256 MB to 32 GB, BAR2 2 MB of 2 MB to 256 MB) and
against malformed lists.
macOS sizes every BAR and the bridge windows above it once, when it
enumerates the device. IOPCIFamily never programs this capability and
takes no BAR above 1 GB, and DriverKit has no call to resize one, so
the size shown as now is the one the driver works with.
KFD's GFX 12 MQD already points CP_HQD_PQ_WPTR_POLL_ADDR at each queue's
write index (amd_queue_t.write_dispatch_id). Upstream leaves the global
CP_PQ_WPTR_POLL_CNTL.EN off (gfx_v12_0_kiq_init_register writes it for
the KIQ only), and MES takes each queue's write-pointer address in
ADD_QUEUE and handles unmapped queues through CP_UNMAPPED_DOORBELL. Nothing
upstream says whether MES firmware writes the polling register. With EN
set, the CP would read the write indexes itself every PERIOD, and a
client's own store to its write index would start its work with no
doorbell and no CPU store to the BAR at all.
rt/wptr_poll.h:
- Observation, always on: the register is read once after each KFD queue
is created, when MES has mapped it and compute is active (KFD keeps
GFXOFF off then), and logged whenever its value changed. The first runs
show whether MES writes it.
- The experiment, off unless the dext's personality sets
MacLinuxGPUWptrPollPeriod (1-255, the field's raw value, whose unit is
undocumented): EN and PERIOD are written, re-written if MES clears them,
and reported in session state (WPTR_POLL).
- The runtime skips doorbells only with MAC_HSA_DOORBELL=poll and only
while the driver reports polling; otherwise it says why and the queue
fails.
GFX 12.0 only (the gc_12_0_0 register headers); nothing else changes.
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.
linuxu's memcpy, memmove, memset and memcmp, which are the dext's, used
volatile 8-byte accesses (bytes when the two pointers' alignment differed),
for every pointer, so that no wide or unaligned access could reach device
memory. Device memory never reaches them by pointer apart from BAR0, whose
accesses already go through the aperture's kernel calls; registers and
doorbells are ioremap tokens. Every other pointer is normal cacheable
memory, now copied 64 bytes at a time with LD1/ST1 (byte elements, so no
alignment is needed under -mstrict-align, which splits a plain unaligned
vector load into bytes), with no cache-zeroing instruction. no_builtin
keeps the compiler from turning the loops into calls to themselves.
Measured on this Mac, 64 MiB: memcpy 11.6 -> 64 GB/s with matching
alignment and 1.9 -> 64 GB/s without; memset 15.5 -> 142 GB/s. Checked
against libc over every length to 1100 and 17x17 source/destination
offsets, overlapping moves both ways included.
The driver's own KMD (upstream amdgpu, KFD, TTM, DRM and the linuxu shims)
compiled with no optimization level: clang's -O0, apart from five objects
whose BUILD_BUG_ONs need folding. Every register access, fence, interrupt
and copy path ran unoptimized. Both the DriverKit library and the host
builds the offline tests link now use the flags Linux builds that code
with (CONFIG_CC_OPTIMIZE_FOR_PERFORMANCE, CONFIG_FRAME_POINTER as arm64
has it): -O2 -fno-strict-aliasing -fno-strict-overflow
-fno-delete-null-pointer-checks -fno-common, frame pointers kept for crash
logs. -funsigned-char stays out: it changes char semantics, not code
generation, from what Apple's signed-char ABI has always run.
The DriverKit objects also turn off the printf-family and string-copy
builtins: at -O2 clang rewrites such calls into others (sprintf, strcpy,
strncpy, vsnprintf, fwrite) that the DriverKit runtime does not export.
The library's external references are then a subset of the -O0 build's.
The offline suite passes as before; three tests fail with and without this
change alike (rg is not installed here, and two sanitizer findings in
test-only code: test-debugfs-lifecycle, test-kmem-cache-lifecycle,
test-upstream-pci-failure).
test-dext-compute-production asserted RuntimeBuild's out[2] was 258, so it
failed once DEXT_RUNTIME_BUILD moved on (262). It now compares against the
compiled build the driver reports (RuntimeBuild's out[3]).
Replaces the first-run figures (43.3 tok/s decode, 60 tok/s prefill) with
measured v0.5.4 numbers on driver build 262: warm prefill up to 1,496 tok/s
at 4K, 0.17 s to first token at 137 tokens, 50.5 tok/s DFlash2 decode, 3.4 s
model load; llama.cpp Vulkan pp512 1,100 tok/s. Adds a one-paragraph summary
of the comparison against stock Linux amdgpu/ROCm on the same GPU model.
hsa_memory_copy and hsa_amd_memory_async_copy reached about 3 GB/s on a
link where RADV's SDMA copies reach 6.9 GB/s. A copy between a client's
system pages and VRAM went 1 MiB at a time through the driver's GART-bound
staging buffer: a CPU copy of the pages (the driver's device-safe memcpy)
and a waited SDMA job per step, after the runtime's own CPU copy into its
mapped staging.
rt_kfd_bo_copy now copies between a GTT buffer and VRAM with
amdgpu_ttm_copy_mem_to_mem on TTM's move entity, as amdgpu_move_blit moves
a buffer on Linux: the system pages are mapped through the entity's GART
windows and SDMA copies them directly, one fence for the whole range,
with no CPU copy. A copy that fails or outlives its timeout keeps the
buffers until its fence signals, as the staging path does (copy_wait).
Buffers SDMA cannot reach that way (no DMA addresses, not GTT) keep the
staging path. patches/linux/amdgpu-ttm-copy-mem-export.patch makes the
function callable and leaves its resv argument optional.
BOCopy (selector 48) takes up to 16 MiB a call, and DEXT_RUNTIME_BUILD is
262. The HSA runtime asks for that limit from build 262 on, and copies
between a shared (GPU-mapped) host buffer and a device buffer through the
driver directly, with no CPU copy through its staging buffer.
Host tests: test-kfd-session covers GTT to VRAM and back through the
windows (across page boundaries, from offsets), and a windowed copy that
outlives its timeout. Not yet run on hardware.
hsa_amd_memory_async_copy started a thread for every copy. A copy now goes
to a worker the runtime keeps: an idle one takes it, and a new one starts
only when every worker is busy, so as before no copy waits behind another
(one may wait for dependencies that a later one satisfies). A worker idle
for 2 s ends. Each job keeps its stop request and its completion flag;
destroying a job waits for it to finish, as joining its thread did, so
hsa_shut_down and the reaping of finished jobs are unchanged.