Commit Graph
66 Commits
Author SHA1 Message Date
geramyloveless cdc46fa23c Merge feature/quake3-direct-scanout (cf6ca2a) into display-c
VK_MVK_macos_surface in the RADV WSI patch (SDL 2.24 needs it); mlg-run
stops Quake3e when it falls back from the forced mode.
2026-10-04 08:39:45 -07:00
geramyloveless b8999f34ed Merge branch 'feature/radv-apple-vram' into merge/radv-vram-into-display-c
# Conflicts:
#	dext/sources/MacLinuxGPUXcode.mm
2026-10-04 08:33:41 -07:00
geramyloveless 62cf568154 lx: time each hop of a Linux-file request, per request number
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.
2026-10-04 08:11:50 -07:00
geramyloveless d197adc7e7 radv: VK_MVK_macos_surface for SDL2 before 2.26
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.
2026-10-04 08:08:16 -07:00
geramyloveless fb0fb232ab mlg-run: --basepath and --basegame for Quake3e's game data
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.
2026-10-04 07:24:39 -07:00
geramyloveless fa7e5c9628 quake3e: build the game Vulkan-only for mlg-run
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.
2026-10-03 22:31:05 -07:00
geramyloveless 2ea6aeea12 radv: present Metal surfaces with the GPU's display engine
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.
2026-10-03 22:27:26 -07:00
geramyloveless 7375ebd3d2 libdrm-mlg: the primary node, KMS queries and drmMlgScanout
- 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.
2026-10-03 22:21:35 -07:00
geramyloveless 22fd731283 tests: the aperture gate covers the dext's BAR0 mapping
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.
2026-10-03 20:39:36 -07:00
geramyloveless aa0aca57a9 linuxu: waits park until woken instead of polling every millisecond
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).
2026-10-03 17:50:21 -07:00
geramyloveless 0a67e495c2 Merge feature/sysinfo: the R9700's identity in System Report
The display OUTPUT op republishes MacLinuxGPUDisplays with the lit
mode, as STATUS and the pattern ops do.
2026-10-03 17:14:14 -07:00
geramyloveless 7f14420460 kfd session: signal events and interrupt-driven waits
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.
2026-10-03 17:13:29 -07:00
geramyloveless a56c499f91 Publish the GPU's identity and monitors for System Information
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.
2026-10-03 17:12:22 -07:00
geramyloveless 60c1b44f02 Merge feature/clean-upgrade: Retire selector and upgrade handoff 2026-10-03 16:56:19 -07:00
geramyloveless 29b4e710d4 display: a presented frame no longer waits for its copy or flip
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.
2026-10-03 16:56:14 -07:00
geramyloveless f185a7f1de tests: share the DCN 4.0.1 register fixture
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.
2026-10-03 16:56:14 -07:00
geramyloveless d6ca8045c7 host: hand the GPU from the previous driver to the new one on upgrade
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.
2026-10-03 16:43:29 -07:00
geramyloveless 2ea5d08b16 dext: hand the GPU to a replacement driver (Retire), stop at once when idle
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.
2026-10-03 16:43:29 -07:00
geramyloveless 331692b9ca display: a GPU that left the bus has no display to drive
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.
2026-10-03 15:57:17 -07:00
geramyloveless eea40d37ac Merge feature/hotplug into feature/display-c
The surprise-removal path of the DMA seam completes retired table entries, which now hold an IOMemoryDescriptor (imports share the table).
2026-10-03 15:57:17 -07:00
geramyloveless cfbf699f34 Merge feature/mlg-host-window into feature/display-c 2026-10-03 15:48:10 -07:00
geramyloveless 457a75876b dext: survive the GPU leaving the bus
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.
2026-10-03 15:44:38 -07:00
geramyloveless 0f426a08de linuxu: surprise removal of the GPU
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.
2026-10-03 15:44:38 -07:00
geramyloveless b7de5f648c libmlg_drm: place the host window before InitDevice
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.
2026-10-03 15:35:47 -07:00
geramyloveless 1c07048c01 Merge main into feature/display-c 2026-10-03 15:19:43 -07:00
geramyloveless 84b40028d2 Place the host window before InitDevice in the host app and the self-test
MacLinuxGPUHost init and drm-selftest.py --init called InitDevice
without placing the host window (selector 54), so compute start failed
with gart status -19. Query the aperture size, reserve it aligned, set
the base, then probe, as the HSA runtime does.
2026-10-03 15:16:21 -07:00
geramyloveless 8ac5223b6b installer: --display builds the DMG with Display Core enabled 2026-10-03 15:07:47 -07:00
geramyloveless f09557da66 host: display-agent --dry-run
MacLinuxGPUHost display-agent --dry-run [--once] [--interval ms] [--init]
follows the GPU's connected monitors through an observer client. It polls
the cached connector state (selector 84 STATUS) and, when the hotplug
epoch moves, probes, reads each connected monitor's mode list (MODES)
and EDID (sysfs), and prints the CGVirtualDisplay it would create, then
the add, update and remove changes against what it had. It creates no
display; without --dry-run it refuses.

The plan takes the identity and colour from the EDID: the monitor name
(else PNP ID and product), the PNP ID word as vendor, the product, the
serial (or a stable hash of the serial string), the CIE primaries and
white point. It takes the modes from the driver's list for the link:
progressive only, duplicates dropped, preferred first, and the largest
mode as max pixels. The size comes from the driver's display_info (else
the EDID's). hiDPI is 0. A monitor with no valid EDID or no progressive
mode is reported and skipped.

The model (report/modes/EDID decoding, the plan, the agent's changes)
moves to host/DisplayAgent.swift, Foundation only, which the Xcode
target now builds; test-display-agent compiles it with a test of its
own. docs/macos-displays.md records what of the frame path exists.
2026-10-03 14:51:43 -07:00
geramyloveless 723a9ff36e dext: map a client's memory descriptor for the device
dext_dma_import() takes a memory descriptor a client passed (a display
agent's IOSurface pages, as a structure-input descriptor), retains it and
prepares it for DMA with an IODMACommand on the bound device, limited to
the device's DMA width. Every segment must be whole 16 KiB pages below
that width and together exactly the requested length; otherwise the
mapping is completed again and refused. The mapping is recorded in the
same table as the coherent mappings, under an import id, so the existing
rules hold for it: dext_dma_release_import() completes it, or under the
shutdown hold only retires it until the endpoint reset; a quarantine
retains it; fini refuses while it lives; the shutdown hold counts its
bytes. Coherent-allocation lookups (descriptor copies, range
descriptors, frees by CPU address) never match an import.

Table entries now hold an IOMemoryDescriptor, the type IODMACommand
prepares. The DriverKit mocks prepare several segments when asked, and
test-iokit-dma's "import" scenario covers the lifetime, release under
the shutdown hold, refusals (partial pages, no room, PrepareForDMA
failure, a misaligned run, an IOVA beyond the DMA width) and quarantine
retention.
2026-10-03 14:48:17 -07:00
geramyloveless a27677cf2c rt: import a client's memory as a GPU buffer and copy it into VRAM
rt/surface.h: memory of another process that the platform mapped for the
device (a display agent's IOSurface, mapped by the dext's IODMACommand),
given as DMA segments, is imported the way Linux imports any foreign
buffer: an exporter whose sg_table carries those DMA addresses,
amdgpu_gem_prime_import() (an SG BO), pinned in GTT and bound in the
GART. rt_surface_copy() copies dirty rectangles from it into an amdgpu
VRAM buffer with the SDMA buffer functions on the TTM entity: one copy
packet per contiguous run (whole rows with equal pitches are one range),
up to 1024 packets per job, the last fence added to both buffers and
waited for with a bound. The CPU touches no pixel and no other copy
mechanism exists.

The provider's release runs exactly once, when the dma-buf is released:
after the BO is destroyed, which TTM delays until its fences signalled.
A failed import never runs it.

The DART layer gains imported mappings (linuxu_dart_import): charged to
the budget and live for containment while imported.

test-surface-import runs it on the CS fixture device, whose software
SDMA engine reads system memory through the GART table upstream filled
and faults on anything the DART does not map: a surface in three
separately allocated segments, a whole frame with differing pitches (360
row copies, one job), damage rectangles with clipping, 1100 rectangles
(two jobs), a band with equal pitches (one packet), refused imports and
destinations, and the release after the BO is gone.
2026-10-03 14:43:55 -07:00
geramyloveless c336a91260 scripts: display-test.py status and modes
status prints the cached connector state and the hotplug epoch without
detecting anything; modes <connector> lists that connector's probed
modes with refresh, pixel clock, the preferred mode and physical size.
2026-10-03 14:35:21 -07:00
geramyloveless 74fb0a661f Merge main into feature/display-b
# Conflicts:
#	Makefile
#	dext/sources/session_state.h
#	linuxu/tests/test_read_driver_log.py
#	linuxu/tests/test_session_shutdown.cpp
#	scripts/read-driver-log.py
2026-10-03 14:15:00 -07:00
geramyloveless 1120f5c32a Merge main: suspend/resume and driver robustness
Brings in feature/ipad-next (power and robust). The CS fixture keeps both
sides: the DART fault model, narrow BAR, held SDMA, TTM eviction checks and
self-test v2 counters from main, and the R9700 configuration, driver-stream
modeling and BAR memory for the loopback from the Vulkan work.
cs_fixture_bar_memory now maps only the CPU-visible part of VRAM, so a
narrowed BAR is honored. The README keeps main's sleep limitation and notes
that Vulkan has no presentation yet.
2026-10-03 14:10:59 -07:00
geramyloveless cd088371a9 activate: --display enables Display Core in the dext personality
--display sets MacLinuxGPUDisplay=true in every MacLinuxGPU personality
of the built dext's Info.plist before its final signature: in the local
profile path the dext is signed afterwards as before; after Xcode's
automatic signing the dext is signed again with its own identity,
entitlements and flags, then the app. The source Info.plist is not
changed. Without --display the built personality is checked to carry no
display key, so an install without the flag is compute-only.
2026-10-03 14:08:37 -07:00
geramyloveless eccbc20c0a scripts: read connector EDIDs and filter the log for display
read-sysfs.py read a file until its reported length; a bin attribute of
size 0, such as a DRM connector's edid, reports none, so it stopped after
the first chunk. It now ends such a read at a short chunk. The usage text
shows the connector directories.

read-driver-log.py --display prints only the lines of display bring-up
and the display test: the display opt-in, DMCUB/DMUB, Display Core and
its clock manager, SMU, HPD, EDID, link training, commits and their
waits, connectors and the display test's own lines.
2026-10-03 14:08:36 -07:00
geramyloveless 2d77cee5e9 scripts: display-test.py, the hardware display test runner
display-test.py drives selector 84 through an observer client:

  probe [--edid]      every connector with status, mode count, preferred
                      mode and EDID size; --edid reads each connected
                      EDID from sysfs (drm/cardN/cardN-<conn>/edid) and
                      decodes vendor, product, serial, name, size and
                      preferred timing
  show [--connector NAME] [--pattern bars|white|gradient] [--seconds N]
                      the pattern on every connected output, or one;
                      with --seconds it is turned off afterwards, also on
                      Ctrl-C
  off                 the recorded configuration restored

--init brings the GPU up through a session client held for the run (a
show then defaults to 30 seconds, since the session ends with the
script). Errors name the failing step's errno; nothing else is tried.
test-display-test runs it against a fake selector.
2026-10-03 14:08:36 -07:00
geramyloveless 9718e8d8cf dext: Display selector 84 for the in-driver display test
MLG_SELECTOR_DISPLAY (84, after DrmSelfTest 82 and PowerControl 83 on
feature/power; 96-103 stay the Linux-file selectors) runs the display
test client (rt/display.h) for observer clients, admitted like the other
observer reads, one op at a time (Busy otherwise):

  scalar in   [0] op: probe, show or off  [1] pattern (show only)
              [2] MLG_DISPLAY_CONFIRM ("DISP")
  struct in   show only, optional connector name; none means every
              connected output
  struct out  struct rt_display_report
  scalar out  [0] 0 or the op's negative Linux errno

The observer policy accepts only that shape. Each op is logged with its
probe, commit and restore status, the connected and lit outputs, the
framebuffer and the fill and commit times.

close_session turns a showing pattern off right after observer
admission drains and before anything else is torn down, so the
configuration it replaced is committed again while the driver still
runs; a quarantined session keeps the client with every other upstream
owner. test-session-shutdown covers both orders and the selector policy.
2026-10-03 14:08:22 -07:00
geramyloveless 73b0f63c42 tests: the display test client on the fixture DCN 4.0.1 device
test-dm-offline now continues past dm_hw_init the way amdgpu_pci_probe
does: drm_dev_register(), with the PCI function as the DRM device's
parent and a client file opened like amdgpu_driver_open_kms opens one
(its VM with CPU page-table updates, a scheduler no job reaches, the
real amdgpu_driver_postclose_kms), so dumb buffers and framebuffers are
amdgpu's own.

Two connectors get a sink the way Linux emulates a monitor (forced on,
a synthetic EDID through drm_edid_override_set, as video=<conn>:e and
debugfs edid_override do): HDMI-A-1 with a CTA-861 HDMI block and DP-2
with a base block only; DP-1 and DP-3 stay empty. The test then checks:

- connector sysfs as Linux shows it under drm/card0: status unknown
  before probing, connected/disconnected after, enabled, dpms, the mode
  list and the EDID bytes;
- probe: status, mode count, EDID size and the 1920x1080@60 preferred
  mode per connector;
- refusals: an unknown pattern (-EINVAL), an output with no sink and a
  connector that does not exist (-ENOENT), each leaving nothing behind;
- show on one connector, then on the other, then on every connected
  output (each on its own CRTC), with the pattern bytes in VRAM, an OTG
  programmed with 2200x1125 totals and a HUBP scanning out the
  framebuffer address;
- off: the recorded configuration restored (enabled=disabled, the OTG's
  master enable cleared), and the session-close stop;
- drm_dev_unregister() removing the connector and glue directories.

The fixture runs no DMCUB firmware, so DMUB and power-gate waits time
out and a run takes about three minutes.
2026-10-03 14:08:22 -07:00
geramyloveless cdb75b6ff4 Pin llama.cpp b11379 and build its Vulkan backend for RADV
llama.cpp is the first application of the Vulkan path. third_party/llama.cpp
pins b11379 as an optional, unpatched upstream (sparse, update = none);
scripts/bootstrap.sh --llama-only fetches it and verify-upstream.py checks
it once checked out.

scripts/build-llama-vulkan.sh (make llama-vulkan) builds it with
GGML_VULKAN against the Vulkan loader (Homebrew's or the LunarG SDK's),
Metal, BLAS and libcurl off, into build/llama.cpp/bin: llama-bench,
llama-completion and test-backend-ops. Its shaders need shaderc's glslc.
scripts/llama-radv.sh runs any program with the loader pointed at the RADV
ICD alone, so a MoltenVK installation is not used.

test-llama-offline brings the CS fixture device up inside llama.cpp's own
test-backend-ops (vulkan/tests/fixture_preload.c, inserted through
MLG_PRELOAD) so its Vulkan backend runs on RADV on the software GPU:
llama.cpp lists the R9700, and in performance mode ADD and the Q4_0/Q4_K
matrix multiplications of a feed-forward layer (matrix-vector and
matrix-matrix pipelines) are compiled by ACO, allocated, submitted and
fenced. It skips unless RADV and llama.cpp are built.
2026-10-03 11:19:41 -07:00
geramyloveless 8c105a22ef radv: build Mesa's Vulkan driver for macOS, and test it offline
scripts/build-radv.sh (make radv) builds RADV from third_party/mesa on
libdrm-mlg: Meson with the ACO compiler and no LLVM, no window-system
platform (headless WSI), no GL, video, zstd or SPIRV-Tools, so the driver
links only the system and libdrm-mlg. It installs a relocatable ICD into
build/radv/install (libvulkan_radeon.dylib, libdrm_mlg.dylib,
libmlg_drm.dylib, share/vulkan/icd.d/radeon_icd.json with a relative
library path) and fails if any symbol other than the weak layer
entrypoints is left unresolved. Mesa's Python generators get a virtualenv
when python3 lacks mako, PyYAML or packaging.

test-radv-offline (vulkan/tests/test_radv_offline.c) loads the ICD as the
loader does and runs it on the CS fixture device through libdrm-mlg and
the loopback transport, against unmodified upstream DRM/amdgpu: instance
and enumeration ("AMD Radeon AI Pro R9700 (RADV GFX1201)", Vulkan 1.4, PCI
bus info), device creation, host-visible memory, an empty submit with a
fence, vkCmdFillBuffer and vkCmdUpdateBuffer executed by the software GPU
and checked through the mapping, a compute pipeline compiled by ACO, and a
dispatch submitted with a timeline semaphore and a fence (the software GPU
runs no shaders, so its result is not checked). It skips when RADV has not
been built.
2026-10-03 11:19:30 -07:00
geramyloveless a64270efa5 Pin Mesa 26.2.4 for RADV, with two declared patches
third_party/mesa is Mesa at mesa-26.2.4, the latest stable release,
declared in patches/manifest.json as an optional upstream: a shallow,
partial, sparse submodule of what a RADV-only Meson build reads (about
60 MB), marked update = none so a recursive clone does not fetch it. Only
the Vulkan build needs it; scripts/bootstrap.sh --with-mesa fetches it
with the rest, --mesa-only alone, and once checked out it is kept at the
pin and patched like the Linux tree.

The patch set, 88 lines added and 9 removed in 8 files:

- radv-macos-build.patch: find libdrm through pkg-config on Darwin when
  RADV is built, select addrlib's portable type definitions instead of
  the Apple kernel driver's private header, and link RADV with
  -undefined dynamic_lookup as KosmicKrisp does.
- drm-file-ops.patch: util/os_drm.h issues requests through drmIoctl and
  wraps open, stat, mmap and munmap of DRM nodes and files in libdrm's
  drmFile* functions when libdrm defines LIBDRM_FILE_OPS; RADV's six call
  sites use the wrappers. Nothing changes for a kernel libdrm.

bootstrap.sh sets up any manifest upstream the same way now (pin fetched
by SHA, sparse before the first checkout, declared patches applied).
verify-upstream.py checks Mesa's pin, sparse set, patches and working tree
once it is checked out, and takes --only linux|mesa; lib-dext verifies the
Linux tree alone (make verify-linux), so local Mesa work cannot block a
driver build, while make verify-source checks every tree.
2026-10-03 11:19:19 -07:00
geramyloveless 81fdbf22c4 libdrm-mlg: libdrm and libdrm_amdgpu over libmlg_drm
Mesa's amdgpu drivers reach the kernel through libdrm's core API, through
libdrm_amdgpu (devices, buffers, GPU virtual address ranges) and through a
few system calls on the DRM descriptors. libmlg_drm/libdrm provides the
part of xf86drm.h, amdgpu.h and libsync.h they use, over libmlg_drm, with
libdrm's names, types and return conventions, so RADV's stock amdgpu
winsys and Mesa's native ac_linux_drm path build and run unchanged.

The driver's files live in the dext's per-client Linux process. Each one
the library hands out (an opened render node, and every syncobj,
sync_file and dma-buf descriptor a request returns) is represented by one
end of a socket pair, the library keeping the other end: close, dup,
fcntl and fork work on it as on any descriptor, and when the last copy is
closed a watcher thread sees end-of-file and closes the driver's file, the
lifetime a kernel file has. Requests carrying descriptors are translated
both ways, with O_CLOEXEC in Linux's value. drmFileOpen, drmFileStat,
drmFileMmap and drmFileMunmap, declared under LIBDRM_FILE_OPS, stand in
for the system calls that cannot reach the driver. sync_wait and
sync_merge work through temporary syncobjs of an open render node.

The amdgpu part follows libdrm_amdgpu (MIT), from which its VA manager
and buffer handling are derived: device deduplication, the PRT half-range
reservation, dma-buf import by GEM_OP rather than lseek, no userptr.
LIBDRM_MLG_DEBUG=1 reports refused requests and descriptor lifetimes.

make libdrm-mlg installs build/libdrm-mlg with the uapi headers as the
kernel installs them and libdrm.pc and libdrm_amdgpu.pc for Meson.
test-libdrm-mlg runs it end to end against the CS fixture device. The
Makefile's depfile search now skips the Meson and CMake trees the Vulkan
builds will put under build/.
2026-10-03 11:18:55 -07:00
geramyloveless fee1bf108d Merge feature/robust: process-death recovery, DMA hold, TTM self-test
The KFD test fixture gained MES failure modes on both branches. Keep
both: power's one-shot removal failures (mes_fail_removes) and robust's
hung, dead and slow MES queues, with arrays sized FIXTURE_MES_SLOTS.
REMOVE_QUEUE honours the one-shot failures first. The GPU reset request
still trips the test unless a MES call failed, and is logged as recovery
being off.
2026-10-03 10:45:43 -07:00
geramyloveless 4897d775de cs self-test: move the VRAM buffer to GTT and back through TTM
The self-test (selector 82, drm-selftest.py) copied VRAM into GTT only
through the client's own GPUVM, never through the path an eviction takes.
Two steps now move its VRAM buffer the way a client's submission moves
it: AMDGPU_GEM_OP SET_PLACEMENT, then an SDMA copy of the buffer whose
AMDGPU_CS validates it there. Into GTT, TTM's move goes through a GART
transfer window as an eviction's does (SDMA uploads the window PTEs,
flushes VMID 0, copies); the copy made afterwards must still hold the
buffer's known contents. The move back runs the source window. Each wait
is bounded: a move that never completes fails the step with -ETIME and
parks the test process as before.

The result is version 2 (240 bytes): the two steps, the bytes TTM moved
during each, their times and the words read back. drm-selftest.py reads
versions 1 and 2 and prints the TTM line; the dext logs the new fields.
2026-10-03 10:38:03 -07:00
geramyloveless 2b325d4752 tests: TTM VRAM-GTT moves through the GART windows on the CS fixture
The CS fixture's software GPU now checks every system-memory page it
touches against the live DMA mappings, as the DART would: an access
outside them is counted as a DART fault and fails like a GPU fault. Its
BAR can be narrower than VRAM (the iPad's covers 256 MiB), and its SDMA
engine can be held like the compute engine.

ttm_evict_check runs TTM moves through the unmodified upstream code with
a 64 MiB BAR over 256 MiB of VRAM: a BO beyond the BAR validated to GTT
and back, then evicted under VRAM pressure, each through
amdgpu_move_blit's GART transfer windows. It checks the contents and the
window PTEs SDMA uploaded: valid, system, snooped for cached pages,
writable, exactly the ttm_tt's DMA addresses, each inside a live mapping.
No GPU or DART fault occurs.

It then holds SDMA while a kernel BO moves: the move fails after TTM's
15 s wait with the same log lines as the iPad's failure, the BO stays in
VRAM, and the pages TTM released stay mapped until the engine catches up,
so its late copy faults nothing. CS_FIXTURE_NO_DMA_HOLD=1 runs the
negative control, in which that copy hits unmapped DMA addresses.
2026-10-03 10:38:03 -07:00
geramyloveless 05bcf49db3 dext: close a dying KFD client even when it froze the device
Once a KFD client left GPU completion uncertain, every later stop and
client release returned EBUSY before trying anything, so a client killed
after a failed queue removal always quarantined the session, even when
its session could still recover.

Record whether only KFD clients froze the device. Releasing a client and
stopping compute then close its KFD process anyway, since the close
retries the session's recovery (hung-queue reset and removal, a copy
that outlived its timeout); when every KFD client is certain again the
device thaws. Stop tries every client before giving up. The client's
queue handles go with it and its dext client owns the queue records, so
a close that keeps the client leaves no stale handle behind.

dext_kfd_close destroys retained queue records too instead of refusing,
and dext_kfd_settle retries what left a client uncertain without closing
it. The production test covers a client that dies after a failed removal,
both when the close recovers it and when it is kept until a later stop.
2026-10-03 10:38:03 -07:00
geramyloveless af101f49cb kfd session: recover a queue MES does not confirm removing
A client killed with an open engine left its session uncertain whenever
DESTROY_QUEUE failed: remove_queue_mes times out when a wave neither
finishes nor preempts, KFD asks for a GPU reset that recovery-off turns
into a log line, and the session kept every buffer. The dext then
quarantined the device until a replug.

Tear a dying client down as upstream recovers a hung MES user queue
(amdgpu_userq's detect_and_reset before the unmap): when DESTROY_QUEUE
fails after KFD already took the queue off its lists, MES resets the
compute queues it finds hung and removes this one again with
remove_queue_after_reset, under the device queue manager's lock as
remove_queue_mes runs. A queue KFD still lists is retried with
DESTROY_QUEUE instead, never a second DESTROY_QUEUE on a detached one.
Close tries every queue, and keeps memory only while something is still
unconfirmed.

An SDMA copy that outlives its timeout keeps its fence: the session
settles once it signals, and close waits for it once more, bounded.
rt_kfd_session_settle retries all of this without closing, and
rt_kfd_session_failure names the first step that could not confirm the
GPU let go. Each failure and recovery is logged with the queue and
doorbell.

The KFD fixture gains a MES whose queues can hang (REMOVE_QUEUE fails
until a hung-queue reset), die or answer slowly, kfd_hws_hang's reset
request as recovery-off logs it, and an SDMA engine that holds copies.
The tests kill clients mid-session with a hung queue, a slow MES, a MES
that never answers (kept, then recovered by closing again), a destroy
retried by a settle, a copy that outlives its timeout, a bounded launch
whose wave never preempts, and a client closed with a hung persistent
queue; every buffer and allocation is accounted for afterwards.
2026-10-03 10:15:54 -07:00
geramyloveless bded3d87c4 hsa: pause queues while the device is suspended, report lost memory
The runtime now follows the driver's device power state.

While the device is suspending, suspended or resuming the driver
refuses GPU work with kIOReturnOffline, having submitted nothing. The
IOKit transport returns that as HSA_STATUS_ERROR_RESOURCE_BUSY and
keeps the session healthy instead of faulting it. A queue whose
doorbell is refused keeps the highest value rung (its packets are in
the ring already); its service thread polls gently and rings it again
once the device takes work, so a generation in flight pauses and
continues. Allocations, transfers, queue creation and bounded launches
fail with the same retryable status.

Once a host sleep has closed the session the device's memory is gone:
queue error callbacks and the power API report HSA_STATUS_ERROR_FATAL,
which a client takes as "reload": release everything, hsa_shut_down,
hsa_init (the next initialization probes the device afresh), load
again.

mac_hsa_power.h, included by mac_hsa.h, gives clients the agent's power
state (state, generation, flags with VRAM preserved, cause, counters,
queues holding a doorbell); mac_hsa_agent_prepare_low_power, which
stops ringing this process's doorbells, waits a bounded time for the
packets already rung to finish, and asks the driver to quiesce;
mac_hsa_agent_resume, which drops the request and rings what waited;
and a bounded wait for the next power change. The iPad app calls
prepare on willResignActive and resume on didBecomeActive; neither is
needed for correctness, since the driver handles sleep itself.

The fake transport models the driver's power state for the new host
test, which covers paused and replayed doorbells (by the service and
by resume), retryable refusals, prepare and resume, waiting for a
change, and lost memory reported to a queue's error callback. A
transport test covers the IOKit status mapping. The runtime's copy of
the protocol names its state enum PowerState, which no longer collides
with the snapshot's State word.
2026-10-03 10:12:22 -07:00
geramyloveless f1557dd66c dext: sleep, device low power and client low-power requests
The driver now handles DriverKit's power changes and gives clients a
power state, a way to ask for low power, and a way to wait for changes.

SetPowerState(Low), the device in a reduced power state while the
system runs, and a client's PowerControl PREPARE quiesce the compute
session through upstream KFD suspend (rt/power.h): every user queue off
MES with its work saved, VRAM untouched. RESUME by the last holder, or
SetPowerState(On), resumes it through upstream KFD resume and the saved
work continues.

SetPowerState(Off), system sleep, takes the Thunderbolt link and with
it the endpoint's state; VRAM cannot survive it on these hosts, and
upstream's only dGPU path evicts all of VRAM to system memory through
SDMA, which neither fits on the iPad nor is safe over the link. The
driver closes the compute session through its ordinary close path
before acknowledging the change; the acknowledgement waits for the close
on the default queue, with a watcher that acknowledges at a deadline so
a stuck close never stalls the sleep. On wake the state is lost if a
session was closed, and the next InitDevice probes afresh and makes it
active again. A quiesced session closes as it is, its queues already
off MES; the KFD suspend is handed back before upstream removal takes
its own, so upstream's suspend count stays balanced across sessions.

A failed quiesce or resume hands the suspend back, so MES maps the
queues again and the close removes them through MES; a GPU that cannot
prove itself idle leaves the session to the existing quarantine rather
than freeing memory it may use.

Clients see state, generation, flags (VRAM preserved among them),
cause, error and counters through QueryInfo tag "LPWR" (observers too)
and the PowerControl selector 83: QUERY, PREPARE, RESUME and an async
WAIT completing at the next generation change. While suspending,
suspended or resuming, selectors that would put work on the GPU are
refused with kIOReturnOffline, which a client retries after resume;
frees, queue destruction and cached queries stay available. A closing
client's waits end and its hold is dropped. Observers may request
transitions only with the session-release entitlement.

power_state.h holds the state machine, the snapshot, the admission
policy and the plan each event leads to, with a host test that also
checks the runtime's copy of the protocol. The session shutdown test
covers the removal hook and the observer policy for the new tag and
selector, and read-driver-log.py prints the power state.
2026-10-03 10:03:32 -07:00
geramyloveless 3998f121ad linuxu: quiesce and resume compute through upstream KFD suspend
A low-power period that keeps VRAM needs every user queue off the GPU
with its work saved, and the same queues back afterwards. Upstream
amdgpu has no suspend flavour for a discrete GPU that keeps VRAM: S3,
s2idle and BACO/BAMACO runtime PM all run amdgpu_device_prepare and
amdgpu_device_suspend, which evict all of VRAM to system memory through
TTM and SDMA. What it does offer without touching VRAM is the KFD half
of those paths, amdgpu_amdkfd_suspend(adev, true), which on a dGPU is
kgd2kfd_suspend(kfd, true): every KFD process's queues are evicted
through MES (waves saved through CWSR), eviction fences are signaled,
new processes are held off, and the queue managers stop. Its pair,
kgd2kfd_resume(kfd, true), restores the processes' buffers in place and
maps the queues back.

rt/power.h wraps exactly those two calls for the dext and reads
upstream's own state around them: the queue lists, the queue managers'
scheduling flag, and the reset mark kfd_hws_hang() leaves when MES fails
a removal. A failed MES removal is reported as -EIO even though upstream
marks the queue inactive before asking MES, so a queue the GPU may still
be running is never mistaken for a quiesced one. Upstream counts
suspends, so the module keeps its own suspend until it is resumed.

The new fixture test drives both entry points from the unmodified
kfd_device.c over the KFD session fixture: a suspend unmaps the queue
and holds new processes off, work published meanwhile waits, the resume
maps the same queue back and the work runs, a session closed while
suspended issues no MES operation and the resume that follows lets KFD
take processes again, and an injected MES removal failure is reported.
The fixture gains a process restore that replaces the eviction fence as
upstream does, MES removal failure injection, a non-fatal
kfd_hws_hang() reset request after an injected failure, and the SMI
event list kfd_init_node sets up.
2026-10-03 10:01:53 -07:00