mirror of
https://github.com/lemonade-sdk/mac_linuxgpu.git
synced 2026-11-22 23:57:31 -10:00
main
71
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
b190c105a8 |
Kernel arguments in CPU-visible VRAM, published with the HDP flush
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. |
||
|
|
4fe23bc535 |
A client rings its KFD queues' doorbells itself
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. |
||
|
|
2dd02645b6 |
AQL queues are mapped again after a device reset
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. |
||
|
|
b856a93f95 |
GPU recovery: device resets behind a gate, bounded; RESET_WAIT
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. |
||
|
|
c3c8521137 |
PCI restore puts back the BARs and MSI-X a device reset clears
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. |
||
|
|
2122b9b1c1 |
The CP write-pointer polling experiment, off by default
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. |
||
|
|
5607122bec |
AQLQueueKick on the delivery thread
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. |
||
|
|
66593d0727 |
Driver events read in the unified log; Stop and power changes are events
Upstream errors (printk level 3 and worse) went to the unified log as
IOLog("mac.linuxgpu: EVENT %s"), and the DMA seam's events as IOLog("%s"):
both arrive as <private>. They now go through os_log with %{public}s, as
MACLINUXGPU_EVENT already did. printk.c cannot include os/log.h next to
the Linux headers, so the dext registers the sink (klog_set_event_sink)
from a constructor; the level filter is unchanged, so nothing new reaches
the unified log in release beyond events. dext_close's refusal is logged
with literal text instead of a %s argument.
New events, each rare: the driver's Stop (DriverKit has no willTerminate;
Stop is how the driver learns that it or its PCI provider is being
terminated) with the session state, FinishStop letting go of the provider,
and every SetPowerState with the power state it arrived in. A device that
left the bus was already an event.
test-klog registers a sink as the dext does; the session-shutdown fixture's
Stop section bound grows by ten lines for the Stop event.
|
||
|
|
79036bbc8f |
SysfsWrite: the performance level and power profile, through upstream's store()
On Linux, root writes power_dpm_force_performance_level and pp_power_profile_mode, and amdgpu_pm.c's store() applies them. This driver had no sysfs write path: its observer client only reads. Selector 89 (SysfsWrite) takes an attribute id and a value and runs that attribute's own store(), through linuxu_sysfs_write (as kernfs, one store() of a NUL-terminated page). It is limited to: - An allowlist in session_state.h: power_dpm_force_performance_level with auto, low, high or profile_peak, and pp_power_profile_mode with a bare profile index, 0-99. Manual, the other profile_* levels and custom profile parameters are not offered. - Observer clients that carry the session-release entitlement, which is the host app's, as for Retire and the quarantine release. - Synchronous and bounded on the observer reads' driver thread, never the delivery thread, with admission as for SysfsRead. store()'s result comes back as the bytes taken or a negative Linux errno. A value outside the allowlist is NotPermitted, a missing entitlement is NotPrivileged, and a store() still running at 250 ms is Timeout. Tests: test-sysfs-read writes through a device attribute's store(), and checks the NUL-terminated buffer, store()'s own errno, and the read-only, missing and empty cases. test-session-shutdown checks the observer policy, that the call is synchronous but not on the delivery thread, the paths, and the value allowlist (every offered level and index, with and without a newline, and the levels, spellings and parameters it refuses). |
||
|
|
0bf25fe71e |
A faulted queue left on the command processor is reset, not left to wedge
The fault repro on build 256 wedged compute twice. KFD evicted the faulting process's queues, MES reported each removal done, and no removal failure was logged. After the process closed, though, the CP wrote again for the dead PASID, and from then on no launch of any new process completed until a power cycle. A CP stalled on the faulting access keeps running the queue on its HQD after MES lets it go. The session now reads every compute HQD (kfd2kgd hqd_dump; the dump is the register image of the compute MQD from cp_mqd_base_addr_lo, which GFX 11 and 12 share). It does this when it first sees the fault, and again at close before any queue is destroyed or any memory freed: - An HQD still active with one of the session's queues, matched by MES doorbell and MQD address, is reset through MES's hung-queue reset (the session's existing queue_recover), and the HQDs are read again. - A queue that survives that makes the session request a GPU reset (amdgpu_amdkfd_gpu_reset), record step RT_KFD_STEP_CP_STUCK and stay uncertain. A close keeps its memory, and no second reset is requested. A settle or close that finds the HQDs clear lets it go. - HQDs that cannot be read are handled the same way. A removed device has nothing running. The reported fault address is also fixed. KFD's GFX 11/12 handler shifts the IH's page number, which counts 4 KiB GPU pages, by the CPU's PAGE_SHIFT, so on linuxu's 16 KiB pages the address came out four times too large (0x20001070000 for 0x800041c000 on the R9700). Arm64 Linux with 16 KiB pages has the same bug upstream. The session converts with AMDGPU_GPU_PAGE_SHIFT. The fixture now models this case. Its HQDs come from the CP model behind hqd_dump. A faulted queue can stay on its HQD after MES removes it and reports success, and then either MES's hung-queue reset or only a GPU reset (which can be held back) takes it off. Its IH entries count 4 KiB pages, as the hardware's do. test-kfd-session runs three cases while a second client dispatches throughout: 1. Stuck through MES's removal: found when the fault is seen and cleared by the hung-queue reset, with no GPU reset. 2. Stuck through the hung-queue reset too: one GPU reset is requested, the close is refused while the reset is pending, and a settle then clears the session and the close succeeds. 3. Never polled before the program leaves: the close itself finds the queue and resets it first. The ordinary fault case also asserts that the HQDs were read and were clear, and that the reported address is the exact 4 KiB GPU page. |
||
|
|
1ce2a2c272 |
A client's GPU page fault stays that client's: no quarantine, no lost GPU
A program that destroyed a completion signal while its dispatch was still queued made the CP's signal write fault (gfxhub, client CPC, its own PASID). The driver then quarantined the session and isolated the GPU for every program until a power cycle. Upstream KFD had already done what Linux does: its interrupt handler (kfd_int_process_v11) evicted the faulting process's queues and signaled its memory events. The damage came from the dext. The faulting program's queues no longer ran, so the next program's code-object load timed out in its cache-sync launch. That launch's queue was destroyed cleanly through KFD, but dext_compute_dispatch froze the device anyway, as for a DriverKit HQD, because the launch's kernel-ring cache sync had been submitted. With the device frozen for a non-KFD cause, every client release returned -EBUSY (-11006), the close quarantined the session, and closing a quarantined session isolates PCI. That isolation is what the log called "PCI transport fault 4: the GPU no longer answers"; the GPU had not left the bus. Now: - A failed launch on a KFD queue no longer freezes the device. The cache sync is an upstream kernel-ring job that touches no client memory and is covered by the ring's own timeout and recovery. An unconfirmed queue destroy still freezes, scoped to KFD as before. DriverKit HQDs are unchanged. - Each KFD session creates the memory-exception event libhsakmt creates (CREATE_EVENT, KFD_IOC_EVENT_MEMORY). rt_kfd_session_fault polls it without sleeping and keeps what KFD reported: address, not-present, read-only, no-execute, imprecise. A faulted session refuses kicks and new queues with -EFAULT, and its close is an ordinary close. - AQLQueueService (59) answers status kIOReturnVMError for such a queue. With four outputs requested (build 256 on), it adds the fault flags and the faulting page's address. AQLQueueKick (57) answers kIOReturnVMError. Other clients and the display are not involved. - Fault 4 is logged as the driver's own isolation of a quarantined session, and the device-lost line no longer claims the device stopped answering. Tests: - The KFD session fixture delivers UTCL2 faults the way the IH does, through kfd_int_process_v11's ISR and then its work handler on a workqueue. Its CP raises one itself, and stalls, when a completion signal it must write is unmapped. test-kfd-session: one client frees a signal and then runs the dispatch that names it, while another client dispatches throughout. KFD evicts exactly the faulting queue (one MES remove), the fault is reported and sticky, kicks fail with -EFAULT, the bystander keeps completing, and both closes are clean. - test-dext-compute-production kfd-fault-isolated: a client's launch times out after its cache sync, and its queue then reports the fault, while a second client runs on. The device never freezes and both releases succeed. The scenario fails on the old freeze. |
||
|
|
eb16490b9c |
PCIe: give amdgpu the port above the GPU's switch, so the link can leave Gen2
Host to VRAM copies on the R9700 behind a TB5 enclosure top out at 1.65 GB/s (1.83 GB/s back), whatever the engine, chunk size or number of queues: the Gen2 x4 rate. IOPCIFamily shows why. The enclosure's downstream port (8086:5786, Link Capabilities 16 GT/s x4) and the GPU's switch upstream port (1002:1478) are linked at 5 GT/s x4. amdgpu_device_partner_bandwidth walks pci_upstream_bridge() past the dGPU's own switch ports and takes the platform's speed from the first other port's Link Capabilities. Our pci_upstream_bridge() returned NULL, so amdgpu_device_get_pcie_info took the platform speed as unknown and set the platform mask to Gen1|Gen2, and the SMU's PCIe DPM table is clamped to that: the link is held at 5 GT/s by policy, not by the hardware. DriverKit gives no configuration access past the endpoint, but the registry carries what IOPCIFamily read from each port. At Start the dext reads vendor-id, device-id, IOPCIExpressCapabilities and IOPCIExpressLinkCapabilities along its provider chain (CopyProviderProperties), skips the AMD entries as upstream does, and hands the first other port to the PCI shim (linuxu_pci_set_upstream_partner). pci_upstream_bridge() then returns a read-only stand-in for that port: vendor and device, and the PCIe Capabilities and Link Capabilities registers through pcie_capability_read_word/dword, so pcie_get_speed_cap, pcie_get_width_cap and pci_pcie_type answer for it. Every configuration access in the shim reaches the GPU endpoint whatever device it is given, so the stand-in refuses all of them rather than read or write the GPU's registers under the port's name. When the chain cannot be read, or has no such port, the dext says so in its log and amdgpu keeps its Gen1/Gen2 default. The other upstream callers stay as they were: the switch save/restore in amdgpu_device_cache_switch_state requires an AMD downstream port above the endpoint and returns on the stand-in's vendor, and amdgpu_device_gpu_bandwidth falls back to the endpoint's own capability as before. test-pci-dext covers the stand-in: absent until set, the registry's 16 GT/s x4 reported instead of the endpoint's 32 GT/s x16, downstream port type, no configuration reads or writes through it, cleared again. Not yet run on hardware: it needs a dext build, and the check is pp_dpm_pcie listing a 16 GT/s level and the host to VRAM rate rising past 1.65 GB/s. |
||
|
|
fbc26b2b12 |
A transport fault names its caller and ends the session's waits
When a definite PCI transport fault is recorded, admission closes. From then on nothing this driver waits for on the GPU completes. Fences, eviction copies and MES requests all wait forever, and they hold the session queue, which is also where the driver's Stop runs. The three 248 instances from today's hangs never exited after the GPU was power-cycled, and the upgrade to 249 waited on them until the user killed them. - The first fault logs where it came from: the frame-pointer return addresses above it and record_fault's own address, so atos places them in the dext binary. This is what named amdgpu_gmc_set_pte_pde. It runs only on that fault. - dext_pci_set_fault_hook: the session layer reacts once, on the faulting thread. transport_lost calls rt_device_lost. That does what a removal does: the DRM device counts as unplugged, there is no hardware access, and every ring's fences are force-completed with -ECANCELED, now and from a thread every 5 ms. So no wait outlives the fault. Unlike a removal, the PCI device is not marked disconnected (rt_removal_active stays false), so what the GPU may still reach stays retained by the fault's DMA quarantine. - With the GPU unreachable, the last client's leaving closes the session. The close quarantines, naming the PCI fault. When the device then leaves the bus, the removal releases the session and the driver stops. rt_removal_end also stops the lost device's thread, and a new session starts with s_deviceLost clear. session shutdown transport-fault-removal: a fault while a program and the display run, with one hook reaction even when it fires twice. The program leaves, the close quarantines on the fault, the power cycle removes the device, and the instance finishes and stops. |
||
|
|
c282a82741 |
MMIO tokens live in their own address range; process memory is memory
The display's rejoin with LSE loaded knocked the GPU "off the bus" on 248 and 249. The new framebuffers' pin evicted LSE's VRAM, and the eviction's SDMA copy maps its window through amdgpu_ttm_map_buffer. That calls amdgpu_gart_map, and amdgpu_gmc_set_pte_pde writes the PTEs into the copy job's IB, which is ordinary process memory, with writeq(). Linux allows this. The DriverKit accessors decoded every address outside the BAR0 aperture as a synthetic token (address / 256 GB), so the IB at 0x127849020 became token 0, "a lost mapping". The first such write recorded a definite MMIO transport fault, which closes PCI admission and quarantines DMA. Upstream then reported "device lost from bus" with the GPU still on it, and every client's work hung. The fault's call chain (next commit) named the site. The encoding also overlapped real memory in the other direction. A process mapping above 256 GB decoded as a live token, and a store to it went to that token's BAR. Tokens now start at 2^48, above the arm64 user VA ceiling, where no process memory can be. Token 0's range is never minted. Decoding means "inside that range", nothing else. readX/writeX, memcpy_toio/fromio and memset_io go to: - the BAR0 aperture: the kernel, as before; - the token range: MMIO for a live token, a loud fault for a stale or never-minted one; - below 4 GB (__PAGEZERO, a null-based bug): a fault, as before; - anything else: a plain load or store, ordered as Linux orders readX and writeX. test_mmio_dk_accessors checks: - a live register token goes to MMIO; - PTE writes into an IB through amdgpu_gmc_set_pte_pde's own expression are plain stores, as are memset_io and memcpy_to/fromio on heap memory; - a process mapping that the old scheme decoded as the live register token is plain memory; - a stale token, token 0's range and a null-based address still fault and touch nothing. |
||
|
|
e317a1fb11 |
The device spec comes back as a versioned structure
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). |
||
|
|
0ee07c4401 |
MMIO token numbers are renewed between sessions
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. |
||
|
|
121b63ba35 |
GPU recovery: hung queues reset as on Linux; a device reset wedges for now
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. |
||
|
|
9d10aa0e33 |
Session calls never run on the driver's incoming-call thread
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. |
||
|
|
0c8ffc27d5 |
Merge feature/async-lx (3e4651d) into display-c
|
||
|
|
ec8198541d |
lx: no request that can sleep runs on the driver's incoming-call thread
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. |
||
|
|
b4d1555088 |
linuxu: an ALLOC1 xarray never hands out index 0
xa_alloc ignored XA_FLAGS_ALLOC1, so the first DRM syncobj of every render-node file got handle 0, which userspace and upstream read as "no syncobj". Linux keeps index 0 busy in such an array; the shim now starts its search at 1. DEFINE_XARRAY_ALLOC also defined an ALLOC1 array, unlike upstream (where ALLOC counts from 0 and ALLOC1 from 1); DRM's minors use it and would have moved to card1. test_xarray_limit checks both kinds. |
||
|
|
347a44ec16 |
display: no op that can sleep runs on a client's call
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. |
||
|
|
4968adb4de |
VRAM only through the kernel: no CPU access through a BAR mapping
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. |
||
|
|
4b142d018e |
Merge feature/radv-apple-vram (d132e25) into display-c
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. |
||
|
|
c1547a4457 |
Merge feature/quake3-direct-scanout (b004eb7) into display-c
Windowed drag-follow, edge cropping, the HIDE driver op, test-mlg-place. |
||
|
|
b004eb754d |
radv, libdrm-mlg: windowed frames follow the window, clipped, off when it leaves
- drmMlgPlaceWindow (libdrm-mlg) places one frame: the window's content and the monitor's screen in global points (CoreGraphics' space), the output's mode and the image. A screen point is crtc/screen pixels, which is the backing scale and the mode in one factor. A window that fills the screen (or is in native full screen there) gets the primary plane; otherwise an overlay plane at its rectangle in CRTC pixels, clipped to the CRTC with the matching crop of the image on every edge. A window off the monitor, or with less of it there than DC's 12-pixel smallest viewport (which DC would grow without saying), gets nothing, with the reason. No window or no screen keeps the old rules. - LX_SCANOUT HIDE: the client's frames off the screen (the desktop back, the overlay off) while it stays attached and keeps its overlay plane. - The WSI (radv-macos-display-wsi.patch) reads the window at every present, in global points, and uses drmMlgPlaceWindow. Off the monitor it hides once, logs it, keeps the game running paced at the refresh rate, and shows the frames again when the window comes back; going full screen on the monitor when the window is elsewhere is gone. A place that changed is checked with TEST before it is presented; a refusal names the rectangles and the scale. A layer at another size than the images makes presents VK_SUBOPTIMAL_KHR, so a resized window or a full-screen toggle gets new images. - Tests: test-mlg-place (1x and 2x, screens at any global position, full screen, clipping on each edge and a corner, a scaled window clipped, off the screen, the viewport minimum, modes, refusals); test-scanout (HIDE, a cropped present after it, a crop past the framebuffer refused); test-radv-scanout (suboptimal presents for a layer of another size). |
||
|
|
c969e84507 |
dart: no fixed DMA budget; the platform's refusal is the limit, logged
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. |
||
|
|
b8999f34ed |
Merge branch 'feature/radv-apple-vram' into merge/radv-vram-into-display-c
# Conflicts: # dext/sources/MacLinuxGPUXcode.mm |
||
|
|
1681cda855 |
lx: async calls run on workers that stay, not a thread per call
Every blocking request (a wait with a deadline) started a thread of its own, which in the dext means creating a dispatch queue, and joined it afterwards. A wait whose fence had already signalled cost 46 us against 29 us for the same request without a deadline. Each client now keeps the workers it starts: a call goes to an idle one, or starts one while fewer than MLG_LX_MAX_ASYNC exist, so there are as many as calls ever overlapped. Since a client has at most that many calls out, a call never waits for a worker. The workers leave when the client is destroyed, after its calls returned. rt_lx_async_workers reports their number; test_lx_files checks that later calls reuse them. |
||
|
|
e14e2f8f9c |
display: copy what a buffer missed in VRAM, and move rows that scrolled
Each of the three framebuffers remembers the damage it missed while the others were drawn, and a frame copied that again from the client's surface, so a frame crossed PCIe with the damage of the last two or three frames, not only its own. The worker now copies what its buffer missed from the buffer it drew last (VRAM to VRAM, always the front or the pending one, so never the one being drawn); only the frame's own damage comes from the surface. The VRAM copies run on the first engine after the copies that drew the source buffer (scheduler dependencies) and the surface's copies on the other engine wait for them. PRESENT takes moves (rows that scrolled): width x height at (x, y) are the previous frame's pixels at (x, src_y). The worker copies them from the buffer drawn last, which holds that frame, before the frame's damage. A frame that replaces one in the mailbox, or comes before anything was drawn, has its moves (and the replaced frame's) copied from the surface: the rows they come from were never drawn. Moves outside the frame are refused. The request's reserved word becomes the move count (old agents send 0), moves follow the rectangles, at most 32 and 4096 bytes in all. The statistics become version 3: bytes is what came from the surface, vram_bytes what was copied in VRAM, moved_rows and moves_dropped. test_display_pipeline: frames 2-4 take only their own damage from the surface and the rest in VRAM; scrolling under a fixed header and inside a window with mailbox replacement, and moves at the frame's edges, leave every scanout pixel equal to the surface; moves past the frame refused. |
||
|
|
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. |
||
|
|
e90d2141cb |
display: a client's framebuffers on the output's planes (LX_SCANOUT)
A process that renders on the GPU can now show its frames on the monitor the display output drives with no copy: its framebuffers go into the output worker's own commits, which stays the only committer. - Linux-file clients open the primary node (MLG_LX_DEV_PRIMARY). drm_open makes the first opener DRM master; the display hooks drop that before the file is installed, under the display lock, so the driver's own modesets keep working. The node carries the KMS queries and ADDFB2, RMFB and CLOSEFB (lx_describe.c), nothing that changes the display. - LX_SCANOUT (selector 104): ATTACH (one client per output, which gets a free overlay plane of the CRTC), TEST, PRESENT, DETACH, STATE. A frame goes on the primary plane in place of the desktop, whose frames then wait in the mailbox and are counted as held, or on the overlay plane at a rectangle over the desktop. The client's syncobj gets the flip's fence at the commit; the commit waits for the rendering through the framebuffer's implicit fences. DETACH, and a client going away, put the desktop back before its framebuffers can go. - The worker builds each commit from the desktop buffer and the client's frame; client flips do not count as desktop frames in the statistics the agent reads. - libmlg_drm: /dev/dri/cardN, mlg_scanout and the IOKit transport's LX_SCANOUT; the loopback transport sets the display hooks as the dext does. |
||
|
|
bb6412357c |
Stop CPU access to the VRAM aperture once the GPU has left the bus
A Thunderbolt power-off of the R9700 with the display mirrored panicked the Mac (panic-full-2026-10-03-200811: "LLC Bus error (Slave error) ... NC Write ... uncorrectable", the panicked task the 235 dext). The faulting thread, symbolized against the installed binary (3C1A7727-6854-3A29-9D61-CD15EFA13081), was a DRM worker removing a framebuffer (drm_mode_rmfb_work_fn, atomic_remove_fb): the output's teardown deletes its scanout buffers, which commits the plane off, and DC sent the DMUB its commands (set_pixel_clock_dmcub -> dmub_srv_fb_cmd_execute) by copying them into the DMUB inbox in VRAM with linuxu_device_memcpy, a CPU store through the dext's mapping of BAR0. Registers and doorbells go through kernel IOPCIDevice calls, which the kernel refuses for a vanished device (and the removal already skips: no_hw_access); a store through a user mapping to a device that is gone is an uncorrectable bus error on Apple silicon, not an error the process can see. Linux takes the aperture away on hot unplug (amdgpu_device_unmap_mmio). Here it is gated: the device string functions (every memcpy, memset, memmove and memcmp in the driver, which is how the DMUB inbox and kmap'd VRAM are written) skip stores into the aperture and read all ones from it once the device is known gone. It is known gone at the first of: rt_removal_begin, the dext's removal notification, or a register read of all ones after which the device no longer answers a configuration read (checked at most every 10 ms, through the kernel), which DC's own register reads (the DMUB inbox pointers) hit before it writes the inbox. The display statistics now count the driver's CPU accesses to the aperture. test_display_pipeline: with the display live (flips writing registers, copies on SDMA), the device leaves the bus with a frame queued; from then on no register write, no SDMA copy and no store into the aperture happen, aperture loads read all ones, and the output stops. |
||
|
|
3266899b74 |
display: copy a region redrawn in place once per flip
Measured on the R9700 (build 235, the Dell at 2560x1440): a window redrawing a 1732x1140 region every frame made every flip copy about 24.8 MB from the capture surface, three times the region: the frame's damage plus the same region again for each scanout buffer that had missed it, kept as separate rectangles. At 0.73 ms per MiB over Thunderbolt that is 17.3 ms of copy per 16.7 ms frame, so frames were replaced before they could flip (55 flips/s) and the picture lagged; a full-screen workload stopped the output when its copies backed up past the flip timeout. Damage now folds a rectangle into any it overlaps closely (contained, equal, or overlapping so the box is no larger than the two), so the region stays one rectangle and is copied once; damage covering nine tenths of the frame becomes one whole-frame copy. The flip wait first waits for its own copies (bounded at 2 s, as GPU work), then for the flip (200 ms), and says which did not complete. printk_once and the DRM *_ONCE messages are now once per call site: DM's MST/DSC check logged "dsc precompute is not needed" on every commit, sixty times a second, filling the kernel log. The display agent also finishes launching as a background agent only after its virtual display has a mode: made an NSApplication earlier, the process never saw the new display's modes. test_display_pipeline: a window redrawn in place with an item inside it copies the window's bytes once per flip. |
||
|
|
a7f4f41f99 |
linuxu: HZ is 1000
At HZ=100 a millisecond timeout became a 10 ms jiffy, so KFD's WAIT_EVENTS and every msecs_to_jiffies timeout was rounded up to 10 ms. Nothing ticks in linuxu (jiffies are read from the clock and every sleep is a deadline), so a 1 ms jiffy costs nothing. The jiffies test checks the 1000 Hz conversions. |
||
|
|
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). |
||
|
|
33e6465ef2 |
dext: KFD signal events and asynchronous event waits (selectors 86, 87)
EVENT creates, destroys and sets a KFD signal event of the client's KFD process and reports its id, trigger and mailbox address for an amd_signal_t. EVENT_WAIT is asynchronous: the dext registers the wait and hands it to a wait-pool thread (rt/wait_pool.h: threads made on demand, idle ones blocked with no timeout), which sleeps in WAIT_EVENTS until KFD's interrupt handler signals an event or the timeout passes, then completes the client's call. A wait the pool cannot take is refused (-EAGAIN), never run on the caller's queue. The HSA runtime does not use these yet. |
||
|
|
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. |
||
|
|
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. |
||
|
|
fa4db960db |
rt: the board's identity and the monitor on each connector
rt_device_identity() copies what the amdgpu device knows after its probe: VRAM size, type and width, CU count, the GC IP version, KFD's ISA target, the VBIOS part number, version, build and date, and the FRU board name. These are the values Linux shows in sysfs and AMDGPU_INFO; nothing is derived per board. rt_display_monitor() reports one connector's monitor from the state the last probe left: the EDID monitor name (drm_edid_get_monitor_name) and the display_info physical size. No detection, no AUX or DDC traffic. libdrm's product-name table moves to rt/amdgpu_ids.h so libmlg_drm and the dext use the same one. test-dm-offline checks both on its fixture R9700 device. |
||
|
|
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. |
||
|
|
4ba7b56afd |
display: fixes from the first hardware run of build 232
- IMPORT failed on the R9700 with PrepareForDMA refusing the client's descriptor: the import asked for up to 64 segments, and IODMACommand::PrepareForDMA takes at most 32 (its IIG declaration passes IOAddressSegment segments[32]). DEXT_DMA_IMPORT_SEGMENTS_MAX is 32, the mocks assert it, and a refused PrepareForDMA logs its code. - PROBE, SHOW, OFF, STATUS and MODES failed with a bad argument from the host app: the frame ops raised MLG_DISPLAY_WORDS to 2 and these ops required it too. They take and return one status word again; the host app asks for two, which every build accepts. |
||
|
|
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. |
||
|
|
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). |
||
|
|
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. |
||
|
|
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. |
||
|
|
2734dfe2de |
display: an output a display agent feeds, and PRESENT
rt_display_output() lights one connector at an exact mode (size and refresh within 50 mHz of one of its probed modes; -EINVAL otherwise) with two framebuffers, recording the configuration before it as the test pattern does; off and stop restore it. rt_display_present() copies an imported surface's dirty rectangles into the framebuffer not on screen with SDMA, together with the previous frame's rectangles (that buffer is a frame behind; a whole frame when it is stale or the damage overflowed), then flips to it with drm_client_modeset_commit(), a plane update that completes on vblank. A failed copy or flip is reported with its step's errno and leaves the screen on the buffer it was on. test-dm-offline: no mode at 59.000 Hz and a connector without a sink are refused; [email protected] is lit with the output marker; a present without a surface and a present with no output are refused. |
||
|
|
a5b6464702 |
rt: check that the GPU sees a client's writes, and imports by owner
rt_surface_verify() reads 64 ranges of 256 bytes spread over an imported surface with SDMA into a GTT buffer and, given a CPU view of the client's memory, with the CPU, and counts the dwords that differ from rt_surface_pattern(seed) — the pattern the client wrote. It is the hardware test of whether the client's pages stay mapped and coherent after the call that imported them. Imports are kept in a table by owner (a user client) and handle: rt_surface_add/get/remove, remove_owner for a client's stop, remove_all for a session close; the provider context and the geometry are available to the caller. test-surface-import: three seeds read back exactly by the GPU and the CPU view, and a wrong seed mismatches every dword; the table's lookups, refusals and the three removals each release their surfaces. |
||
|
|
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. |
||
|
|
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. |