Repository navigation
poly,hk: Replace CAS loop in poly_heap_try_alloc_offs with lock-free fetch-add - #1484
Conversation
Replacing poly_heap_try_alloc_offs() with a global CAS loop on poly_heap::bottom causes severe retry contention under high-concurrency tessellation dispatches where thousands of threads allocate patch points concurrently. Preserve overflow latching and wrap-free reservation safety without the CAS spin-loop: - Count poly_heap::bottom in 16-byte units and add a large-request admission counter (poly_heap::large_demand) so normal allocations use a single lock-free atomic_fetch_add() while keeping both counters provably below UINT32_MAX across in-flight lanes. - Keep atomic publication of the shared device overflow status word on heap reset, clear both bottom and large_demand, and record both the poly_heap descriptor span and status word in compute attachments. - Update KosmicKrisp and the robust-index / heap-math tests for the unit-counted cursor and large_demand reset. Signed-off-by: DjDeveloperr <hey@djdev.me>
|
Merge readiness at
Areas: Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels. |
There was a problem hiding this comment.
Verdict: MERGE at 342392e
Checked: Read the full diff against aurora-wip c5bf0a7 (geometry.h, poly_heap_math.h, query.cl/query.h, hk_query_pool.c, draws.cl, kk_cmd_draw.c, tests) and every user of struct poly_heap at the head (hk_cmd_draw.c slot init, hk_device.c descriptor sizing by sizeof, gallium agx_state.c per-batch upload, kk heap reset, libkk/libagx allocators).
Checked: Tried to break the fetch-add allocator. Successful ranges are disjoint because each comes from its own atomic_fetch_add return value plus a fits check. Every failure path leaves the reset-time check (bottom > size/16) true, so the status word is always set: (a) cursor already > capacity; (b) oversize request latches capacity+1 with atomic_fetch_max; (c) large-admission rejection only happens after a request with old demand <= C/Q pushed demand to >= floor(C/Q)+1 quanta, so admitted large units exceed C and their unconditional cursor adds overflow it; (d) small overshoot leaves the cursor > C. Rejected large requests add to large_demand only after it is already closed, so they cannot close admission on their own.
Checked: Wrap bounds: with C = UINT32_MAX/16, Q = 16384, in-flight = 196608, 4C+1+in-flight*(Q-1) = 4294770685 and (1+in-flight)(C/Q) = 3221045247, both <= 4294967295, so both static_asserts hold. Offsets out are old16 <= size, no u32 overflow. The robust-index CAS path uses unit counts on a 16-byte-aligned alloc_size_B (agx_robust_index_shadow_sizes aligns to 16), so the floor division is exact.
Checked: Built the head in the B1 x86 container (meson, -Dvulkan-drivers=asahi -Dbuild-tests=true, mesa-clc/precomp on, so libagx.cl compiles with the new OpenCL static_asserts): BUILD-OK, meson test 266/266 OK. Also built and ran poly_heap_math_tests standalone with gcc: PASS.
Checked: No AI attribution in the commit message or PR body; no Apple-derived material in the diff.
Follow-ups:
- The wrap margin is about 196k units. The bound assumes at most 128 cores x 1024 resident threads x 1.5. A future part over that needs POLY_HEAP_MAX_IN_FLIGHT raised, or the assert will fail at libagx build time (safe, but worth a comment pointing at it).
- draws.cl robust-index reservations now also refuse once large admission is closed, even if the CAS would still fit. That only happens in a pass already bound to report overflow, so the result is the same; noting it as a deliberate behaviour change.
- The
selftestcheck is red on this head. It is the repo's agent-policy-test.sh ("push to the default branch heals it" FAIL), the same failure on #1482/#1485/#1488, and unrelated to this diff.
2nd-gen hardware verification — Apple M3 Pro (
|
| Workload | Baseline c5bf0a743d3c (ms) |
Proposed 342392ea7d70 (ms) |
Speedup | Δ time | Pixel CRC32 (32/32) |
|---|---|---|---|---|---|
high_patch_4 |
5.582 / 5.584 / 5.585 | 3.295 / 3.296 / 3.296 | 1.6943× | −40.98% | 0xbd6a4dd6 (exact) |
indirect_large |
4.392 / 4.393 / 4.394 | 4.391 / 4.392 / 4.394 | 1.0003× | −0.03% | 0xe1ce10cb (exact) |
contention_16 |
7.078 / 7.078 / 7.079 | 7.077 / 7.078 / 7.079 | 1.0001× | −0.01% | 0x7a75dcd7 (exact) |
large_32 |
3.317 / 3.317 / 3.318 | 3.318 / 3.318 / 3.318 | 0.9997× | +0.03% | 0x6bd27aa2 (exact) |
- Overflow & smoke checks:
- Small-allocation tessellation overflow (
--patches 4096 --draws 6 --tess-outer 16 --tess-inner 16): cleanVK_ERROR_DEVICE_LOST (-4), 0 GPU faults. - Indirect
large_demandoverflow (--patches 65536 --draws 8 --tess-outer 4 --tess-inner 4 --indirect): cleanVK_ERROR_DEVICE_LOST (-4), 0 GPU faults. gpubench-vk(GB_VERIFY=1):render.mdi(168.79 → 168.92 µs, CRC0x06f8412a) andrender.deferred(1310.08 → 1310.77 µs, CRC0x02cfe9a54) PASS.
- Small-allocation tessellation overflow (
- Health: GPU
dmesgfaults 0 → 0, recoveries 0 → 0, hang kills 0 → 0, failed render/compute classes 0/0 → 0/0.
What: Replace the
atomic_compare_exchange_weakspin-loop inpoly_heap_try_alloc_offs()(introduced by #1424) with lock-free 16-byte-unitatomic_fetch_add()plus alarge_demand(>= 256 KiB) admission counter, while preserving atomic overflow status publication inquery.cland fullsizeof(struct poly_heap)+ status-word compute attachment tracking inhk_finish_dispatched_imm_writes().Tested: Apple M5 Pro J714s (G17S B1) at
342392ea7d70f0350c16b7a46c77689156c6dde3against its parentc5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15b. Across four tessellation workloads, per-run batch medians dropped from106.321 → 0.746 ms(142.45×,−99.30%) onhigh_patch_4,15.572 → 1.051 ms(14.82×,−93.25%) onindirect_large,11.930 → 1.007 ms(11.84×,−91.56%) oncontention_16, and0.964 → 0.506 ms(1.91×,−47.55%) onlarge_32, with bit-exact framebuffer pixel CRC32 matches across all 32/32 runs.hk_vulkan_heap_overflowpassed, small andlarge_demandtessellation overflows cleanly returnedVK_ERROR_DEVICE_LOSTwith 0 GPU faults,poly_heap_math_testspassed, andmesa:asahipassed 237/237.Risk: Two-way door for geometry, tessellation, and robust-index passes using
struct poly_heapon AGX and KosmicKrisp. Compile-timestatic_assertbounds guarantee neitherbottomnorlarge_demandcan wrapUINT32_MAXacross in-flight lanes before heap reset;struct poly_heapgrows from 16 B to 32 B.Not yet: Hardware evidence covers Apple M5 Pro J714s (G17S B1). The KosmicKrisp reset update (
kk_cmd_draw.c) was checked by build and shared heap-math tests rather than separately on macOS hardware.Details
src/poly/poly_heap_math.h,src/poly/geometry.h: Countpoly_heap::bottomin 16-byte units (POLY_HEAP_UNIT_B) and addpoly_heap::large_demandfor allocations at or above256 KiB(POLY_HEAP_LARGE_QUANTUM). Replace the CAS spin-loop inpoly_heap_try_alloc_offs()with a single lock-freeatomic_fetch_add(), latch oversize requests withatomic_fetch_max(cursor, capacity + 1), and retain compile-timestatic_assertproofs preventing counter wrap across resident AGX threads.src/asahi/libagx/query.cl,src/asahi/libagx/query.h,src/asahi/vulkan/hk_query_pool.c: Pass thestruct poly_heapbase address toLIBAGX_IMM_WRITE_HEAP_RESET, checkheap->bottom > heap->size / POLY_HEAP_UNIT_B, atomically store1uto the device overflow status word on exhaustion, clear bothbottomandlarge_demand, and track bothsizeof(struct poly_heap)and theuint32_tstatus word indst->compute_attachmentsinsidehk_finish_dispatched_imm_writes().src/asahi/libagx/draws.cl,src/kosmickrisp/vulkan/kk_cmd_draw.c, tests: Updatelibagx_draw_robust_index_impl()to gate onpoly_heap_large_admission_open(heap)and unit-counted offsets, zerolarge_demandon KosmicKrisp heap reset, and updatepoly_heap_math_tests.candrobust-index-exhaustion.py.Evidence
Testing
Native AArch64 Arch Linux ARM on one J714s Apple MacBook Pro (14-inch, M5 Pro, 2026), GPU Apple M5 Pro (G17S B1), kernel
7.3.0-m5-pr67(#171 SMP PREEMPT Fri Nov 27 18:15:08 UTC 2026 aarch64), GPU firmware27.0 (26A428), SLC enabled on 16 planes, stock system Mesa unmodified (pacman -Qkk mesa:128 total files, 0 altered files). GPU fault lines indmesgwere zero before, after overflow tests, and after cleanup.libvulkan_asahi.soSHA-256c5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15b8eded9488d315b76816ef05b2952e1df84f28949164b0b427237c6d19f2f4638342392ea7d70f0350c16b7a46c77689156c6dde3c1d6e723a92767fc0063230851eb102c81c7db45fe29ddaebeb8d017e77f1ea1At publication, live
origin/aurora-wiphad advanced tof6ea9a1be834b1e56b62f4a1dc63e041a74e4b83with changes outside this PR's modified files.c5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15bis an ancestor oforigin/aurora-wip, and342392ea7d70f0350c16b7a46c77689156c6dde3merges cleanly with zero conflicts (git merge-tree --write-tree origin/aurora-wip 342392ea7d70). The table reports the exact tested parent baseline.Both Mesa 26.3.0-devel ICDs were built natively on J714s with identical release options using GCC
16.1.1 20260430(-Dbuildtype=release -Db_ndebug=true -Dvulkan-drivers=asahi -Dgallium-drivers= -Dplatforms=x11,wayland -Dllvm=enabled -Dglx=disabled -Degl=disabled -Dgbm=disabled -Dgles1=disabled -Dgles2=disabled -Dopengl=false -Dglvnd=disabled -Dbuild-tests=false -Dvideo-codecs= -Dvulkan-layers= -Dtools= -Dvalgrind=disabled -Dwerror=false), staged into tmpfs, and pinned per process withVK_DRIVER_FILESunderLC_ALL=Cwith debug/trace environment variables unset during timing runs.Benchmark
The standalone C/Vulkan tessellation benchmark
poly_heap_tess_bench.c(SHA-256bcabfe37975eb8cd1543c95765fa3201038f1eeb7e5c04fc4c62f6d1696d0bd4, built withgcc -O2 -Wall -Wextra -o poly_heap_tess_bench poly_heap_tess_bench.c -lvulkan -lm) drives a fullVS -> TCS -> libagx tessellator -> TES -> FSpipeline into an offscreen256×256VK_FORMAT_R8G8B8A8_UNORMtarget, timingvkCmdBeginRenderPassthrough post-vkCmdEndRenderPass(includingpoly_heap_try_alloc_offs()and post-graphicsLIBAGX_IMM_WRITE_HEAP_RESET) with GPU timestamp queries and verifying rendered output via pixel CRC32 readback.Commands executed per pinned ICD (
VK_DRIVER_FILES):Four independent processes per arm ran in interleaved ABBA ABBA order (
base, pr3, pr3, base, base, pr3, pr3, base), each executing 4 warmup + 32 timed GPU batches (128 timed batches per arm per workload). Cells show min / median / max across the 4 per-run medians in ms / batch (lower is better); speedups and percentage changes compare the medians.c5bf0a743d3(ms)342392ea7d70(ms)high_patch_4(8192×4, tess 4)0xbd6a4dd6(50,176 px, exact)indirect_large(4096×4, tess 8, indirect)0xe1ce10cb(50,176 px, exact)contention_16(2048×4, tess 16)0x7a75dcd7(50,176 px, exact)large_32(512×2, tess 32)0x6bd27aa2(25,921 px, exact)Run-to-run medians varied by
< 0.6%onhigh_patch_4,contention_16, andindirect_large, and by2.3%(baseline) /5.2%(proposed, one run at0.532 msvs three at0.505–0.506 ms) onlarge_32. Pooled across all 128 iterations per arm, baseline and proposed distributions had zero overlap on every workload; all samples (including occasional desktop-compositor single-iteration maxima such as1.272 msonindirect_large) are included unmodified in the raw results.Path verification and correctness
VK_LOADER_DEBUG=driverandVkPhysicalDeviceDriverPropertiesconfirmed each arm loaded its staged tmpfslibvulkan_asahi.so(git-c5bf0a743dvsgit-342392ea7d).libagx.spvSPIR-V atomic audit (spirv-dis): All 4 compiled copies ofpoly_heap_try_alloc_offsreplacedOpAtomicCompareExchange(5 → 1total inlibagx.spv, leaving onlylibagx_draw_robust_index_impl) with lock-freeOpAtomicIAdd(4 → 12),OpAtomicUMax(0 → 4), andpoly_heap_large_admission_open(OpAtomicLoad5 → 9).hk_vulkan_heap_overflow: PASS on both baseline and proposed (fitting 1,024 points →VK_SUCCESS, overflowing 33,554,432 points →VK_ERROR_DEVICE_LOST, 0 GPU faults).--patches 4096 --draws 6 --tess-outer 16 --tess-inner 16): PASS (geometry heap overflow,VK_ERROR_DEVICE_LOST = -4, 0 GPU faults).large_demand(>= 256 KiB) heap overflow (--patches 65536 --draws 8 --tess-outer 4 --tess-inner 4 --indirect): PASS (geometry heap overflow,VK_ERROR_DEVICE_LOST = -4, 0 GPU faults).poly_heap_math_testsPASS;mesa:asahi237/237 PASS.Benchmark source, runner script, summary, SPIR-V atomic audit, and raw outputs from both arms