From 90ebc113a820bea143b77e69ab59734394019b87 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 09:51:29 -0500 Subject: [PATCH 1/2] borealis: refit M5 acceleration structures from their build's plan An M5 update re-ran the whole native encode for every structure: the five planner phases, the node and envelope jobs, and a parent-linking pass, each behind its own barrier, one structure after another. GTA V updates about 200 bottom-level structures a frame, which came to about 7000 dispatches and 5100 barriers. A build that allows updates now also keeps its plan after the retained IR topology: the plan state, the envelope job, each IR node's parent and the node jobs. An update regenerates the IR leaves, refits the IR internal nodes bottom up from the saved parents, restores the saved jobs with its own IR and image addresses, and re-encodes them into the same slots, without planning. Every step runs for all updates of a build call before the next, so a call waits at a handful of barriers instead of several per structure. An update into another structure also copies the topology and the plan there. Updatable structures grow by 68 bytes per IR node for the saved plan. Signed-off-by: DjDeveloperr --- .../vulkan/bvh/agx3_m5_legacy_refit.comp | 83 ++++-- src/asahi/vulkan/bvh/hk_build_interface.h | 54 +++- .../vulkan/hk_m5_acceleration_structure.c | 262 ++++++++++++++---- 3 files changed, 328 insertions(+), 71 deletions(-) diff --git a/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp b/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp index 0cec091fabe5..042e97c7286a 100644 --- a/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp +++ b/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp @@ -1,6 +1,8 @@ /* Copyright 2026 Aurora Silicon * SPDX-License-Identifier: MIT - * Refit a retained binary topology without sorting or repartitioning. + * Refit a retained binary topology without sorting or repartitioning, and + * keep the build's plan so the refit re-encodes the same native nodes + * (see hk_m5_refit_args for the phases). */ #version 460 #extension GL_GOOGLE_include_directive : require @@ -19,19 +21,23 @@ layout(local_size_x = 64) in; layout(push_constant) uniform CONSTS { hk_m5_refit_args args; }; struct refit_node { uint parent; uint arrivals; uint reserved[2]; }; TYPE(refit_node, 4); -uint source_index(uint child) + +REF(uint32_t) parent_of(uint64_t plan, uint id) { - uint offset = ir_id_to_offset(child); - return ir_id_to_type(child) == vk_ir_node_internal - ? args.leaf_bound + (offset - args.root_offset) / SIZEOF(vk_ir_box_node) - : offset / (args.root_offset / args.leaf_bound); + return INDEX(uint32_t, plan + uint64_t(HK_M5_PLAN_PARENTS), id); } + +REF(hk_agx3_leaf_job) retained_job(uint64_t plan, uint id) +{ + return INDEX(hk_agx3_leaf_job, plan + uint64_t(HK_M5_PLAN_JOBS(args.node_bound)), id); +} + void main() { uint id = gl_GlobalInvocationID.x; uint header_words = SIZEOF(vk_ir_header) / 4; uint internal_bound = args.node_bound - args.leaf_bound; - if (args.phase <= 1) { + if (args.phase == HK_M5_REFIT_SAVE_IR || args.phase == HK_M5_REFIT_PREPARE) { uint64_t retained_base = args.retained; /* The M5 retained copy covers the whole internal node capacity. */ uint words = header_words + internal_bound * (SIZEOF(vk_ir_box_node) / 4); @@ -39,7 +45,7 @@ void main() uint64_t addr = id < header_words ? uint64_t(args.header) + uint64_t(id)*4ul : args.intermediate_bvh + uint64_t(args.root_offset) + uint64_t(id-header_words)*4ul; REF(uint32_t) retained = REF(uint32_t)(retained_base + uint64_t(id)*4ul); - if (args.phase == 0) DEREF(retained) = DEREF(REF(uint32_t)(addr)); + if (args.phase == HK_M5_REFIT_SAVE_IR) DEREF(retained) = DEREF(REF(uint32_t)(addr)); else { uint value = DEREF(retained); if (id < 3) value = 0x7fffffffu; @@ -48,25 +54,60 @@ void main() DEREF(REF(uint32_t)(addr)) = value; } } - if (args.phase == 1 && id < args.node_bound) { - DEREF(INDEX(refit_node, args.parents, id)).parent = 0xffffffffu; + if (args.phase == HK_M5_REFIT_PREPARE && id < args.node_bound) DEREF(INDEX(refit_node, args.parents, id)).arrivals = 0; - } return; } - if (args.phase == 2) { - if (id >= DEREF(args.header).ir_internal_node_count) return; - REF(vk_ir_box_node) node = REF(vk_ir_box_node)(args.intermediate_bvh + - uint64_t(args.root_offset) + uint64_t(id)*uint64_t(SIZEOF(vk_ir_box_node))); - for (uint c = 0; c < 2; ++c) { - uint child = DEREF(node).children[c]; - if (child != VK_BVH_INVALID_NODE) - DEREF(INDEX(refit_node, args.parents, source_index(child))).parent = args.leaf_bound + id; + + if (args.phase == HK_M5_REFIT_SAVE_PLAN) { + /* Planning set every node's parent; inactive leaves and the root keep + * the ~0 it started from. */ + if (id < args.node_bound) + DEREF(parent_of(args.plan, id)) = + DEREF(INDEX(hk_agx3_plan_node, args.plan_nodes, id)).parent; + hk_agx3_plan_state state = DEREF(REF(hk_agx3_plan_state)(args.plan_state)); + if (id < state.job_count) + DEREF(retained_job(args.plan, id)) = + DEREF(INDEX(hk_agx3_leaf_job, args.plan_jobs, id)); + if (id == 0) { + DEREF(REF(hk_agx3_plan_state)(args.plan + uint64_t(HK_M5_PLAN_STATE))) = state; + hk_agx3_envelope_job envelope = + DEREF(REF(hk_agx3_envelope_job)(args.plan_envelope)); + envelope.bounds = REF(vk_ir_node)(uint64_t(envelope.bounds) - args.intermediate_bvh); + DEREF(REF(hk_agx3_envelope_job)(args.plan + uint64_t(HK_M5_PLAN_ENVELOPE))) = envelope; } return; } + + if (args.phase == HK_M5_REFIT_COPY_PLAN) { + if (id < HK_M5_PLAN_BYTES(args.node_bound) / 4u) + DEREF(INDEX(uint32_t, args.plan_copy, id)) = DEREF(INDEX(uint32_t, args.plan, id)); + return; + } + + /* REFIT: restore the plan with this update's addresses. */ + hk_agx3_plan_state state = + DEREF(REF(hk_agx3_plan_state)(args.plan + uint64_t(HK_M5_PLAN_STATE))); + if (id < state.job_count) { + hk_agx3_leaf_job job = DEREF(retained_job(args.plan, id)); + job.intermediate_bvh = args.intermediate_bvh; + job.output_bvh = args.output_bvh; + DEREF(INDEX(hk_agx3_leaf_job, args.plan_jobs, id)) = job; + } + if (id == 0) { + DEREF(REF(hk_agx3_plan_state)(args.plan_state)) = state; + hk_agx3_envelope_job envelope = DEREF( + REF(hk_agx3_envelope_job)(args.plan + uint64_t(HK_M5_PLAN_ENVELOPE))); + envelope.bounds = REF(vk_ir_node)(args.intermediate_bvh + uint64_t(envelope.bounds)); + envelope.output_bvh = args.output_bvh; + envelope.resource_id = args.resource_id; + DEREF(REF(hk_agx3_envelope_job)(args.plan_envelope)) = envelope; + } + + /* Then each leaf refits its ancestors; the last child to arrive at a + * node computes its bounds. */ if (id >= args.leaf_bound) return; - uint parent = DEREF(INDEX(refit_node, args.parents, id)).parent; + uint parent = DEREF(parent_of(args.plan, id)); for (uint steps = 0; parent != 0xffffffffu && steps < args.node_bound; ++steps) { REF(vk_ir_box_node) node = REF(vk_ir_box_node)(args.intermediate_bvh + uint64_t(args.root_offset) + uint64_t(parent-args.leaf_bound)*uint64_t(SIZEOF(vk_ir_box_node))); @@ -85,6 +126,6 @@ void main() bounds.max = max(bounds.max, DEREF(src).aabb.max); } DEREF(node).base.aabb = bounds; - parent = DEREF(INDEX(refit_node, args.parents, parent)).parent; + parent = DEREF(parent_of(args.plan, parent)); } } diff --git a/src/asahi/vulkan/bvh/hk_build_interface.h b/src/asahi/vulkan/bvh/hk_build_interface.h index 91bd166405fc..2ef9af265290 100644 --- a/src/asahi/vulkan/bvh/hk_build_interface.h +++ b/src/asahi/vulkan/bvh/hk_build_interface.h @@ -250,20 +250,72 @@ struct hk_agx3_refit_args { }; /* The separate M5 backend keeps its qualified IR-topology refit protocol. - * GEN1 uses hk_agx3_refit_args and the current retained-job protocol. */ + * GEN1 uses hk_agx3_refit_args and the current retained-job protocol. + * + * An updatable M5 structure keeps two things from its build, after its + * image: the IR header and internal nodes (the topology), and then the + * build's plan: the plan state, the envelope job, the IR parent of every IR + * node and the node jobs. An update refits the IR from the topology and + * re-encodes the same jobs into the same slots, so it never plans. + * + * Phases (agx3_m5_legacy_refit.comp): + * - SAVE_IR, at a build: copy the IR header and internal nodes into the + * structure. + * - PREPARE, at an update before its leaves: copy them back into scratch, + * reset the bounds and the active leaf count, and clear the arrival + * counters. + * - SAVE_PLAN, at a build after planning: copy the plan into the + * structure (the parents from the plan nodes). + * - REFIT, at an update after its leaves: recompute the bounds of the IR + * internal nodes bottom up, and restore the plan into encode scratch + * with this update's IR and image addresses. + * - COPY_PLAN, at an update into another structure: copy the plan. + */ +#define HK_M5_REFIT_SAVE_IR 0u +#define HK_M5_REFIT_PREPARE 1u +#define HK_M5_REFIT_SAVE_PLAN 2u +#define HK_M5_REFIT_REFIT 3u +#define HK_M5_REFIT_COPY_PLAN 4u + +/* The retained plan: the hk_agx3_plan_state, the hk_agx3_envelope_job with + * its bounds as a byte offset into the IR, a uint32_t IR parent per IR + * node (~0 for the root and for leaves in no node), then node_bound + * hk_agx3_leaf_jobs (their IR and image addresses are stale). */ +#define HK_M5_PLAN_STATE 0u +#define HK_M5_PLAN_ENVELOPE 32u +#define HK_M5_PLAN_PARENTS 80u +#define HK_M5_PLAN_JOBS(node_bound) \ + ((HK_M5_PLAN_PARENTS + 4u * (node_bound) + 7u) & ~7u) +#define HK_M5_PLAN_BYTES(node_bound) \ + (HK_M5_PLAN_JOBS(node_bound) + 64u * (node_bound)) + struct hk_m5_refit_args { + /* SAVE_IR and PREPARE: the retained IR header and internal nodes. */ VOID_REF retained; VOID_REF metadata; VOID_REF intermediate_bvh; REF(vk_ir_header) header; + /* PREPARE and REFIT: an arrival counter per IR node, 16 bytes apart. */ VOID_REF parents; uint32_t root_offset; uint32_t leaf_bound; uint32_t node_bound; uint32_t phase; + /* SAVE_PLAN: the plan nodes. */ VOID_REF plan_nodes; + /* SAVE_PLAN: the plan to save; REFIT: where to restore it. */ VOID_REF plan_jobs; VOID_REF plan_state; + VOID_REF plan_envelope; + /* The retained plan: SAVE_PLAN's destination, REFIT's and COPY_PLAN's + * source. */ + VOID_REF plan; + /* COPY_PLAN: the destination structure's retained plan. */ + VOID_REF plan_copy; + /* REFIT: the native image and its structure's ID. */ + VOID_REF output_bvh; + uint32_t resource_id; + uint32_t padding; }; /* Push constants of refit encoding. */ diff --git a/src/asahi/vulkan/hk_m5_acceleration_structure.c b/src/asahi/vulkan/hk_m5_acceleration_structure.c index 5e3973178d79..850e92a428bc 100644 --- a/src/asahi/vulkan/hk_m5_acceleration_structure.c +++ b/src/asahi/vulkan/hk_m5_acceleration_structure.c @@ -81,8 +81,11 @@ hk_m5_agx3_refit_spirv(size_t *size_B) } static void hk_flush_buffer_write_cp(VkCommandBuffer); -static void hk_agx3_refit_phase(VkCommandBuffer, +static void hk_m5_refit(VkCommandBuffer, const struct vk_acceleration_structure_build_state *, unsigned); +static VkResult hk_build_leaves_batched(VkCommandBuffer, struct vk_device *, + struct vk_meta_device *, const struct vk_acceleration_structure_build_args *, + struct vk_acceleration_structure_build_state *, uint32_t, uint32_t); /* Native tables have 16-byte entries and reserve ID zero. Keep the same @@ -419,12 +422,15 @@ get_pipeline_spv(struct hk_device *dev, const char *name, const uint32_t *spv, name, key_size, pipeline); } +/* Plans and encodes a structure. With a build state that allows updates, + * also saves the plan into the structure (HK_M5_REFIT_SAVE_PLAN). */ static VkResult hk_cmd_build_agx3_from_ir_mode(VkCommandBuffer command_buffer, const struct hk_agx3_plan_args *args, VkDeviceAddress node_status, VkDeviceAddress envelope_status, - bool single_leaf) + bool single_leaf, + const struct vk_acceleration_structure_build_state *save) { VK_FROM_HANDLE(hk_cmd_buffer, cmd, command_buffer); struct hk_device *dev = hk_cmd_buffer_device(cmd); @@ -472,6 +478,10 @@ hk_cmd_build_agx3_from_ir_mode(VkCommandBuffer command_buffer, 0, 1, &barrier, 0, NULL, 0, NULL); } + /* The saved plan is read-only to the node and envelope jobs below. */ + if (save) + hk_m5_refit(command_buffer, save, HK_M5_REFIT_SAVE_PLAN); + const struct hk_agx3_leaf_args encode = { .jobs = args->jobs, .status = node_status, .job_count = args->node_bound, }; @@ -509,7 +519,7 @@ hk_m5_backend_cmd_build_agx3_from_ir(VkCommandBuffer command_buffer, VkDeviceAddress envelope_status) { return hk_cmd_build_agx3_from_ir_mode(command_buffer, args, node_status, - envelope_status, false); + envelope_status, false, NULL); } /* ---------------------------------------------------------------- */ @@ -580,6 +590,16 @@ hk_agx3_retained_offset(const struct vk_acceleration_structure_build_state *stat ? (uint64_t)state->leaf_node_count * 80 : 0), 8); } +/* Where an updatable structure keeps its build's plan: after its IR + * topology (hk_m5_refit_args). */ +static VkDeviceSize +hk_m5_plan_offset(const struct vk_acceleration_structure_build_state *state) +{ + return ALIGN_POT(hk_agx3_retained_offset(state) + sizeof(struct vk_ir_header) + + (uint64_t)state->internal_node_count * + sizeof(struct vk_ir_box_node), 8); +} + static VkDeviceSize hk_get_as_size(VkDevice _device, const struct vk_acceleration_structure_build_state *state) @@ -589,9 +609,10 @@ hk_get_as_size(VkDevice _device, struct hk_agx3_as_layout layout; if (!hk_agx3_as_layout_init(state->leaf_node_count, &layout)) return 0; + /* A valid layout bounds node_bound well below 2^26, so the plan's + * 32-bit size cannot wrap. */ if (state->build_info->flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR) - return hk_agx3_retained_offset(state) + sizeof(struct vk_ir_header) + - (uint64_t)state->internal_node_count * sizeof(struct vk_ir_box_node); + return hk_m5_plan_offset(state) + HK_M5_PLAN_BYTES(layout.node_bound); return layout.as_bytes + (vk_get_as_geometry_type(state->build_info) == VK_GEOMETRY_TYPE_INSTANCES_KHR ? (uint64_t)state->leaf_node_count * 80 : 0); @@ -666,12 +687,12 @@ hk_encode_as(VkCommandBuffer commandBuffer, struct hk_device *dev = hk_cmd_buffer_device(cmd); if (dev->m5_native_as) { - /* Keep only header/internal topology; updated vertices are read from - * input buffers, with no Morton sort or tree reconstruction. */ - if ((state->build_info->flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR) && - (state->build_info->mode == VK_BUILD_ACCELERATION_STRUCTURE_MODE_BUILD_KHR || - state->build_info->srcAccelerationStructure != state->build_info->dstAccelerationStructure)) { - hk_agx3_refit_phase(commandBuffer, state, 0); + /* A build that allows updates keeps its IR topology and its plan; + * updates (hk_update_batched) refit and re-encode from them. */ + const bool updatable = state->build_info->flags & + VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR; + if (updatable) { + hk_m5_refit(commandBuffer, state, HK_M5_REFIT_SAVE_IR); hk_flush_buffer_write_cp(commandBuffer); } struct hk_agx3_as_layout layout; @@ -701,7 +722,7 @@ hk_encode_as(VkCommandBuffer commandBuffer, VkResult result = hk_cmd_build_agx3_from_ir_mode( commandBuffer, &args, encode + layout.node_status, encode + layout.envelope_status, - false); + false, updatable ? state : NULL); if (result != VK_SUCCESS) vk_command_buffer_set_error(&cmd->vk, result); return; @@ -744,10 +765,13 @@ hk_encode_as(VkCommandBuffer commandBuffer, internal_bound + state->leaf_node_count, 1, 1); } +/* One refit phase of one structure (hk_m5_refit_args). The save phases + * write the destination; the others read the source, which an update may + * share with its destination. */ static void -hk_agx3_refit_phase(VkCommandBuffer commandBuffer, - const struct vk_acceleration_structure_build_state *state, - unsigned phase) +hk_m5_refit(VkCommandBuffer commandBuffer, + const struct vk_acceleration_structure_build_state *state, + unsigned phase) { VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); struct hk_device *dev = hk_cmd_buffer_device(cmd); @@ -764,23 +788,49 @@ hk_agx3_refit_phase(VkCommandBuffer commandBuffer, vk_command_buffer_set_error(&cmd->vk, result); return; } - VK_FROM_HANDLE(vk_acceleration_structure, retained_as, - phase == 1 ? state->build_info->srcAccelerationStructure : state->build_info->dstAccelerationStructure); - uint64_t scratch = state->build_info->scratchData.deviceAddress; + const VkAccelerationStructureBuildGeometryInfoKHR *info = state->build_info; + VK_FROM_HANDLE(vk_acceleration_structure, dst, info->dstAccelerationStructure); + VK_FROM_HANDLE(vk_acceleration_structure, src, info->srcAccelerationStructure); + const bool save = phase == HK_M5_REFIT_SAVE_IR || + phase == HK_M5_REFIT_SAVE_PLAN; + const uint64_t base = vk_acceleration_structure_get_va(save ? dst : src); + const uint64_t scratch = info->scratchData.deviceAddress; + const uint64_t encode = scratch + state->scratch.header_offset + + sizeof(struct vk_ir_header); struct hk_m5_refit_args args = { - .retained = vk_acceleration_structure_get_va(retained_as) + hk_agx3_retained_offset(state), + .retained = base + hk_agx3_retained_offset(state), .intermediate_bvh = scratch + state->scratch.ir_offset, .header = scratch + state->scratch.header_offset, .parents = scratch + state->scratch.size, .root_offset = state->leaf_node_count * - hk_agx3_ir_leaf_size(vk_get_as_geometry_type(state->build_info)), + hk_agx3_ir_leaf_size(vk_get_as_geometry_type(info)), .leaf_bound = state->leaf_node_count, .node_bound = layout.node_bound, .phase = phase, + .plan_nodes = encode + layout.nodes, + .plan_jobs = encode + layout.jobs, + .plan_state = encode + layout.state, + .plan_envelope = encode + layout.envelope, + .plan = base + hk_m5_plan_offset(state), + .plan_copy = vk_acceleration_structure_get_va(dst) + hk_m5_plan_offset(state), + .output_bvh = hk_as_native_va(dst), + .resource_id = phase == HK_M5_REFIT_REFIT ? hk_m5_as_id(dev, dst) : 0, }; - unsigned count = phase <= 1 - ? MAX2(layout.node_bound, (sizeof(struct vk_ir_header) + - state->internal_node_count * sizeof(struct vk_ir_box_node)) / 4) - : phase == 2 ? state->internal_node_count : state->leaf_node_count; + unsigned count; + switch (phase) { + case HK_M5_REFIT_SAVE_IR: + case HK_M5_REFIT_PREPARE: + count = MAX2(layout.node_bound, (sizeof(struct vk_ir_header) + + state->internal_node_count * sizeof(struct vk_ir_box_node)) / 4); + break; + case HK_M5_REFIT_COPY_PLAN: + count = HK_M5_PLAN_BYTES(layout.node_bound) / 4; + break; + default: + /* Saving and refitting: a thread per IR node, which covers every + * leaf and every job. */ + count = layout.node_bound; + break; + } vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); vk_common_CmdPushConstants(commandBuffer, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(args), &args); @@ -828,40 +878,156 @@ hk_init_update_scratch(VkCommandBuffer commandBuffer, { for (unsigned i = 0; i < count; ++i) if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE) - hk_agx3_refit_phase(commandBuffer, &states[i], 1); + hk_m5_refit(commandBuffer, &states[i], HK_M5_REFIT_PREPARE); } +/* Encodes an update's restored node jobs, or its envelope. */ static void -hk_update_prepare(VkCommandBuffer commandBuffer, - const struct vk_acceleration_structure_build_state *state, - bool flushed_cp, bool flushed_compute) +hk_m5_update_encode(VkCommandBuffer commandBuffer, + const struct vk_acceleration_structure_build_state *state, + bool envelope) { - hk_flush_buffer_write_cp(commandBuffer); + VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); + struct hk_device *dev = hk_cmd_buffer_device(cmd); + struct hk_agx3_as_layout layout; + if (!hk_agx3_as_layout_init(state->leaf_node_count, &layout)) { + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_DEVICE_MEMORY); + return; + } + const uint64_t encode = state->build_info->scratchData.deviceAddress + + state->scratch.header_offset + + sizeof(struct vk_ir_header); + const struct hk_agx3_leaf_args nodes = { + .jobs = encode + layout.jobs, .status = encode + layout.node_status, + .job_count = layout.node_bound, + }; + const struct hk_agx3_envelope_args finish = { + .jobs = encode + layout.envelope, + .status = encode + layout.envelope_status, .job_count = 1, + }; + VkPipeline pipeline; + VkPipelineLayout pipeline_layout; + VkResult result = envelope + ? get_pipeline_spv(dev, "hk-agx3-as-envelope", agx3_envelope_spv, + sizeof(agx3_envelope_spv), sizeof(finish), &pipeline, + &pipeline_layout) + : get_pipeline_spv(dev, "hk-agx3-node-encode", agx3_node_spv, + sizeof(agx3_node_spv), sizeof(nodes), &pipeline, + &pipeline_layout); + if (result != VK_SUCCESS) { + vk_command_buffer_set_error(&cmd->vk, result); + return; + } + vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, + pipeline); + vk_common_CmdPushConstants(commandBuffer, pipeline_layout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, + envelope ? sizeof(finish) : sizeof(nodes), + envelope ? (const void *)&finish + : (const void *)&nodes); + if (envelope) + hk_cmd_dispatch_unaligned(commandBuffer, 1, 1, 1); + else + hk_cmd_dispatch_indirect_addr(commandBuffer, encode + layout.state); } +/* The updates of one build call. An update keeps its build's IR topology + * and plan: it regenerates the IR leaves, refits the IR internal nodes and + * re-encodes the build's node jobs into the same slots, without planning. + * Each step runs for every update before the next, so a call waits at a + * few barriers rather than at several per structure. */ static void -hk_update_as(VkCommandBuffer commandBuffer, - const struct vk_acceleration_structure_build_state *state) +hk_update_batched(VkCommandBuffer commandBuffer, struct vk_device *device, + struct vk_meta_device *meta, + const struct vk_acceleration_structure_build_args *build_args, + const struct vk_acceleration_structure_build_state *states, + uint32_t build_count) { VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); - struct hk_device *dev = hk_cmd_buffer_device(cmd); - hk_agx3_refit_phase(commandBuffer, state, 2); - VkResult result = vk_cmd_build_as_leaves(commandBuffer, &dev->vk, &dev->meta, - &dev->accel_struct_args, state); - if (result != VK_SUCCESS) { - vk_command_buffer_set_error(&cmd->vk, result); + uint32_t count = 0; + for (uint32_t i = 0; i < build_count; ++i) + count += states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE; + if (!count) + return; + + /* The leaves: the ordinary leaf pass, on copies not typed as updates, + * as vk_cmd_build_as_leaves() runs it for one. */ + struct vk_acceleration_structure_build_state *leaves = + malloc(count * sizeof(*leaves)); + if (!leaves) { + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_HOST_MEMORY); return; } + uint32_t n = 0; + for (uint32_t i = 0; i < build_count; ++i) { + if (states[i].config.internal_type != VK_INTERNAL_BUILD_TYPE_UPDATE) + continue; + leaves[n] = states[i]; + leaves[n].config.internal_type = VK_INTERNAL_BUILD_TYPE_LBVH; + leaves[n].config.build_flags |= VK_BUILD_FLAG_NO_HEADER_BOUNDS; + leaves[n].leaf_node_count = 0; + leaves[n].processed = false; + ++n; + } + for (uint32_t i = 0; i < count; ++i) { + const uint32_t flags = leaves[i].config.build_flags & VK_LEAF_BUILD_FLAGS; + bool done = false; + for (uint32_t j = 0; j < i; ++j) + done |= (leaves[j].config.build_flags & VK_LEAF_BUILD_FLAGS) == flags; + if (done) + continue; + VkResult result = hk_build_leaves_batched(commandBuffer, device, meta, + build_args, leaves, count, flags); + if (result != VK_SUCCESS) { + free(leaves); + vk_command_buffer_set_error(&cmd->vk, result); + return; + } + } + free(leaves); hk_flush_buffer_write_cp(commandBuffer); - hk_agx3_refit_phase(commandBuffer, state, 3); - hk_flush_buffer_write_cp(commandBuffer); - hk_encode_as(commandBuffer, state); + + for (uint32_t i = 0; i < build_count; ++i) + if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE) + hk_m5_refit(commandBuffer, &states[i], HK_M5_REFIT_REFIT); + /* The node jobs' indirect dispatch reads the restored plan state. */ + const VkMemoryBarrier restored = { + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | + VK_ACCESS_INDIRECT_COMMAND_READ_BIT, + }; + vk_common_CmdPipelineBarrier(commandBuffer, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, + 0, 1, &restored, 0, NULL, 0, NULL); + + /* As in a build: the nodes of a bottom-level structure before its + * envelope, and the envelope of a top-level structure, which places the + * tables its instance records name, before its nodes. An update into + * another structure also gives that one the topology and the plan. */ + for (unsigned step = 0; step < 2; ++step) { + for (uint32_t i = 0; i < build_count; ++i) { + const struct vk_acceleration_structure_build_state *state = &states[i]; + if (state->config.internal_type != VK_INTERNAL_BUILD_TYPE_UPDATE) + continue; + const bool instances = vk_get_as_geometry_type(state->build_info) == + VK_GEOMETRY_TYPE_INSTANCES_KHR; + hk_m5_update_encode(commandBuffer, state, instances == (step == 0)); + if (step == 0 && state->build_info->srcAccelerationStructure != + state->build_info->dstAccelerationStructure) { + hk_m5_refit(commandBuffer, state, HK_M5_REFIT_SAVE_IR); + hk_m5_refit(commandBuffer, state, HK_M5_REFIT_COPY_PLAN); + } + } + if (step == 0) + hk_flush_buffer_write_cp(commandBuffer); + } } -/* Same per-AS native records, planned and encoded concurrently. */ /* The upstream runtime hands encoding every state of a batch at once, after * the common builder finished the intermediate trees of the non-update - * states. Keep the M5 per-state prepare/encode/update sequence inside it. */ + * states. */ static void hk_encode_dispatch(VkCommandBuffer commandBuffer, struct vk_device *device, struct vk_meta_device *meta, @@ -874,13 +1040,11 @@ hk_encode_dispatch(VkCommandBuffer commandBuffer, struct vk_device *device, /* The common builder hands encoding the completed intermediate tree. */ vk_bvh_build_barrier_compute_to_compute(commandBuffer, false); + hk_update_batched(commandBuffer, device, meta, build_args, states, + build_count); for (uint32_t i = 0; i < build_count; i++) { - if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE) { - hk_update_prepare(commandBuffer, &states[i], true, - flushed_compute_after_init_update_scratch); - hk_update_as(commandBuffer, &states[i]); + if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE) continue; - } if (!prepared) { VkResult result = hk_encode_prepare(commandBuffer, &states[i]); if (result != VK_SUCCESS) { @@ -1101,9 +1265,9 @@ hk_m5_backend_device_init_accel_struct_state(struct hk_device *dev) .morton_sort_workgroup_size = 512, .morton_sort_kvs_per_thread = 2, .propagate_cull_flags = false, - /* The native builder refits updates in place (hk_update_as). Without + /* The native builder refits updates (hk_update_batched). Without * this, the common code reports the build scratch size for updates, - * and the refit's parent records land past the application's + * and the refit's arrival counters land past the application's * update scratch. */ .has_update = dev->m5_native_as, }; From 82c07f762bd4834a05b991049a696dbf3de83cf5 Mon Sep 17 00:00:00 2001 From: DjDeveloperr Date: Mon, 30 Nov 2026 10:02:07 -0500 Subject: [PATCH 2/2] borealis: run each M5 refit step once for all updates of a call The refit still dispatched its preparation, its refit and its node and envelope jobs once per structure, and every M5 internal dispatch waits for the one before it. With about 200 bottom-level updates a frame in GTA V that is about 800 dispatches. Run each step of all the updates of a build call in one dispatch: a workgroup finds its update by a binary search over per-update workgroup offsets. After the refit, a single-thread pass sums the restored jobs of every update into job offsets and the node encoding's indirect dispatch, and the envelope jobs land in one array, so a call dispatches seven times however many structures it updates. Signed-off-by: DjDeveloperr --- src/asahi/vulkan/bvh/agx3_m5_legacy_leaf.comp | 27 ++ .../vulkan/bvh/agx3_m5_legacy_refit.comp | 52 ++- src/asahi/vulkan/bvh/hk_build_interface.h | 40 ++ src/asahi/vulkan/bvh/meson.build | 2 + .../vulkan/hk_m5_acceleration_structure.c | 433 +++++++++++++----- 5 files changed, 426 insertions(+), 128 deletions(-) diff --git a/src/asahi/vulkan/bvh/agx3_m5_legacy_leaf.comp b/src/asahi/vulkan/bvh/agx3_m5_legacy_leaf.comp index 6525306367d9..7da399ec1d7f 100644 --- a/src/asahi/vulkan/bvh/agx3_m5_legacy_leaf.comp +++ b/src/asahi/vulkan/bvh/agx3_m5_legacy_leaf.comp @@ -23,10 +23,19 @@ #include "hk_build_interface.h" layout(local_size_x = 8) in; +#ifdef HK_M5_LEAF_BATCHED +/* The restored jobs of every update of a build call (hk_m5_leaf_batch_args). */ +layout(push_constant) uniform CONSTS +{ + hk_m5_leaf_batch_args batch; +}; +hk_agx3_leaf_args args; +#else layout(push_constant) uniform CONSTS { hk_agx3_leaf_args args; }; +#endif shared vec3 vertices[24]; shared vec3 lower[8], upper[8]; @@ -209,7 +218,25 @@ encode_instance(hk_agx3_leaf_job job, uint lane) void main() { +#ifdef HK_M5_LEAF_BATCHED + /* The last update whose first job is at or before this workgroup. */ + uint w = gl_WorkGroupID.x, lo = 0, hi = batch.count; + while (hi - lo > 1) { + uint mid = (lo + hi) / 2; + if (DEREF(INDEX(uint32_t, batch.bases, mid)) <= w) + lo = mid; + else + hi = mid; + } + uint first = DEREF(INDEX(uint32_t, batch.bases, lo)); + hk_m5_leaf_task task = DEREF(INDEX(hk_m5_leaf_task, batch.tasks, lo)); + args.jobs = REF(hk_agx3_leaf_job)(task.jobs); + args.status = task.status; + args.job_count = DEREF(INDEX(uint32_t, batch.bases, lo + 1)) - first; + uint id = w - first, lane = gl_LocalInvocationID.x; +#else uint id = gl_WorkGroupID.x, lane = gl_LocalInvocationID.x; +#endif if (id >= args.job_count) return; hk_agx3_leaf_job job = DEREF(INDEX(hk_agx3_leaf_job, args.jobs, id)); diff --git a/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp b/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp index 042e97c7286a..6c1b7de39299 100644 --- a/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp +++ b/src/asahi/vulkan/bvh/agx3_m5_legacy_refit.comp @@ -18,7 +18,12 @@ #include "hk_build_interface.h" layout(local_size_x = 64) in; +#ifdef HK_M5_REFIT_BATCHED +layout(push_constant) uniform CONSTS { hk_m5_refit_batch_args batch; }; +hk_m5_refit_args args; +#else layout(push_constant) uniform CONSTS { hk_m5_refit_args args; }; +#endif struct refit_node { uint parent; uint arrivals; uint reserved[2]; }; TYPE(refit_node, 4); @@ -32,9 +37,8 @@ REF(hk_agx3_leaf_job) retained_job(uint64_t plan, uint id) return INDEX(hk_agx3_leaf_job, plan + uint64_t(HK_M5_PLAN_JOBS(args.node_bound)), id); } -void main() +void refit(uint id) { - uint id = gl_GlobalInvocationID.x; uint header_words = SIZEOF(vk_ir_header) / 4; uint internal_bound = args.node_bound - args.leaf_bound; if (args.phase == HK_M5_REFIT_SAVE_IR || args.phase == HK_M5_REFIT_PREPARE) { @@ -129,3 +133,47 @@ void main() parent = DEREF(parent_of(args.plan, parent)); } } + +#ifdef HK_M5_REFIT_BATCHED +/* The node encoding of all updates: each update's restored jobs follow the + * jobs of the updates before it. */ +void prefix() +{ + uint sum = 0; + for (uint u = 0; u < batch.count; ++u) { + DEREF(INDEX(uint32_t, batch.bases, u)) = sum; + hk_m5_refit_args task = DEREF(INDEX(hk_m5_refit_args, batch.tasks, u)); + sum += DEREF(REF(hk_agx3_plan_state)(task.plan_state)).job_count; + } + DEREF(INDEX(uint32_t, batch.bases, batch.count)) = sum; + DEREF(INDEX(uint32_t, batch.dispatch, 0)) = sum; + DEREF(INDEX(uint32_t, batch.dispatch, 1)) = 1; + DEREF(INDEX(uint32_t, batch.dispatch, 2)) = 1; +} +#endif + +void main() +{ +#ifdef HK_M5_REFIT_BATCHED + if (batch.phase == HK_M5_REFIT_PREFIX) { + if (gl_GlobalInvocationID.x == 0) + prefix(); + return; + } + /* The last update whose first workgroup is at or before this one. */ + uint g = gl_WorkGroupID.x, lo = 0, hi = batch.count; + while (hi - lo > 1) { + uint mid = (lo + hi) / 2; + if (DEREF(INDEX(uint32_t, batch.groups, mid)) <= g) + lo = mid; + else + hi = mid; + } + args = DEREF(INDEX(hk_m5_refit_args, batch.tasks, lo)); + args.phase = batch.phase; + refit((g - DEREF(INDEX(uint32_t, batch.groups, lo))) * 64u + + gl_LocalInvocationID.x); +#else + refit(gl_GlobalInvocationID.x); +#endif +} diff --git a/src/asahi/vulkan/bvh/hk_build_interface.h b/src/asahi/vulkan/bvh/hk_build_interface.h index 2ef9af265290..0e1695430c02 100644 --- a/src/asahi/vulkan/bvh/hk_build_interface.h +++ b/src/asahi/vulkan/bvh/hk_build_interface.h @@ -318,6 +318,46 @@ struct hk_m5_refit_args { uint32_t padding; }; +#ifdef VULKAN +TYPE(hk_m5_refit_args, 8); +#endif + +/* The updates of one build call run each refit phase in one dispatch + * (agx3_m5_legacy_refit.comp built with HK_M5_REFIT_BATCHED): workgroup g + * of the dispatch belongs to update u, groups[u] <= g < groups[u + 1], and + * runs that update's phase as workgroup g - groups[u] of its own dispatch. + * PREFIX, after REFIT, sums the restored jobs of all updates into bases[] + * (count + 1 entries) and the node encoding dispatch. */ +#define HK_M5_REFIT_PREFIX 5u + +struct hk_m5_refit_batch_args { + REF(hk_m5_refit_args) tasks; + REF(uint32_t) groups; + REF(uint32_t) bases; + REF(uint32_t) dispatch; + uint32_t count; + uint32_t phase; +}; + +/* One node encoding dispatch for the updates of a build call + * (agx3_m5_legacy_leaf.comp built with HK_M5_LEAF_BATCHED): workgroup w + * encodes job w - bases[u] of update u, bases[u] <= w < bases[u + 1]. */ +struct hk_m5_leaf_task { + VOID_REF jobs; + REF(uint32_t) status; +}; + +#ifdef VULKAN +TYPE(hk_m5_leaf_task, 8); +#endif + +struct hk_m5_leaf_batch_args { + REF(hk_m5_leaf_task) tasks; + REF(uint32_t) bases; + uint32_t count; + uint32_t padding; +}; + /* Push constants of refit encoding. */ struct hk_agx3_refit_encode_args { VOID_REF refit; diff --git a/src/asahi/vulkan/bvh/meson.build b/src/asahi/vulkan/bvh/meson.build index 65de04dbd10f..1039463b612b 100644 --- a/src/asahi/vulkan/bvh/meson.build +++ b/src/asahi/vulkan/bvh/meson.build @@ -36,6 +36,8 @@ foreach s : [['encode.comp', 'hk_encode'], ['write.comp', 'hk_bvh_write'], ['agx3_m5_legacy_envelope.comp', 'hk_agx3_m5_legacy_envelope'], ['agx3_m5_legacy_plan.comp', 'hk_agx3_m5_legacy_plan'], ['agx3_m5_legacy_refit.comp', 'hk_agx3_m5_legacy_refit'], + ['agx3_m5_legacy_refit.comp', 'hk_agx3_m5_legacy_refit_batched', '-DHK_M5_REFIT_BATCHED=1'], + ['agx3_m5_legacy_leaf.comp', 'hk_agx3_m5_legacy_leaf_batched', '-DHK_M5_LEAF_BATCHED=1'], ['agx3_leaf.comp', 'hk_agx3_gen1_leaf'], ['agx3_leaf.comp', 'hk_agx3_gen1_leaf_pairs', '-DHK_AGX3_LEAF_PAIRS=1'], ['agx3_leaf.comp', 'hk_agx3_gen1_leaf_instances', '-DHK_AGX3_LEAF_ONLY=2'], diff --git a/src/asahi/vulkan/hk_m5_acceleration_structure.c b/src/asahi/vulkan/hk_m5_acceleration_structure.c index 850e92a428bc..df56304ea661 100644 --- a/src/asahi/vulkan/hk_m5_acceleration_structure.c +++ b/src/asahi/vulkan/hk_m5_acceleration_structure.c @@ -66,6 +66,14 @@ static const uint32_t agx3_refit_spv[] = { #include "bvh/hk_agx3_m5_legacy_refit.spv.h" }; +static const uint32_t agx3_refit_batched_spv[] = { +#include "bvh/hk_agx3_m5_legacy_refit_batched.spv.h" +}; + +static const uint32_t agx3_node_batched_spv[] = { +#include "bvh/hk_agx3_m5_legacy_leaf_batched.spv.h" +}; + const uint32_t * hk_m5_agx3_node_encoder_spirv(size_t *size_B) { @@ -765,28 +773,20 @@ hk_encode_as(VkCommandBuffer commandBuffer, internal_bound + state->leaf_node_count, 1, 1); } -/* One refit phase of one structure (hk_m5_refit_args). The save phases - * write the destination; the others read the source, which an update may - * share with its destination. */ -static void -hk_m5_refit(VkCommandBuffer commandBuffer, - const struct vk_acceleration_structure_build_state *state, - unsigned phase) +/* The arguments of one refit phase of one structure (hk_m5_refit_args) and + * its thread count. The save phases write the destination; the others read + * the source, which an update may share with its destination. */ +static bool +hk_m5_refit_args_init(struct hk_cmd_buffer *cmd, + const struct vk_acceleration_structure_build_state *state, + unsigned phase, struct hk_m5_refit_args *out, + uint32_t *threads) { - VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); struct hk_device *dev = hk_cmd_buffer_device(cmd); struct hk_agx3_as_layout layout; if (!hk_agx3_as_layout_init(state->leaf_node_count, &layout)) { vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_DEVICE_MEMORY); - return; - } - VkPipeline pipeline; - VkPipelineLayout pipeline_layout; - VkResult result = get_pipeline_spv(dev, "hk-agx3-refit", agx3_refit_spv, - sizeof(agx3_refit_spv), sizeof(struct hk_m5_refit_args), &pipeline, &pipeline_layout); - if (result != VK_SUCCESS) { - vk_command_buffer_set_error(&cmd->vk, result); - return; + return false; } const VkAccelerationStructureBuildGeometryInfoKHR *info = state->build_info; VK_FROM_HANDLE(vk_acceleration_structure, dst, info->dstAccelerationStructure); @@ -797,7 +797,7 @@ hk_m5_refit(VkCommandBuffer commandBuffer, const uint64_t scratch = info->scratchData.deviceAddress; const uint64_t encode = scratch + state->scratch.header_offset + sizeof(struct vk_ir_header); - struct hk_m5_refit_args args = { + *out = (struct hk_m5_refit_args){ .retained = base + hk_agx3_retained_offset(state), .intermediate_bvh = scratch + state->scratch.ir_offset, .header = scratch + state->scratch.header_offset, @@ -815,22 +815,44 @@ hk_m5_refit(VkCommandBuffer commandBuffer, .output_bvh = hk_as_native_va(dst), .resource_id = phase == HK_M5_REFIT_REFIT ? hk_m5_as_id(dev, dst) : 0, }; - unsigned count; switch (phase) { case HK_M5_REFIT_SAVE_IR: case HK_M5_REFIT_PREPARE: - count = MAX2(layout.node_bound, (sizeof(struct vk_ir_header) + + *threads = MAX2(layout.node_bound, (sizeof(struct vk_ir_header) + state->internal_node_count * sizeof(struct vk_ir_box_node)) / 4); break; case HK_M5_REFIT_COPY_PLAN: - count = HK_M5_PLAN_BYTES(layout.node_bound) / 4; + *threads = HK_M5_PLAN_BYTES(layout.node_bound) / 4; break; default: /* Saving and refitting: a thread per IR node, which covers every * leaf and every job. */ - count = layout.node_bound; + *threads = layout.node_bound; break; } + return true; +} + +/* One refit phase of one structure. */ +static void +hk_m5_refit(VkCommandBuffer commandBuffer, + const struct vk_acceleration_structure_build_state *state, + unsigned phase) +{ + VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); + struct hk_device *dev = hk_cmd_buffer_device(cmd); + struct hk_m5_refit_args args; + uint32_t count; + if (!hk_m5_refit_args_init(cmd, state, phase, &args, &count)) + return; + VkPipeline pipeline; + VkPipelineLayout pipeline_layout; + VkResult result = get_pipeline_spv(dev, "hk-agx3-refit", agx3_refit_spv, + sizeof(agx3_refit_spv), sizeof(struct hk_m5_refit_args), &pipeline, &pipeline_layout); + if (result != VK_SUCCESS) { + vk_command_buffer_set_error(&cmd->vk, result); + return; + } vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); vk_common_CmdPushConstants(commandBuffer, pipeline_layout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(args), &args); @@ -871,71 +893,172 @@ hk_update_scratch_size(VkDevice device, (uint64_t)layout.node_bound * 16; } +static_assert(sizeof(struct hk_m5_refit_args) == 120, "M5 refit task ABI"); +static_assert(sizeof(struct hk_m5_leaf_task) == 16, "M5 node task ABI"); +static_assert(sizeof(struct hk_agx3_envelope_job) == 48, "M5 envelope job ABI"); + +/* The updates of a build call, bottom-level structures first. Returns + * their number and, in *bottom, how many are bottom-level. */ +static uint32_t +hk_m5_updates(const struct vk_acceleration_structure_build_state *states, + uint32_t build_count, uint32_t *order, uint32_t *bottom) +{ + uint32_t n = 0; + for (unsigned top = 0; top < 2; ++top) { + for (uint32_t i = 0; i < build_count; ++i) + if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE && + (vk_get_as_geometry_type(states[i].build_info) == + VK_GEOMETRY_TYPE_INSTANCES_KHR) == top) + order[n++] = i; + if (!top) + *bottom = n; + } + return n; +} + +static VkResult +hk_m5_refit_batched_pipeline(struct hk_device *dev, VkPipeline *pipeline, + VkPipelineLayout *layout) +{ + return get_pipeline_spv(dev, "hk-agx3-refit-batched", agx3_refit_batched_spv, + sizeof(agx3_refit_batched_spv), + sizeof(struct hk_m5_refit_batch_args), pipeline, + layout); +} + +/* Runs one refit phase of several updates in one dispatch + * (hk_m5_refit_batch_args). With envelopes, REFIT restores the envelope job + * of the u-th update at envelopes[u]. Returns the uploaded arguments. */ +static uint64_t +hk_m5_refit_batched(VkCommandBuffer commandBuffer, + const struct vk_acceleration_structure_build_state *states, + const uint32_t *order, uint32_t count, unsigned phase, + uint64_t envelopes) +{ + VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); + struct hk_device *dev = hk_cmd_buffer_device(cmd); + struct hk_m5_refit_args *tasks = malloc(count * sizeof(*tasks)); + uint32_t *groups = malloc((count + 1) * sizeof(*groups)); + if (!tasks || !groups) { + free(tasks); + free(groups); + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_HOST_MEMORY); + return 0; + } + uint64_t total = 0; + groups[0] = 0; + for (uint32_t u = 0; u < count; ++u) { + uint32_t threads; + if (!hk_m5_refit_args_init(cmd, &states[order[u]], phase, &tasks[u], + &threads)) { + free(tasks); + free(groups); + return 0; + } + if (envelopes) + tasks[u].plan_envelope = + envelopes + (uint64_t)u * sizeof(struct hk_agx3_envelope_job); + total += DIV_ROUND_UP(threads, 64); + groups[u + 1] = MIN2(total, UINT32_MAX); + } + uint64_t task_addr = 0, group_addr = 0; + if (total <= UINT32_MAX / 64) { + task_addr = hk_pool_upload(cmd, tasks, count * sizeof(*tasks), 8); + group_addr = hk_pool_upload(cmd, groups, (count + 1) * sizeof(*groups), 4); + } + free(tasks); + free(groups); + if (!task_addr || !group_addr) { + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_DEVICE_MEMORY); + return 0; + } + const struct hk_m5_refit_batch_args args = { + .tasks = task_addr, .groups = group_addr, .count = count, .phase = phase, + }; + VkPipeline pipeline; + VkPipelineLayout layout; + VkResult result = hk_m5_refit_batched_pipeline(dev, &pipeline, &layout); + if (result != VK_SUCCESS) { + vk_command_buffer_set_error(&cmd->vk, result); + return 0; + } + vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, + pipeline); + vk_common_CmdPushConstants(commandBuffer, layout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(args), + &args); + hk_cmd_dispatch_unaligned(commandBuffer, total * 64, 1, 1); + return task_addr; +} + static void hk_init_update_scratch(VkCommandBuffer commandBuffer, const struct vk_acceleration_structure_build_state *states, - uint32_t count) + uint32_t build_count) { - for (unsigned i = 0; i < count; ++i) - if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE) - hk_m5_refit(commandBuffer, &states[i], HK_M5_REFIT_PREPARE); + VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); + uint32_t *order = malloc(build_count * sizeof(*order)), bottom; + if (!order) { + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_HOST_MEMORY); + return; + } + uint32_t count = hk_m5_updates(states, build_count, order, &bottom); + if (count) + hk_m5_refit_batched(commandBuffer, states, order, count, + HK_M5_REFIT_PREPARE, 0); + free(order); } -/* Encodes an update's restored node jobs, or its envelope. */ static void -hk_m5_update_encode(VkCommandBuffer commandBuffer, - const struct vk_acceleration_structure_build_state *state, - bool envelope) +hk_m5_envelopes(VkCommandBuffer commandBuffer, uint64_t jobs, uint64_t status, + uint32_t count) { VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); struct hk_device *dev = hk_cmd_buffer_device(cmd); - struct hk_agx3_as_layout layout; - if (!hk_agx3_as_layout_init(state->leaf_node_count, &layout)) { - vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_DEVICE_MEMORY); + if (!count) return; - } - const uint64_t encode = state->build_info->scratchData.deviceAddress + - state->scratch.header_offset + - sizeof(struct vk_ir_header); - const struct hk_agx3_leaf_args nodes = { - .jobs = encode + layout.jobs, .status = encode + layout.node_status, - .job_count = layout.node_bound, - }; - const struct hk_agx3_envelope_args finish = { - .jobs = encode + layout.envelope, - .status = encode + layout.envelope_status, .job_count = 1, + const struct hk_agx3_envelope_args args = { + .jobs = jobs, .status = status, .job_count = count, }; VkPipeline pipeline; - VkPipelineLayout pipeline_layout; - VkResult result = envelope - ? get_pipeline_spv(dev, "hk-agx3-as-envelope", agx3_envelope_spv, - sizeof(agx3_envelope_spv), sizeof(finish), &pipeline, - &pipeline_layout) - : get_pipeline_spv(dev, "hk-agx3-node-encode", agx3_node_spv, - sizeof(agx3_node_spv), sizeof(nodes), &pipeline, - &pipeline_layout); + VkPipelineLayout layout; + VkResult result = get_pipeline_spv(dev, "hk-agx3-as-envelope", + agx3_envelope_spv, sizeof(agx3_envelope_spv), sizeof(args), &pipeline, + &layout); if (result != VK_SUCCESS) { vk_command_buffer_set_error(&cmd->vk, result); return; } vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline); - vk_common_CmdPushConstants(commandBuffer, pipeline_layout, - VK_SHADER_STAGE_COMPUTE_BIT, 0, - envelope ? sizeof(finish) : sizeof(nodes), - envelope ? (const void *)&finish - : (const void *)&nodes); - if (envelope) - hk_cmd_dispatch_unaligned(commandBuffer, 1, 1, 1); - else - hk_cmd_dispatch_indirect_addr(commandBuffer, encode + layout.state); + vk_common_CmdPushConstants(commandBuffer, layout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(args), + &args); + hk_cmd_dispatch_unaligned(commandBuffer, count, 1, 1); +} + +static void +hk_m5_barrier(VkCommandBuffer commandBuffer, bool indirect) +{ + const VkMemoryBarrier barrier = { + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | + (indirect ? VK_ACCESS_INDIRECT_COMMAND_READ_BIT : 0), + }; + vk_common_CmdPipelineBarrier(commandBuffer, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | + (indirect ? VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT : 0), + 0, 1, &barrier, 0, NULL, 0, NULL); } /* The updates of one build call. An update keeps its build's IR topology * and plan: it regenerates the IR leaves, refits the IR internal nodes and * re-encodes the build's node jobs into the same slots, without planning. - * Each step runs for every update before the next, so a call waits at a - * few barriers rather than at several per structure. */ + * Each step is one dispatch for all updates (PREPARE ran in + * hk_init_update_scratch), so a call waits at a few barriers however many + * structures it updates. */ static void hk_update_batched(VkCommandBuffer commandBuffer, struct vk_device *device, struct vk_meta_device *meta, @@ -944,85 +1067,143 @@ hk_update_batched(VkCommandBuffer commandBuffer, struct vk_device *device, uint32_t build_count) { VK_FROM_HANDLE(hk_cmd_buffer, cmd, commandBuffer); - uint32_t count = 0; - for (uint32_t i = 0; i < build_count; ++i) - count += states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE; - if (!count) + struct hk_device *dev = hk_cmd_buffer_device(cmd); + uint32_t *order = malloc(build_count * sizeof(*order)), bottom; + if (!order) { + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_HOST_MEMORY); + return; + } + const uint32_t count = hk_m5_updates(states, build_count, order, &bottom); + if (!count) { + free(order); return; + } /* The leaves: the ordinary leaf pass, on copies not typed as updates, * as vk_cmd_build_as_leaves() runs it for one. */ struct vk_acceleration_structure_build_state *leaves = malloc(count * sizeof(*leaves)); - if (!leaves) { + struct hk_m5_leaf_task *tasks = malloc(count * sizeof(*tasks)); + if (!leaves || !tasks) { + free(order); + free(leaves); + free(tasks); vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_HOST_MEMORY); return; } - uint32_t n = 0; - for (uint32_t i = 0; i < build_count; ++i) { - if (states[i].config.internal_type != VK_INTERNAL_BUILD_TYPE_UPDATE) - continue; - leaves[n] = states[i]; - leaves[n].config.internal_type = VK_INTERNAL_BUILD_TYPE_LBVH; - leaves[n].config.build_flags |= VK_BUILD_FLAG_NO_HEADER_BOUNDS; - leaves[n].leaf_node_count = 0; - leaves[n].processed = false; - ++n; + for (uint32_t u = 0; u < count; ++u) { + leaves[u] = states[order[u]]; + leaves[u].config.internal_type = VK_INTERNAL_BUILD_TYPE_LBVH; + leaves[u].config.build_flags |= VK_BUILD_FLAG_NO_HEADER_BOUNDS; + leaves[u].leaf_node_count = 0; + leaves[u].processed = false; } - for (uint32_t i = 0; i < count; ++i) { - const uint32_t flags = leaves[i].config.build_flags & VK_LEAF_BUILD_FLAGS; + VkResult result = VK_SUCCESS; + for (uint32_t u = 0; u < count && result == VK_SUCCESS; ++u) { + const uint32_t flags = leaves[u].config.build_flags & VK_LEAF_BUILD_FLAGS; bool done = false; - for (uint32_t j = 0; j < i; ++j) - done |= (leaves[j].config.build_flags & VK_LEAF_BUILD_FLAGS) == flags; - if (done) - continue; - VkResult result = hk_build_leaves_batched(commandBuffer, device, meta, - build_args, leaves, count, flags); - if (result != VK_SUCCESS) { - free(leaves); - vk_command_buffer_set_error(&cmd->vk, result); - return; - } + for (uint32_t v = 0; v < u; ++v) + done |= (leaves[v].config.build_flags & VK_LEAF_BUILD_FLAGS) == flags; + if (!done) + result = hk_build_leaves_batched(commandBuffer, device, meta, + build_args, leaves, count, flags); } free(leaves); - hk_flush_buffer_write_cp(commandBuffer); - - for (uint32_t i = 0; i < build_count; ++i) - if (states[i].config.internal_type == VK_INTERNAL_BUILD_TYPE_UPDATE) - hk_m5_refit(commandBuffer, &states[i], HK_M5_REFIT_REFIT); - /* The node jobs' indirect dispatch reads the restored plan state. */ - const VkMemoryBarrier restored = { - .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, - .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, - .dstAccessMask = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | - VK_ACCESS_INDIRECT_COMMAND_READ_BIT, + if (result != VK_SUCCESS) { + free(order); + free(tasks); + vk_command_buffer_set_error(&cmd->vk, result); + return; + } + hk_m5_barrier(commandBuffer, false); + + /* Refit the IR and restore each plan; the envelope jobs go to one array, + * bottom-level structures first, so one dispatch finishes each kind. */ + struct agx_ptr envelopes = hk_pool_alloc(cmd, + count * (sizeof(struct hk_agx3_envelope_job) + 4), 8); + struct agx_ptr bases = hk_pool_alloc(cmd, (count + 1) * 4, 4); + struct agx_ptr dispatch = hk_pool_alloc(cmd, 3 * 4, 16); + uint64_t refit = envelopes.gpu && bases.gpu && dispatch.gpu + ? hk_m5_refit_batched(commandBuffer, states, order, count, + HK_M5_REFIT_REFIT, envelopes.gpu) + : 0; + if (!refit) { + free(order); + free(tasks); + vk_command_buffer_set_error(&cmd->vk, VK_ERROR_OUT_OF_DEVICE_MEMORY); + return; + } + const uint64_t envelope_status = + envelopes.gpu + count * sizeof(struct hk_agx3_envelope_job); + hk_m5_barrier(commandBuffer, false); + + /* Place every update's jobs, and finish the top-level structures, whose + * envelopes place the tables their instance records name. */ + const struct hk_m5_refit_batch_args prefix = { + .tasks = refit, .bases = bases.gpu, .dispatch = dispatch.gpu, + .count = count, .phase = HK_M5_REFIT_PREFIX, }; - vk_common_CmdPipelineBarrier(commandBuffer, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, - VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, - 0, 1, &restored, 0, NULL, 0, NULL); - - /* As in a build: the nodes of a bottom-level structure before its - * envelope, and the envelope of a top-level structure, which places the - * tables its instance records name, before its nodes. An update into - * another structure also gives that one the topology and the plan. */ - for (unsigned step = 0; step < 2; ++step) { - for (uint32_t i = 0; i < build_count; ++i) { - const struct vk_acceleration_structure_build_state *state = &states[i]; - if (state->config.internal_type != VK_INTERNAL_BUILD_TYPE_UPDATE) - continue; - const bool instances = vk_get_as_geometry_type(state->build_info) == - VK_GEOMETRY_TYPE_INSTANCES_KHR; - hk_m5_update_encode(commandBuffer, state, instances == (step == 0)); - if (step == 0 && state->build_info->srcAccelerationStructure != - state->build_info->dstAccelerationStructure) { - hk_m5_refit(commandBuffer, state, HK_M5_REFIT_SAVE_IR); - hk_m5_refit(commandBuffer, state, HK_M5_REFIT_COPY_PLAN); - } + VkPipeline pipeline; + VkPipelineLayout layout; + result = hk_m5_refit_batched_pipeline(dev, &pipeline, &layout); + if (result != VK_SUCCESS) { + free(order); + free(tasks); + vk_command_buffer_set_error(&cmd->vk, result); + return; + } + vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, + pipeline); + vk_common_CmdPushConstants(commandBuffer, layout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(prefix), + &prefix); + hk_cmd_dispatch_unaligned(commandBuffer, 1, 1, 1); + hk_m5_envelopes(commandBuffer, + envelopes.gpu + bottom * sizeof(struct hk_agx3_envelope_job), + envelope_status + bottom * 4, count - bottom); + hk_m5_barrier(commandBuffer, true); + + /* Every update's node jobs, in one dispatch. An update into another + * structure also gives that one the topology and the plan. */ + for (uint32_t u = 0; u < count; ++u) { + const struct vk_acceleration_structure_build_state *state = &states[order[u]]; + struct hk_agx3_as_layout as_layout; + hk_agx3_as_layout_init(state->leaf_node_count, &as_layout); + const uint64_t encode = state->build_info->scratchData.deviceAddress + + state->scratch.header_offset + + sizeof(struct vk_ir_header); + tasks[u] = (struct hk_m5_leaf_task){ + .jobs = encode + as_layout.jobs, .status = encode + as_layout.node_status, + }; + if (state->build_info->srcAccelerationStructure != + state->build_info->dstAccelerationStructure) { + hk_m5_refit(commandBuffer, state, HK_M5_REFIT_SAVE_IR); + hk_m5_refit(commandBuffer, state, HK_M5_REFIT_COPY_PLAN); } - if (step == 0) - hk_flush_buffer_write_cp(commandBuffer); } + free(order); + const struct hk_m5_leaf_batch_args nodes = { + .tasks = hk_pool_upload(cmd, tasks, count * sizeof(*tasks), 8), + .bases = bases.gpu, .count = count, + }; + free(tasks); + result = nodes.tasks ? get_pipeline_spv(dev, "hk-agx3-node-encode-batched", + agx3_node_batched_spv, sizeof(agx3_node_batched_spv), sizeof(nodes), + &pipeline, &layout) : VK_ERROR_OUT_OF_DEVICE_MEMORY; + if (result != VK_SUCCESS) { + vk_command_buffer_set_error(&cmd->vk, result); + return; + } + vk_common_CmdBindPipeline(commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, + pipeline); + vk_common_CmdPushConstants(commandBuffer, layout, + VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(nodes), + &nodes); + hk_cmd_dispatch_indirect_addr(commandBuffer, dispatch.gpu); + hk_m5_barrier(commandBuffer, false); + + /* Then finish the bottom-level structures. */ + hk_m5_envelopes(commandBuffer, envelopes.gpu, envelope_status, bottom); } /* The upstream runtime hands encoding every state of a batch at once, after