Skip to content

poly,hk: Replace CAS loop in poly_heap_try_alloc_offs with lock-free fetch-add - #1484

Merged
DjDeveloperr merged 2 commits into
aurora-wipfrom
djdev/poly-heap-lockfree-alloc
Dec 1, 2026
Merged

DjDeveloperr merged 2 commits into
aurora-wipfrom
djdev/poly-heap-lockfree-alloc

Conversation

@DjDeveloperr

Copy link
Copy Markdown

What: Replace the atomic_compare_exchange_weak spin-loop in poly_heap_try_alloc_offs() (introduced by #1424) with lock-free 16-byte-unit atomic_fetch_add() plus a large_demand (>= 256 KiB) admission counter, while preserving atomic overflow status publication in query.cl and full sizeof(struct poly_heap) + status-word compute attachment tracking in hk_finish_dispatched_imm_writes().

Tested: Apple M5 Pro J714s (G17S B1) at 342392ea7d70f0350c16b7a46c77689156c6dde3 against its parent c5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15b. Across four tessellation workloads, per-run batch medians dropped from 106.321 → 0.746 ms (142.45×, −99.30%) on high_patch_4, 15.572 → 1.051 ms (14.82×, −93.25%) on indirect_large, 11.930 → 1.007 ms (11.84×, −91.56%) on contention_16, and 0.964 → 0.506 ms (1.91×, −47.55%) on large_32, with bit-exact framebuffer pixel CRC32 matches across all 32/32 runs. hk_vulkan_heap_overflow passed, small and large_demand tessellation overflows cleanly returned VK_ERROR_DEVICE_LOST with 0 GPU faults, poly_heap_math_tests passed, and mesa:asahi passed 237/237.

Risk: Two-way door for geometry, tessellation, and robust-index passes using struct poly_heap on AGX and KosmicKrisp. Compile-time static_assert bounds guarantee neither bottom nor large_demand can wrap UINT32_MAX across in-flight lanes before heap reset; struct poly_heap grows 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: Count poly_heap::bottom in 16-byte units (POLY_HEAP_UNIT_B) and add poly_heap::large_demand for allocations at or above 256 KiB (POLY_HEAP_LARGE_QUANTUM). Replace the CAS spin-loop in poly_heap_try_alloc_offs() with a single lock-free atomic_fetch_add(), latch oversize requests with atomic_fetch_max(cursor, capacity + 1), and retain compile-time static_assert proofs 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 the struct poly_heap base address to LIBAGX_IMM_WRITE_HEAP_RESET, check heap->bottom > heap->size / POLY_HEAP_UNIT_B, atomically store 1u to the device overflow status word on exhaustion, clear both bottom and large_demand, and track both sizeof(struct poly_heap) and the uint32_t status word in dst->compute_attachments inside hk_finish_dispatched_imm_writes().
  • src/asahi/libagx/draws.cl, src/kosmickrisp/vulkan/kk_cmd_draw.c, tests: Update libagx_draw_robust_index_impl() to gate on poly_heap_large_admission_open(heap) and unit-counted offsets, zero large_demand on KosmicKrisp heap reset, and update poly_heap_math_tests.c and robust-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 firmware 27.0 (26A428), SLC enabled on 16 planes, stock system Mesa unmodified (pacman -Qkk mesa: 128 total files, 0 altered files). GPU fault lines in dmesg were zero before, after overflow tests, and after cleanup.

Arm Mesa revision Staged libvulkan_asahi.so SHA-256
Baseline (exact parent of PR head) c5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15b 8eded9488d315b76816ef05b2952e1df84f28949164b0b427237c6d19f2f4638
Proposed 342392ea7d70f0350c16b7a46c77689156c6dde3 c1d6e723a92767fc0063230851eb102c81c7db45fe29ddaebeb8d017e77f1ea1

At publication, live origin/aurora-wip had advanced to f6ea9a1be834b1e56b62f4a1dc63e041a74e4b83 with changes outside this PR's modified files. c5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15b is an ancestor of origin/aurora-wip, and 342392ea7d70f0350c16b7a46c77689156c6dde3 merges 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 with VK_DRIVER_FILES under LC_ALL=C with debug/trace environment variables unset during timing runs.

Benchmark

The standalone C/Vulkan tessellation benchmark poly_heap_tess_bench.c (SHA-256 bcabfe37975eb8cd1543c95765fa3201038f1eeb7e5c04fc4c62f6d1696d0bd4, built with gcc -O2 -Wall -Wextra -o poly_heap_tess_bench poly_heap_tess_bench.c -lvulkan -lm) drives a full VS -> TCS -> libagx tessellator -> TES -> FS pipeline into an offscreen 256×256 VK_FORMAT_R8G8B8A8_UNORM target, timing vkCmdBeginRenderPass through post-vkCmdEndRenderPass (including poly_heap_try_alloc_offs() and post-graphics LIBAGX_IMM_WRITE_HEAP_RESET) with GPU timestamp queries and verifying rendered output via pixel CRC32 readback.

Commands executed per pinned ICD (VK_DRIVER_FILES):

./poly_heap_tess_bench --patches 8192 --draws 4 --tess-outer 4 --tess-inner 4 --iters 32 --warmup 4
./poly_heap_tess_bench --patches 2048 --draws 4 --tess-outer 16 --tess-inner 16 --iters 32 --warmup 4
./poly_heap_tess_bench --patches 512 --draws 2 --tess-outer 32 --tess-inner 32 --iters 32 --warmup 4
./poly_heap_tess_bench --patches 4096 --draws 4 --tess-outer 8 --tess-inner 8 --indirect --iters 32 --warmup 4

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.

Workload Baseline c5bf0a743d3 (ms) Proposed 342392ea7d70 (ms) Speedup Change Pixel CRC32 (all 8 runs)
high_patch_4 (8192×4, tess 4) 106.217 / 106.321 / 106.452 0.745 / 0.746 / 0.747 142.45× −99.30% 0xbd6a4dd6 (50,176 px, exact)
indirect_large (4096×4, tess 8, indirect) 15.547 / 15.572 / 15.594 1.048 / 1.051 / 1.052 14.82× −93.25% 0xe1ce10cb (50,176 px, exact)
contention_16 (2048×4, tess 16) 11.892 / 11.930 / 11.939 1.006 / 1.007 / 1.008 11.84× −91.56% 0x7a75dcd7 (50,176 px, exact)
large_32 (512×2, tess 32) 0.957 / 0.964 / 0.979 0.505 / 0.506 / 0.532 1.91× −47.55% 0x6bd27aa2 (25,921 px, exact)

Run-to-run medians varied by < 0.6% on high_patch_4, contention_16, and indirect_large, and by 2.3% (baseline) / 5.2% (proposed, one run at 0.532 ms vs three at 0.505–0.506 ms) on large_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 as 1.272 ms on indirect_large) are included unmodified in the raw results.

Path verification and correctness

  • ICD verification: VK_LOADER_DEBUG=driver and VkPhysicalDeviceDriverProperties confirmed each arm loaded its staged tmpfs libvulkan_asahi.so (git-c5bf0a743d vs git-342392ea7d).
  • Compiled libagx.spv SPIR-V atomic audit (spirv-dis): All 4 compiled copies of poly_heap_try_alloc_offs replaced OpAtomicCompareExchange (5 → 1 total in libagx.spv, leaving only libagx_draw_robust_index_impl) with lock-free OpAtomicIAdd (4 → 12), OpAtomicUMax (0 → 4), and poly_heap_large_admission_open (OpAtomicLoad 5 → 9).
  • Hardware overflow & correctness checks on J714s:
    • Framebuffer pixel CRC32 and non-zero pixel counts matched identically across all 32/32 runs (all 4 workloads × 8 runs).
    • 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).
    • Tessellation small-allocation heap overflow (--patches 4096 --draws 6 --tess-outer 16 --tess-inner 16): PASS (geometry heap overflow, VK_ERROR_DEVICE_LOST = -4, 0 GPU faults).
    • Indirect tessellation 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).
  • Host/unit checks: poly_heap_math_tests PASS; mesa:asahi 237/237 PASS.

Benchmark source, runner script, summary, SPIR-V atomic audit, and raw outputs from both arms

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>
@DjDeveloperr
DjDeveloperr requested review from a team as code owners December 1, 2026 12:54
@github-actions github-actions Bot added area:borealis Area from CODEOWNERS (bot) area:compiler Area from CODEOWNERS (bot) door:two-way Revertible or not, from Merge risk (bot) needs-review No approving review from Core or Omarchy Mac yet (bot) labels Dec 1, 2026
@github-actions

github-actions Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Merge readiness at 51b8c7ea: not ready yet

Check Detail
CI at head running running: policy, selftest, build-test, build-test
Review no needs one approving review from Core or Omarchy Mac (not the author)
Requested changes ok none
Hardware row at head ok the PR body at 342392ea; the changed files are byte-identical at 51b8c7ea
Conflicts ok none
PR text ok Risk: two-way · for geometry, tessellation, and robust-index passes using struct polyheap on AGX and KosmicKrisp. Compile-time staticassert bounds guarantee neither bottom nor largedemand can wrap UINT32MAX across in-flight lanes before heap reset; struct polyheap grows from 16 B to 32 B.

Areas: area:borealis, area:compiler

Updated by pr-readiness on pushes, edits, reviews and comments, and on a schedule. Rules: merge policy · labels.

@github-actions github-actions Bot added the ci-failing A check failed at the PR head (bot) label Dec 1, 2026

@aurora-silicon-review aurora-silicon-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 selftest check 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.

@DjDeveloperr

Copy link
Copy Markdown
Author

2nd-gen hardware verification — Apple M3 Pro (J516s, G15S B1 / HAL200 / AGX3B) at 342392ea7d70

  • Hardware / Kernel: Apple MacBook Pro 16" M3 Pro (J516s, G15S B1), stock Linux 7.3.0 (#1 SMP PREEMPT Wed Nov 25 01:32:57 EST 2026, boot_id=789b6322-503e-4622-9644-78f699a2dfef), all 6 MCC planes 0x00002100, system mesa-aurora untouched (pacman -Qkk mesa: 79 files, 0 altered).
  • Build & ICD pinning: Native AArch64 release builds (vulkan-drivers=[asahi]), pinned via VK_DRIVER_FILES, MESA_SHADER_CACHE_DISABLE=true, LC_ALL=C, headless; VK_LOADER_DEBUG=driver vulkaninfo --summary confirmed exact staged binaries and embedded revisions:
    • Baseline c5bf0a743d3c0c0b31cbfd53c5d3ca10e5c0a15b: libvulkan_asahi.so SHA-256 83c6b405133020755976beaadf1de92c7d068e762d0dfe35aea681be5dc06e11
    • Proposed 342392ea7d70f0350c16b7a46c77689156c6dde3: libvulkan_asahi.so SHA-256 676014bf13992145aae4a61542ec332495446f9f3c3c38ae035ddb9747ee3c65
  • Paired ABBA ABBA tessellation timing (4 runs/arm × 32 timed batches, GPU ms/batch, min / median / max):
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): clean VK_ERROR_DEVICE_LOST (-4), 0 GPU faults.
    • Indirect large_demand overflow (--patches 65536 --draws 8 --tess-outer 4 --tess-inner 4 --indirect): clean VK_ERROR_DEVICE_LOST (-4), 0 GPU faults.
    • gpubench-vk (GB_VERIFY=1): render.mdi (168.79 → 168.92 µs, CRC 0x06f8412a) and render.deferred (1310.08 → 1310.77 µs, CRC 0x02cfe9a54) PASS.
  • Health: GPU dmesg faults 0 → 0, recoveries 0 → 0, hang kills 0 → 0, failed render/compute classes 0/0 → 0/0.

@github-actions github-actions Bot removed the ci-failing A check failed at the PR head (bot) label Dec 1, 2026
@DjDeveloperr
DjDeveloperr merged commit 7c053c7 into aurora-wip Dec 1, 2026
14 checks passed
@DjDeveloperr
DjDeveloperr deleted the djdev/poly-heap-lockfree-alloc branch December 1, 2026 22:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:borealis Area from CODEOWNERS (bot) area:compiler Area from CODEOWNERS (bot) door:two-way Revertible or not, from Merge risk (bot) needs-review No approving review from Core or Omarchy Mac yet (bot)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant