From 7e9fe5c3a726fd455b5932c8e441baa43cf2f9d3 Mon Sep 17 00:00:00 2001 From: Blaise Tine Date: Mon, 30 Nov 2026 18:32:34 -0800 Subject: [PATCH 1/4] memmap: a 16 KiB stack per thread; RV64 buffers reach past the 8 GB stack window - VX_MEM_STACK_LOG2_SIZE 13 -> 14. A Vulkan shader's deepest call chain (register spills across an unrolled loop of calls into the software sampler) needs more than 8 KiB (the robustness megashader uses 9,136 B), and a frame past its stack corrupts the neighbouring thread's. The stack window's top is aligned to 512 KB instead of 256 KB. VX_lsu_agu and SimX's stack interleave assert that the window stays above the page tables. - RV64: the runtime's heap grows from 8 GB to 32 GB (a scene's acceleration structures and resident buffers exceed 8 GB together, LumiBench CAR and ROBOT). The stack and local-memory window, whose top stays at 8 GB, is reserved out of it before any allocation. Default behaviour (changes it): every kernel's stack base and size move (lui sp, 0xfff80 instead of 0xfffc0); SimX cycles shift by up to about +/-0.5% (identity check: with master's stack size, 15 of 20 differing apps become identical). Branch commits: 8e60ede4b, b7799cb2b. Co-Authored-By: Claude Opus 5.5 --- VX_types.toml | 11 +++++++---- hw/rtl/core/VX_lsu_agu.sv | 6 ++++++ sim/simx/stack_interleave.h | 3 +++ sw/runtime/common/common.h | 9 ++++++++- sw/runtime/common/device.cpp | 24 ++++++++++++++++++++++++ 5 files changed, 48 insertions(+), 5 deletions(-) diff --git a/VX_types.toml b/VX_types.toml index dbc268d125..35be7531f4 100644 --- a/VX_types.toml +++ b/VX_types.toml @@ -18,13 +18,16 @@ VX_ISA_IMPL_ID = 0 # into them. [memmap] VX_MEM_USER_BASE_ADDR = "expr: 0x0000000000010000 if ($XLEN == 64) else 0x00010000" -VX_MEM_STACK_LOG2_SIZE = 13 -# The stack window's top is aligned to max(256 KB, NUM_THREADS stacks): the -# 256 KB-aligned top, rounded down to a whole group of NUM_THREADS stacks. The +# 16 KiB per thread: a kernel's deepest call chain (register spills across an +# unrolled loop of calls into the SW sampler) can need more than 8 KiB, and a +# frame past its stack corrupts the neighbouring thread's. +VX_MEM_STACK_LOG2_SIZE = 14 +# The stack window's top is aligned to max(512 KB, NUM_THREADS stacks): the +# 512 KB-aligned top, rounded down to a whole group of NUM_THREADS stacks. The # window then lies on whole groups and the stack interleave is a pure bit # permutation. The local memory window starts at the same address and runs to # the next such boundary, which bounds its capacity. -stack_window_top = "expr: 0x00000001FFFC0000 if ($XLEN == 64) else 0xFFFC0000" +stack_window_top = "expr: 0x00000001FFF80000 if ($XLEN == 64) else 0xFFF80000" VX_MEM_STACK_BASE_ADDR = "expr: $stack_window_top - ($stack_window_top % ($VX_CFG_NUM_THREADS << $VX_MEM_STACK_LOG2_SIZE))" VX_MEM_LMEM_BASE_ADDR = "expr: $VX_MEM_STACK_BASE_ADDR" VX_MEM_IO_BASE_ADDR = "expr: 0x0000000000000040 if ($XLEN == 64) else 0x00000040" diff --git a/hw/rtl/core/VX_lsu_agu.sv b/hw/rtl/core/VX_lsu_agu.sv index 2c35a38cb2..024ad87e2d 100644 --- a/hw/rtl/core/VX_lsu_agu.sv +++ b/hw/rtl/core/VX_lsu_agu.sv @@ -59,6 +59,12 @@ module VX_lsu_agu import VX_gpu_pkg::*; ( assign lin_addr = csa_sum[`VX_CFG_XLEN-1:0] + csa_carry[`VX_CFG_XLEN-1:0]; `UNUSED_VAR ({csa_sum[`VX_CFG_XLEN+1:`VX_CFG_XLEN], csa_carry[`VX_CFG_XLEN+1:`VX_CFG_XLEN]}) + // The stacks must stay above the page tables (and the OM aperture below them). + localparam [`VX_CFG_XLEN-1:0] PAGE_TABLE_END = `VX_CFG_XLEN'(`VX_MEM_PAGE_TABLE_BASE_ADDR) + + `VX_CFG_XLEN'(`VX_VM_PT_SIZE_LIMIT); + `STATIC_ASSERT(STACK_WINDOW_SPAN <= STACK_WINDOW_TOP && STACK_WINDOW_BOTTOM >= PAGE_TABLE_END, + ("invalid parameter: stack window reaches into the page-table region")) + `ifdef VX_CFG_LSU_STACK_INTERLEAVE_ENABLE // Thread t's stack is the STACK_SIZE bytes below STACK_TOP - t*STACK_SIZE. // Within each group of NUM_THREADS stacks, offset {thread, word, byte} is diff --git a/sim/simx/stack_interleave.h b/sim/simx/stack_interleave.h index 53e4f35eed..9ec7480803 100644 --- a/sim/simx/stack_interleave.h +++ b/sim/simx/stack_interleave.h @@ -48,6 +48,9 @@ class StackInterleave { static_assert(ispow2(NUM_THREADS), "stack interleave needs a power-of-two thread count"); static_assert(SPAN <= TOP, "stack window underflows the address space"); + // The stacks must stay above the page tables (and the OM aperture below them). + static_assert(BOTTOM >= uint64_t(VX_MEM_PAGE_TABLE_BASE_ADDR) + VX_VM_PT_SIZE_LIMIT, + "stack window reaches into the page-table region"); static_assert(!ENABLED || TOP % GROUP_SIZE == 0, "stack window top is not aligned to a group of stacks"); static bool contains(uint64_t addr) { diff --git a/sw/runtime/common/common.h b/sw/runtime/common/common.h index 4b6705f7df..71f455dae6 100644 --- a/sw/runtime/common/common.h +++ b/sw/runtime/common/common.h @@ -29,10 +29,17 @@ #define ALLOC_BASE_ADDR VX_MEM_USER_BASE_ADDR +// The device address space buffers are allocated from. On RV64 it reaches past +// the stack and local-memory window, whose top stays at 8 GB (the 512 KB-aligned +// VX_MEM_STACK_BASE_ADDR plus one window): a scene's acceleration structures +// and the resident copies of its buffers can exceed 8 GB together (LumiBench +// CAR, ROBOT). #if (VX_CFG_XLEN == 64) -#define GLOBAL_MEM_SIZE 0x200000000 // 8 GB +#define GLOBAL_MEM_SIZE 0x800000000 // 32 GB +#define STACK_WINDOW_END 0x200000000 // 8 GB #else #define GLOBAL_MEM_SIZE 0x100000000 // 4 GB +#define STACK_WINDOW_END GLOBAL_MEM_SIZE #endif #ifndef NDEBUG diff --git a/sw/runtime/common/device.cpp b/sw/runtime/common/device.cpp index f6299fa2f3..96bd4901d6 100644 --- a/sw/runtime/common/device.cpp +++ b/sw/runtime/common/device.cpp @@ -384,6 +384,30 @@ vx_result_t Device::cp_init() { if (rc != VX_SUCCESS) return rc; } + // The per-thread stacks fill the space below VX_MEM_STACK_BASE_ADDR, with + // the local-memory window above it, and on RV64 the heap reaches past them: + // carve the window out before any mem_alloc is reachable. + uint64_t stack_low = 0; + { + uint64_t num_warps = 0, num_threads = 0; + auto rc = this->query_caps(VX_CAPS_NUM_WARPS, &num_warps); + if (rc != VX_SUCCESS) { + return rc; + } + rc = this->query_caps(VX_CAPS_NUM_THREADS, &num_threads); + if (rc != VX_SUCCESS) { + return rc; + } + const uint64_t harts = cp_num_cores_ * num_warps * num_threads; + stack_low = VX_MEM_STACK_BASE_ADDR - (harts << VX_MEM_STACK_LOG2_SIZE); + std::lock_guard g(mu_); + static_assert(VX_MEM_STACK_BASE_ADDR < STACK_WINDOW_END, + "the stack and local-memory window must end at STACK_WINDOW_END"); + if (global_mem_.reserve(stack_low, STACK_WINDOW_END - stack_low) != 0) { + return VX_ERR_DEVICE_LOST; + } + } + if (vm_enabled_) { // Virtual memory: build the page tables and program the CP DMA's MMU // with the page-table root. After this, mem_alloc mints VAs and the From 2ddc3fb7fb49d9909266b751f09229dca4eb47f1 Mon Sep 17 00:00:00 2001 From: Blaise Tine Date: Mon, 30 Nov 2026 18:32:35 -0800 Subject: [PATCH 2/4] toolchain v3.0.4: mesa-vortex, PoCL and the Khronos Vulkan loader for the graphics stack TOOLCHAIN_REV moves to v3.0.4, whose bundles the graphics stack needs: llvm-vortex fixes, mesa-vortex rebuilt from the integrated Mesa (with a -z nodelete ICD), PoCL and Mesa built from their vortex_3.1 branches, the pinned SPIR-V translator, and the Khronos Vulkan loader (toolchain_install.sh --vulkan-loader, ci/vk_loader_check.sh). Docs: building_toolchain.md, rhel/9 prebuilt bundles of CIRCT, Beacon and Foldsim. Default behaviour: none in the hardware or simulators; the CI toolchain version changes. Branch commits: c2c244152, 67b516acf, 90746d69d, f1052b730, fcc855352, e0b786247, 79d9e0a5b. Co-Authored-By: Claude Opus 5.5 --- VERSION | 2 +- ci/mesa_install.sh.in | 4 +- ci/toolchain_install.sh.in | 17 ++- ci/toolchain_prebuilt.sh.in | 15 ++- ci/vk_loader_check.sh | 53 +++++++++ docs/assets/img/gfx_software_stack.svg | 2 +- .../assets/img/opencl_system_architecture.svg | 2 +- docs/building_toolchain.md | 111 +++++++++++++++--- docs/designs/graphics_software_stack.md | 2 +- docs/designs/opencl_on_vortex.md | 2 +- docs/designs/vortexpipe_architecture.md | 2 +- tests/vulkan/common.mk | 13 +- 12 files changed, 197 insertions(+), 28 deletions(-) create mode 100644 ci/vk_loader_check.sh diff --git a/VERSION b/VERSION index 336ccb18c6..0a2902af33 100644 --- a/VERSION +++ b/VERSION @@ -1,4 +1,4 @@ VORTEX_VERSION=3.0 -TOOLCHAIN_REV=v3.0.3 +TOOLCHAIN_REV=v3.0.4 GEM5_REV=v25.0.0.1 FIRESIM_REV=8500116387e0a5fcfde303fb9d18ac3cc84de74f diff --git a/ci/mesa_install.sh.in b/ci/mesa_install.sh.in index 510a8c7ac3..46fdb5e7e4 100644 --- a/ci/mesa_install.sh.in +++ b/ci/mesa_install.sh.in @@ -24,7 +24,7 @@ # (ci/toolchain_install.sh). The apt steps need sudo. # # The defaults build the Vortex Mesa fork -# https://github.com/vortexgpgpu/mesa (branch vortex_3.x) +# https://github.com/vortexgpgpu/mesa (branch vortex_3.1) # whose `vortexpipe` Gallium driver runs Vulkan workloads on the # Vortex GPU. For a vanilla-lavapipe baseline (no vortexpipe), # override MESA_REPO/MESA_REV and set GALLIUM_DRIVERS=llvmpipe. @@ -61,7 +61,7 @@ fi # Pinned source: the Vortex Mesa fork carrying the vortexpipe driver. MESA_REPO=${MESA_REPO:=https://github.com/vortexgpgpu/mesa.git} -MESA_REV=${MESA_REV:=vortex_3.x} +MESA_REV=${MESA_REV:=vortex_3.1} # Gallium / Vulkan driver set. `llvmpipe`+`vortexpipe` (Gallium) under # `swrast` (Vulkan) is lavapipe plus the Vortex accelerator: diff --git a/ci/toolchain_install.sh.in b/ci/toolchain_install.sh.in index e1071b0b96..e0094c12bc 100755 --- a/ci/toolchain_install.sh.in +++ b/ci/toolchain_install.sh.in @@ -148,6 +148,18 @@ mesa() rm -rf mesa-vortex.tar.bz2 } +# The Khronos Vulkan loader (libvulkan.so.1) the Vulkan tests and the CTS run +# with, ahead of the host's: hosts ship loaders without upstream fixes the +# Vortex driver depends on (EL9 1.4.328.1 dlcloses an ICD twice on an +# out-of-memory path of vkCreateInstance; fixed in Vulkan-Loader v1.4.333). +vulkan_loader() +{ + wget $REPOSITORY/vulkan-loader/$OSVERSION/vulkan-loader.tar.bz2 + tar -xvf vulkan-loader.tar.bz2 + mkdir -p $TOOLDIR && rm -rf $TOOLDIR/vulkan-loader && mv vulkan-loader $TOOLDIR + rm -rf vulkan-loader.tar.bz2 +} + verilator() { fetch_parts verilator verilator/$OSVERSION @@ -240,6 +252,7 @@ install_base() yosys sta mesa + vulkan_loader } # SST is built from source by ci/sst_install.sh — see the matching @@ -248,7 +261,7 @@ install_base() show_usage() { echo "Install Pre-built Vortex Toolchain" - echo "Usage: $0 [--pocl] [--chipstar] [--mesa] [--verilator] [--riscv32] [--riscv64] [--llvm] [--libcrt32] [--libcrt64] [--libc32] [--libc64] [--circt] [--foldsim] [--beacon] [--yosys] [--sta] [--gem5] [--all] [-h|--help]" + echo "Usage: $0 [--pocl] [--chipstar] [--mesa] [--vulkan-loader] [--verilator] [--riscv32] [--riscv64] [--llvm] [--libcrt32] [--libcrt64] [--libc32] [--libc64] [--circt] [--foldsim] [--beacon] [--yosys] [--sta] [--gem5] [--all] [-h|--help]" echo " (no arguments: install all components except Foldsim, Beacon and gem5)" echo " Foldsim, Beacon and gem5 are opt-in: Foldsim serves only the Foldsim flow," echo " Beacon only the logic gate, and gem5 is a large source build. --all" @@ -269,6 +282,8 @@ while [ "$1" != "" ]; do ;; --mesa ) mesa ;; + --vulkan-loader ) vulkan_loader + ;; --verilator ) verilator ;; --riscv32 ) riscv32 diff --git a/ci/toolchain_prebuilt.sh.in b/ci/toolchain_prebuilt.sh.in index 457b2ead02..e6e5723b4b 100755 --- a/ci/toolchain_prebuilt.sh.in +++ b/ci/toolchain_prebuilt.sh.in @@ -115,6 +115,16 @@ mesa() mv mesa-vortex.tar.bz2 ./mesa-vortex/$OSVERSION } +# The Khronos Vulkan loader, a per-OS tarball unpacked into +# $TOOLDIR/vulkan-loader (lib/libvulkan.so*). ~0.2 MB compressed. +vulkan_loader() +{ + echo "prebuilt vulkan-loader..." + tar -C $TOOLDIR -cvjf vulkan-loader.tar.bz2 vulkan-loader + mkdir -p ./vulkan-loader/$OSVERSION + mv vulkan-loader.tar.bz2 ./vulkan-loader/$OSVERSION +} + verilator() { echo "prebuilt verilator..." @@ -201,7 +211,7 @@ gem5() show_usage() { echo "Setup Pre-built Vortex Toolchain" - echo "Usage: $0 [--pocl] [--chipstar] [--mesa] [--verilator] [--riscv32] [--riscv64] [--llvm] [--libcrt32] [--libcrt64] [--libc32] [--libc64] [--circt] [--foldsim] [--beacon] [--yosys] [--sta] [--gem5] [--all] [-h|--help]" + echo "Usage: $0 [--pocl] [--chipstar] [--mesa] [--vulkan-loader] [--verilator] [--riscv32] [--riscv64] [--llvm] [--libcrt32] [--libcrt64] [--libc32] [--libc64] [--circt] [--foldsim] [--beacon] [--yosys] [--sta] [--gem5] [--all] [-h|--help]" } while [ "$1" != "" ]; do @@ -212,6 +222,8 @@ while [ "$1" != "" ]; do ;; --mesa ) mesa ;; + --vulkan-loader ) vulkan_loader + ;; --verilator ) verilator ;; --riscv32 ) riscv32 @@ -256,6 +268,7 @@ while [ "$1" != "" ]; do yosys sta mesa + vulkan_loader gem5 ;; -h | --help ) show_usage diff --git a/ci/vk_loader_check.sh b/ci/vk_loader_check.sh new file mode 100644 index 0000000000..7df36d6b6f --- /dev/null +++ b/ci/vk_loader_check.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# Print the Vulkan loader a Vulkan test or CTS run will load, and fail with a +# clear message when it is older than 1.4.333 while the ICD is not robust to it. +# +# Vulkan-Loader before v1.4.333 (EL9 ships 1.4.328.1) closes the ICD twice when +# an allocation fails inside vkCreateInstance (upstream fix dc509c2de). The +# extra dlclose unmaps lavapipe/vortexpipe under a live instance unless the ICD +# is linked with -z nodelete, and the run then crashes (CTS +# api.device_init.create_instance_device_intentional_alloc_fail). The toolchain +# ships a fixed loader: ci/toolchain_install.sh --vulkan-loader. +# +# Usage: vk_loader_check.sh [icd.json] (default: $VK_ICD_FILENAMES) +# Resolves libvulkan.so.1 the way the dynamic linker does for the caller's +# LD_LIBRARY_PATH (then the ld.so cache). Exit 0: usable; 1: old loader and a +# non-robust ICD; 2: no loader found. + +ICD=${1:-${VK_ICD_FILENAMES%%:*}} + +LIB= +IFS=: read -ra dirs <<< "${LD_LIBRARY_PATH:-}" +for d in "${dirs[@]}"; do + [ -n "$d" ] && [ -e "$d/libvulkan.so.1" ] && { LIB=$d/libvulkan.so.1; break; } +done +[ -n "$LIB" ] || LIB=$(ldconfig -p 2>/dev/null | sed -n 's/.*libvulkan\.so\.1 (libc6,x86-64) => //p' | head -1) +if [ -z "$LIB" ]; then + echo "vk_loader_check: FAIL: no libvulkan.so.1 on LD_LIBRARY_PATH or in the ld.so cache" + exit 2 +fi +REAL=$(readlink -f "$LIB") +VER=$(basename "$REAL" | sed -n 's/^libvulkan\.so\.\([0-9][0-9.]*\)$/\1/p') +[ -n "$VER" ] || VER=$(strings -a "$REAL" 2>/dev/null | sed -n 's/^.*Vulkan Loader Version \([0-9][0-9.]*\).*$/\1/p' | head -1) + +ROBUST=no +if [ -n "$ICD" ] && [ -f "$ICD" ]; then + so=$(sed -n 's/.*"library_path"[^"]*"\([^"]*\)".*/\1/p' "$ICD" | head -1) + case $so in /*) ;; *) so=$(dirname "$ICD")/$so ;; esac + readelf -d "$so" 2>/dev/null | grep -q 'FLAGS_1.*NODELETE' && ROBUST=yes +fi + +echo "vk_loader_check: loader $REAL (version ${VER:-unknown}); ICD ${ICD:-none} nodelete=$ROBUST" +older=1 +if [ -n "$VER" ]; then + [ "$(printf '%s\n1.4.333\n' "$VER" | sort -V | head -1)" = 1.4.333 ] && older=0 +fi +if [ $older = 1 ] && [ $ROBUST = no ]; then + echo "vk_loader_check: FAIL: Vulkan loader ${VER:-of unknown version} is older than 1.4.333 and the ICD is not linked" + echo " with -z nodelete: an allocation failure in vkCreateInstance unmaps the ICD under a live instance." + echo " Install the toolchain loader (ci/toolchain_install.sh --vulkan-loader) and put" + echo " \$TOOLDIR/vulkan-loader/lib first on LD_LIBRARY_PATH (tests/vulkan/common.mk does), or use a" + echo " Mesa whose libvulkan_lvp.so is linked with -z nodelete." + exit 1 +fi +exit 0 diff --git a/docs/assets/img/gfx_software_stack.svg b/docs/assets/img/gfx_software_stack.svg index 300bcb7233..62e1767768 100644 --- a/docs/assets/img/gfx_software_stack.svg +++ b/docs/assets/img/gfx_software_stack.svg @@ -31,7 +31,7 @@ - mesa_vortex (branch vortex_3.x) — the Vulkan / Gallium driver + mesa_vortex (branch vortex_3.1) — the Vulkan / Gallium driver lavapipe diff --git a/docs/assets/img/opencl_system_architecture.svg b/docs/assets/img/opencl_system_architecture.svg index 937aa985e7..7053ffb3a0 100644 --- a/docs/assets/img/opencl_system_architecture.svg +++ b/docs/assets/img/opencl_system_architecture.svg @@ -45,7 +45,7 @@ - libpocl.so — PoCL ICD (external: vortexgpgpu/pocl @ vortex_3.x) + libpocl.so — PoCL ICD (external: vortexgpgpu/pocl @ vortex_3.1) OpenCL-C / SPIR-V front end · work-group passes · host runtime diff --git a/docs/building_toolchain.md b/docs/building_toolchain.md index 15debc9180..1b214d64ab 100644 --- a/docs/building_toolchain.md +++ b/docs/building_toolchain.md @@ -212,9 +212,10 @@ The translator binary `llvm-spirv` is built separately against an installed LLVM and lives alongside it. ```bash -git clone --branch llvm_release_200 --depth 1 \ +git clone --branch llvm_release_200 \ https://github.com/KhronosGroup/SPIRV-LLVM-Translator.git cd SPIRV-LLVM-Translator +git checkout df411ebb66357d28ed954988708c71ba98ec1aed mkdir build && cd build cmake -DCMAKE_BUILD_TYPE=Release \ @@ -229,6 +230,17 @@ Match the translator branch to the LLVM major version you built (`llvm_release_200` for LLVM 20, `llvm_release_180` for LLVM 18, etc.). v3.0 uses `llvm_release_200`. +Pin the commit; don't build the branch head. clang's HIP-on-SPIR-V +toolchain, which chipStar's `hipcc` drives, runs `llvm-spirv +--spirv-max-version=1.1 --spirv-ext=+all`. From `llvm_release_200` +`2a0cfc1b` onward (`SPV_KHR_float_controls2`, committed 2026-10-12), `+all` +lets the translator decorate fast-math operations with +`SPV_KHR_float_controls2`, which needs SPIR-V 1.2. Every HIP device link then +fails: "SPIR-V version was restricted to at most 1.1 ... requires SPIR-V +version 1.2". `df411ebb` is the translator the v3.0.3 `ubuntu/focal` +llvm-vortex bundle ships. The v3.0.4 llvm-vortex bundles for both OSes are +built with it (since v3.0.4's 2026-11-28 update). + --- ## 4. compiler-rt for Vortex @@ -261,6 +273,8 @@ cmake -G "Unix Makefiles" \ -DCMAKE_RANLIB="$LLVM_PREFIX/bin/llvm-ranlib" \ -DCMAKE_C_COMPILER="$LLVM_PREFIX/bin/clang" \ -DCMAKE_C_COMPILER_TARGET="riscv32-unknown-elf" \ + -DCMAKE_ASM_COMPILER_TARGET="riscv32-unknown-elf" \ + -DCMAKE_ASM_FLAGS="-march=rv32imaf -mabi=ilp32f -mcmodel=medany" \ -DCMAKE_C_FLAGS="--gcc-toolchain=$RISCV_GCC_TOOLCHAIN \ -march=rv32imaf -mabi=ilp32f \ -Xclang -target-feature -Xclang +xvortex \ @@ -281,6 +295,10 @@ cmake -G "Unix Makefiles" \ -DCOMPILER_RT_BUILD_PROFILE=OFF \ -DCOMPILER_RT_BUILD_SANITIZERS=OFF \ -DCOMPILER_RT_BUILD_XRAY=OFF \ + -DCOMPILER_RT_BUILD_CTX_PROFILE=OFF \ + -DCOMPILER_RT_BUILD_ORC=OFF \ + -DCOMPILER_RT_BUILD_GWP_ASAN=OFF \ + -DCOMPILER_RT_BUILD_CRT=ON \ -DCOMPILER_RT_BAREMETAL_BUILD=ON \ -DCOMPILER_RT_INCLUDE_TESTS=OFF \ ../compiler-rt @@ -289,6 +307,18 @@ make -j$(nproc) make install ``` +The output is `libclang_rt.builtins-riscv32.a` plus `clang_rt.crtbegin-riscv32.o` +and `clang_rt.crtend-riscv32.o`. Two of the settings above matter with LLVM 20 +and CMake 3.31: + +- `CTX_PROFILE`, `ORC` and `GWP_ASAN` default to on and build + `sanitizer_common`, which needs glibc's `features.h` and stops the + baremetal build. +- CMake compiles the assembly builtins (`riscv/save.S`, `restore.S`, + `muldi3.S`) as `ASM`, which takes neither `CMAKE_C_COMPILER_TARGET` nor + `CMAKE_C_FLAGS`. Without the two `CMAKE_ASM_*` settings, clang assembles + them for the host and stops at `xlen must be 32 or 64`. + ### 64-bit Identical to the 32-bit build except for the substitutions: @@ -296,8 +326,8 @@ Identical to the 32-bit build except for the substitutions: | 32-bit value | 64-bit value | |---|---| | `-DCMAKE_INSTALL_PREFIX=$TOOLDIR/libcrt32` | `$TOOLDIR/libcrt64` | -| `-DCMAKE_C_COMPILER_TARGET="riscv32-unknown-elf"` | `riscv64-unknown-elf` | -| `-march=rv32imaf -mabi=ilp32f` | `-march=rv64imafd -mabi=lp64d` | +| `-DCMAKE_C_COMPILER_TARGET` / `-DCMAKE_ASM_COMPILER_TARGET` `"riscv32-unknown-elf"` | `riscv64-unknown-elf` | +| `-march=rv32imaf -mabi=ilp32f` (C and ASM flags) | `-march=rv64imafd -mabi=lp64d` | | `link32.ld` | `link64.ld` | | `riscv32-gnu-toolchain` (sysroot path) | `riscv64-gnu-toolchain` | | `riscv32-unknown-elf` (sysroot subdir, default triple) | `riscv64-unknown-elf` | @@ -331,8 +361,9 @@ mkdir build && cd build ### 32-bit ```bash -CC=$LLVM_PREFIX/bin/clang \ -CFLAGS="--sysroot=$TOOLDIR/riscv32-gnu-toolchain/riscv32-unknown-elf \ +CC=$LLVM_PREFIX/bin/clang AR=$LLVM_PREFIX/bin/llvm-ar RANLIB=$LLVM_PREFIX/bin/llvm-ranlib \ +CFLAGS="--target=riscv32-unknown-elf \ + --sysroot=$TOOLDIR/riscv32-gnu-toolchain/riscv32-unknown-elf \ --gcc-toolchain=$TOOLDIR/riscv32-gnu-toolchain \ -march=rv32imaf -mabi=ilp32f \ -Xclang -target-feature -Xclang +xvortex \ @@ -348,8 +379,9 @@ make install ### 64-bit ```bash -CC=$LLVM_PREFIX/bin/clang \ -CFLAGS="--sysroot=$TOOLDIR/riscv64-gnu-toolchain/riscv64-unknown-elf \ +CC=$LLVM_PREFIX/bin/clang AR=$LLVM_PREFIX/bin/llvm-ar RANLIB=$LLVM_PREFIX/bin/llvm-ranlib \ +CFLAGS="--target=riscv64-unknown-elf \ + --sysroot=$TOOLDIR/riscv64-gnu-toolchain/riscv64-unknown-elf \ --gcc-toolchain=$TOOLDIR/riscv64-gnu-toolchain \ -march=rv64imafd -mabi=lp64d \ -Xclang -target-feature -Xclang +xvortex \ @@ -364,6 +396,25 @@ make install `--disable-shared` keeps musl as `.a` archives only — Vortex kernels are statically linked. +One local change, in the v3.0.4 libc bundles: **riscv32 +`setjmp`/`longjmp`** save and restore `fs0`-`fs11` with `fsw`/`flw` under +`ilp32f` (rv32imaf has no D, so musl's `fsd`/`fld` do not assemble); same +`jmp_buf` offsets. + +Use llvm-vortex `a0df07abbec2` or later. `a81a5957f406` crashes on +`src/misc/wordexp.c`, `src/network/lookup_serv.c` and +`src/network/resolvconf.c`, and never finishes `src/passwd/getgr_a.c`. +The crash comes from duplicated `vx_join` blocks that leave `vx_split`/`vx_join` +dominance invalid after instruction selection. `a0df07abbec2` ("A join is never +duplicated") compiles all four in about a second and passes +`-verify-machineinstrs`. + +Rebuild libc whenever llvm-vortex changes code generation for `+xvortex`: +the libc carries split/join code, and a libc compiled by an older compiler +keeps that compiler's bugs (the libc of 2026-05-17, built by llvm-vortex +`87f0227cb`, returned `rint(+0.0) = -0.0`: its divergent `>=` select was +lowered as `>`, fixed by llvm-vortex `69af3fd0084d`). + --- ## 6. POCL for Vortex @@ -373,7 +424,14 @@ target. POCL ingests OpenCL-C (and, with SPIR-V enabled, SPIR-V via `clCreateProgramWithIL`) and dispatches to the Vortex runtime. -> **v3.0 baseline:** branch `vortex_3.x`, POCL 7.0 derived from +> **Branch:** `vortex_3.1`, which the prebuilt bundles build (v3.0.4 (updated 2026-11-28): `6b98cc8d4f5c`). Since +> `e6df1d510` it programs the TEX unit in texels (`VX_DCR_TEX_DIM`, DCR `0x042`), as Vortex has +> read that DCR since `f2d4c7edc`. It also carries `vortex_3.x`'s atomics, fence and +> TEX-descriptor commits (`49593dcdc`, `7fac914a7`, `471f88096`, forward-ported), so it holds +> everything `vortex_3.x` has. A PoCL without `e6df1d510` writes log2 dimensions there, so the +> TEX unit samples a 16x16 image as 4x4. +> +> **v3.0 baseline:** POCL 7.0 derived from > `upstream/release_6_0`. Includes the SPIR-V ingestion path > (`clCreateProgramWithIL`) and the > `cl_ext_buffer_device_address` extension that chipStar's @@ -389,7 +447,7 @@ POCL consumes Vortex through its install tree (`$VORTEX_PATH`) via `vortex-kernel.pc` exist under `$VORTEX_PATH/lib/pkgconfig/`. ```bash -git clone --branch vortex_3.x --recursive https://github.com/vortexgpgpu/pocl +git clone --branch vortex_3.1 --recursive https://github.com/vortexgpgpu/pocl cd pocl mkdir build && cd build @@ -600,6 +658,19 @@ Vulkan driver is built on. The `vortexpipe` Gallium driver > Tests pick the install up via the `MESA_PATH` make var declared in > `tests/vulkan/common.mk` (defaults to `$(TOOLDIR)/mesa-vortex`). +> **Vulkan loader:** the tests and the CTS load the ICD through the +> Khronos loader of the toolchain, `$TOOLDIR/vulkan-loader/lib/libvulkan.so.1` +> (`ci/toolchain_install.sh --vulkan-loader`, folded into the default +> install and `--all`), not the host's: `tests/vulkan/common.mk` links +> against it and puts it first on `LD_LIBRARY_PATH` (`VULKAN_LOADER_PATH`, +> default `$(TOOLDIR)/vulkan-loader`). The host loader of EL9 (1.4.328.1) +> closes the ICD twice when an allocation fails inside `vkCreateInstance` +> and crashes CTS `api.device_init.create_instance_device_intentional_alloc_fail`; +> Vulkan-Loader v1.4.333 fixed it (upstream `dc509c2de`). The bundle is +> Vulkan-Loader `v1.4.369` built per OS with the XCB, Xlib and Wayland WSI +> and the distribution search paths (`SYSCONFDIR=/etc`), so it finds the +> same ICDs and layers as the host loader. + > **Build-from-source path:** `ci/mesa_install.sh` performs every > step below (build deps, meson configure, build, install) and is > the *producer* of the `mesa-vortex` prebuilt — run once per OS by @@ -607,8 +678,12 @@ Vulkan driver is built on. The `vortexpipe` Gallium driver > `ci/toolchain_prebuilt.sh --mesa`. This section documents the > manual build for maintainers. -> **v3.0 pin:** branch `vortex_3.x` of -> `github.com/vortexgpgpu/mesa` — a fork of upstream Mesa at tag +> **Branch:** `vortex_3.1` of `github.com/vortexgpgpu/mesa`, which the prebuilt bundles build +> (v3.0.4 (updated 2026-11-28): `d6393456d15`, not yet published on vortexgpgpu/mesa (vortex_3.1 is +> `f14e52d6aaf`)). It contains every `vortex_3.x` commit, so it holds everything +> `vortex_3.x` has. +> +> **v3.0 baseline:** `github.com/vortexgpgpu/mesa` — a fork of upstream Mesa at tag > `mesa-25.1.0`, carrying the `vortexpipe` Gallium driver. Built > with `gallium-drivers=llvmpipe,vortexpipe`. @@ -643,7 +718,7 @@ the Vortex build dir first so `vortex-runtime.pc` is on `PKG_CONFIG_PATH`. ```bash -git clone --branch vortex_3.x https://github.com/vortexgpgpu/mesa.git mesa_vortex +git clone --branch vortex_3.1 https://github.com/vortexgpgpu/mesa.git mesa_vortex cd mesa_vortex # Put the Vortex LLVM's llvm-config first so meson selects it. @@ -1392,10 +1467,14 @@ kernel library depends on. | verilator | §1 at the focal version, `--disable-tcmalloc` (so no gperftools runtime dependency) | | yosys | CMake, `BUILD_SHARED_LIBS=OFF`, `YOSYS_ENABLE_UNIT_TESTS=OFF`, libffi linked statically | | sta | §8 at the focal commit; CUDD, SWIG and Eigen built into a private prefix | -| pocl, chipstar, mesa-vortex | the focal binaries, copied unchanged (glibc ≤ 2.34, `GLIBCXX` ≤ 3.4.29); they link the `rhel/9` LLVM, which has the same sonames and ABI | - -Keep the two OS slots in lockstep. When llvm, verilator, yosys or sta is -refreshed for `ubuntu/focal`, rebuild it on EL9 and package it with +| pocl | §6 against the `rhel/9` LLVM with system GCC 11, plus `-DCMAKE_INSTALL_LIBDIR=lib` (GNUInstallDirs picks `lib64` on EL9) and an OpenCL ICD loader on `PKG_CONFIG_PATH` (EL9 has no `ocl-icd` by default, and without a loader `ENABLE_ICD` quietly turns off and a standalone `libOpenCL.so` is built). The bundle has the focal bundle's files (`lib/libpocl.so*`, `etc/OpenCL/vendors/pocl.icd`, both kernel bitcodes) plus `include/CL`, because EL9 ships no OpenCL headers and `tests/opencl` compiles with `-I$(POCL_PATH)/include` | +| chipstar | the focal binaries, copied unchanged (glibc ≤ 2.34, `GLIBCXX` ≤ 3.4.29); they link the `rhel/9` LLVM, which has the same sonames and ABI | +| mesa-vortex | §9 with `ci/mesa_install.sh`'s options against the `rhel/9` LLVM, built in an `almalinux:9` container (system GCC 11; EL9 has no X11/Wayland development packages by default) with the XCB, Xlib, Wayland and libglvnd development packages; the focal one in `ubuntu:22.04` the same way. Both are built against the same Vortex source tree, so the front-end kernels `vortexpipe` embeds are byte-identical on the two OSes. Mesa must be rebuilt whenever an input of those kernels changes, because `vortexpipe` compiles and embeds them: `sw/gfx`, `sw/common`, `sw/kernel` (headers, the `libvortex2.a` sources, the linker scripts and `vxbin.py`), `VX_config.toml`/`VX_types.toml` (the generated config headers), or `third_party/cocogfx` | +| circt, beacon, foldsim | §14-16 with the focal configuration (Release, slang, libstdc++ static) built with gcc-toolset-13 (EL9's GCC 11 has no `libstdc++.a`); circt at the focal bundle's commit, so `circt-verilog` prints the same `CIRCT ` line on both OSes (the Beacon gate fingerprint). The focal `circt-verilog` binds `hypot@GLIBC_2.35` and does not load on EL9 | +| vulkan-loader | Khronos Vulkan-Loader at the focal bundle's tag, built in an `almalinux:9` container (glibc 2.34) with the WSI development headers (XCB, Xlib, Xrandr, Wayland; the loader does not link those libraries) and `SYSCONFDIR=/etc`; the focal one in `ubuntu:22.04` the same way | + +Keep the two OS slots in lockstep. When llvm, verilator, yosys, sta, circt, +beacon, foldsim or vulkan-loader is refreshed for `ubuntu/focal`, rebuild it on EL9 and package it with `OSVERSION=rhel/9 ./ci/toolchain_prebuilt.sh --`. When pocl, chipstar or mesa is refreshed, copy the new tarball into `/rhel/9/`. After any `rhel/9` refresh, confirm the binaries still load on a stock EL9 host (no diff --git a/docs/designs/graphics_software_stack.md b/docs/designs/graphics_software_stack.md index 22e1c0a7cb..a0086ecadd 100644 --- a/docs/designs/graphics_software_stack.md +++ b/docs/designs/graphics_software_stack.md @@ -23,7 +23,7 @@ launch path a draw delegates to), and CP that sequences a draw device-side). **Two trees:** -- **`mesa_vortex`** (branch `vortex_3.x`) — the Vulkan/Gallium **driver** +- **`mesa_vortex`** (branch `vortex_3.1`) — the Vulkan/Gallium **driver** (vortexpipe). - **this tree** — the Vortex **platform**: the SDK (runtime + device kernels + ABI), the SimX models, and the RTL. It is diff --git a/docs/designs/opencl_on_vortex.md b/docs/designs/opencl_on_vortex.md index 14e26e0a3c..131ba6a155 100644 --- a/docs/designs/opencl_on_vortex.md +++ b/docs/designs/opencl_on_vortex.md @@ -52,7 +52,7 @@ Vortex repo owns only the device-side contract plus the test/CI glue. | Component | Where | |---|---| -| PoCL ICD, the Vortex device driver (`lib/CL/devices/vortex/`), the OpenCL-C/SPIR-V→LLVM pipeline, the kernel builtin library (`lib/kernel/vortex/`) | **External:** `vortexgpgpu/pocl` @ `vortex_3.x`, built against `$TOOLDIR/llvm-vortex`, installed to `$TOOLDIR/pocl` | +| PoCL ICD, the Vortex device driver (`lib/CL/devices/vortex/`), the OpenCL-C/SPIR-V→LLVM pipeline, the kernel builtin library (`lib/kernel/vortex/`) | **External:** `vortexgpgpu/pocl` @ `vortex_3.1`, built against `$TOOLDIR/llvm-vortex`, installed to `$TOOLDIR/pocl` | | [`tests/opencl/`](../../tests/opencl/) — 48 applications + [`common.mk`](../../tests/opencl/common.mk) | In-tree | | [`ci/testcases/opencl.yaml`](../../ci/testcases/opencl.yaml) — the `opencl` catalog category (`pytest ci -m opencl`) | In-tree | | [`sw/kernel/`](../../sw/kernel/) → `libvortex2.a` — the **device runtime** every kernel ELF links against (`vx_vprintf`, KMU entry/startup), and [`sw/kernel/include/`](../../sw/kernel/include/) the builtin library compiles against | In-tree | diff --git a/docs/designs/vortexpipe_architecture.md b/docs/designs/vortexpipe_architecture.md index 977761945a..d55255cb1b 100644 --- a/docs/designs/vortexpipe_architecture.md +++ b/docs/designs/vortexpipe_architecture.md @@ -18,7 +18,7 @@ This document is the **driver deep-dive** and builds on the platform map in [`graphics_software_stack.md`](graphics_software_stack.md) — the file inventory (both trees), the SDK boundary, and the layered stack diagram live there and are not repeated here. Filename references use the upstream layout -in `mesa_vortex` (branch `vortex_3.x`). Vortex graphics ISA mnemonics +in `mesa_vortex` (branch `vortex_3.1`). Vortex graphics ISA mnemonics (`vx_tex`, `vx_om_export`, `vx_barrier`) and CSR numbers come from `sw/kernel/include/vx_graphics.h`; the encodings quoted below were checked against the live driver emitters in `vp_nir_to_llvm.c`. diff --git a/tests/vulkan/common.mk b/tests/vulkan/common.mk index ccdaeabd90..f472bf0b6d 100644 --- a/tests/vulkan/common.mk +++ b/tests/vulkan/common.mk @@ -16,6 +16,9 @@ # Mesa-with-vortexpipe install + supporting toolchain libraries. MESA_PATH ?= $(TOOLDIR)/mesa-vortex +# The Khronos loader of the toolchain (ci/toolchain_install.sh --vulkan-loader), linked and +# run ahead of the host's libvulkan.so.1. +VULKAN_LOADER_PATH ?= $(TOOLDIR)/vulkan-loader ZSTD_PATH ?= $(TOOLDIR)/zstd # Vortex runtime, built out-of-tree under the configure build dir. @@ -71,14 +74,14 @@ GLSLC ?= glslc CC ?= cc CFLAGS += -O2 -Wall -Wextra -Wfatal-errors -Werror -LDLIBS += -lvulkan +LDLIBS += -L$(VULKAN_LOADER_PATH)/lib -lvulkan # One SPIR-V module per shader source, stage kept in the name so a # test's .vert/.frag/.comp never collide (foo.vert -> foo.vert.spv). SPVS := $(addsuffix .spv, $(notdir $(SHADERS))) # Run the test under the lavapipe ICD with the vortexpipe driver -# selected; LD_LIBRARY_PATH covers Mesa, host LLVM, zstd and the +# selected; LD_LIBRARY_PATH covers the toolchain's Vulkan loader, Mesa, host LLVM, zstd and the # Vortex runtime. VORTEX_HOME / VORTEX_TOOLDIR tell vortexpipe's # .vxbin compiler where the Vortex tree and toolchain are -- needed # because a prebuilt Mesa's baked-in paths point at the build host. @@ -160,28 +163,34 @@ runtime-%: run run-simx: all $(VORTEX_RT_LIB)/libvortex.so $(RUNTIME_ARGS) $(MAKE) -C $(VORTEX_RT_SRC)/simx DESTDIR=$(VORTEX_RT_LIB) + @$(VK_LOADER_CHECK) @out=`$(RUN_ENV) LD_LIBRARY_PATH=$(RUN_LD_PATH) VORTEX_DRIVER=simx ./$(PROJECT) $(SPVS) $(OPTS) 2>&1`; \ $(check_run) run-rtlsim: all $(VORTEX_RT_LIB)/libvortex.so $(RUNTIME_ARGS) $(MAKE) -C $(VORTEX_RT_SRC)/rtlsim DESTDIR=$(VORTEX_RT_LIB) + @$(VK_LOADER_CHECK) @out=`$(RUN_ENV) LD_LIBRARY_PATH=$(RUN_LD_PATH) VORTEX_DRIVER=rtlsim ./$(PROJECT) $(SPVS) $(OPTS) 2>&1`; \ $(check_run) run-opae: all $(VORTEX_RT_LIB)/libvortex.so $(RUNTIME_ARGS) $(MAKE) -C $(VORTEX_RT_SRC)/opae DESTDIR=$(VORTEX_RT_LIB) + @$(VK_LOADER_CHECK) @out=`SCOPE_JSON_PATH=$(VORTEX_RT_LIB)/scope.json OPAE_DRV_PATHS=$(OPAE_DRV_PATHS) $(RUN_ENV) LD_LIBRARY_PATH=$(RUN_LD_PATH) VORTEX_DRIVER=opae ./$(PROJECT) $(SPVS) $(OPTS) 2>&1`; \ $(check_run) run-xrt: all $(VORTEX_RT_LIB)/libvortex.so $(RUNTIME_ARGS) $(MAKE) -C $(VORTEX_RT_SRC)/xrt DESTDIR=$(VORTEX_RT_LIB) ifeq ($(TARGET), hw) + @$(VK_LOADER_CHECK) @out=`SCOPE_JSON_PATH=$(FPGA_BIN_DIR)/scope.json XRT_INI_PATH=$(VORTEX_RT_SRC)/xrt/xrt.ini EMCONFIG_PATH=$(FPGA_BIN_DIR) XRT_DEVICE_INDEX=$(XRT_DEVICE_INDEX) XCLBIN_PATH=$(FPGA_BIN_DIR)/vortex_afu.xclbin $(RUN_ENV) LD_LIBRARY_PATH=$(XILINX_XRT)/lib:$(RUN_LD_PATH) VORTEX_DRIVER=xrt ./$(PROJECT) $(SPVS) $(OPTS) 2>&1`; \ $(check_run) else ifeq ($(TARGET), hw_emu) + @$(VK_LOADER_CHECK) @out=`SCOPE_JSON_PATH=$(FPGA_BIN_DIR)/scope.json XCL_EMULATION_MODE=$(TARGET) XRT_INI_PATH=$(VORTEX_RT_SRC)/xrt/xrt.ini EMCONFIG_PATH=$(FPGA_BIN_DIR) XRT_DEVICE_INDEX=$(XRT_DEVICE_INDEX) XCLBIN_PATH=$(FPGA_BIN_DIR)/vortex_afu.xclbin $(RUN_ENV) LD_LIBRARY_PATH=$(XILINX_XRT)/lib:$(RUN_LD_PATH) VORTEX_DRIVER=xrt ./$(PROJECT) $(SPVS) $(OPTS) 2>&1`; \ $(check_run) else + @$(VK_LOADER_CHECK) @out=`SCOPE_JSON_PATH=$(VORTEX_RT_LIB)/scope.json $(RUN_ENV) LD_LIBRARY_PATH=$(XILINX_XRT)/lib:$(RUN_LD_PATH) VORTEX_DRIVER=xrt ./$(PROJECT) $(SPVS) $(OPTS) 2>&1`; \ $(check_run) endif From 6defcd4bfe7af2176ae230062e0d086d35a301b9 Mon Sep 17 00:00:00 2001 From: Blaise Tine Date: Mon, 30 Nov 2026 18:32:36 -0800 Subject: [PATCH 3/4] vm: sparse reservations (VX_MEM_SPARSE, vx_buffer_bind) with null translations Vulkan sparse resources need device virtual addresses with no memory behind them. A VX_MEM_SPARSE buffer reserves such a range: every page reads 0 and discards writes until vx_buffer_bind maps memory there (whole bind or none, through the command processor, with a TLB flush before the next launch). - A PTE's RSW bit (N) marks a null translation; the MMU and L1 TLB honour it (VX_tlb_pkg, VX_mmu, VX_tlb_l1/l2/mshr; SimX mmu, mmu_tlb, ptw, tlb_l2). - The command processor's DMA and descriptor reads translate page by page (cp_dev_read, cp_mem_copy), so a copy across an unbound page reads zeros. - A freed buffer is unmapped and the TLBs flushed before the next launch. - The L2 TLB fill reads its victim set row from a registered per-slot copy (logic depth, no cycle change); an aperture inside an identity-mapped region counts as reserved already. Test: tests/regression/vm_sparse (CI vm-sparse cases), vm_test. Default behaviour: none at default config (VM is off by default). Branch commits: 84136cca4, f9ac6eee2, 2bd54a3fb, 294aae748, 559bf634d, ac5fe07f2. Co-Authored-By: Claude Opus 5.5 --- VX_types.toml | 3 + ci/testcases/vm.yaml | 17 + docs/assets/img/vm_tlb_l2_uarch.svg | 3 +- docs/designs/virtual_memory_subsystem.md | 90 ++++-- hw/rtl/vm/VX_mmu.sv | 18 +- hw/rtl/vm/VX_tlb_l1.sv | 3 +- hw/rtl/vm/VX_tlb_l2.sv | 47 ++- hw/rtl/vm/VX_tlb_mshr.sv | 3 + hw/rtl/vm/VX_tlb_pkg.sv | 12 +- hw/unittest/mmu_park/VX_mmu_park_top.sv | 3 +- sim/common/cmd_processor.cpp | 169 ++++++---- sim/common/cmd_processor.h | 17 +- sim/simx/mem/mmu.cpp | 10 +- sim/simx/mem/mmu_tlb.cpp | 2 +- sim/simx/mem/mmu_tlb.h | 6 +- sim/simx/mem/ptw.cpp | 2 +- sim/simx/mem/ptw.h | 2 +- sim/simx/mem/tlb_l2.cpp | 7 +- sim/simx/mem/tlb_l2.h | 6 +- sim/simx/mem/tlb_types.h | 9 +- sw/common/vm_types.h | 6 + sw/runtime/common/buffer.cpp | 27 ++ sw/runtime/common/device.cpp | 67 ++++ sw/runtime/common/vm.cpp | 81 +++++ sw/runtime/common/vm.h | 17 + sw/runtime/common/vortex2_internal.h | 8 + sw/runtime/include/vortex2.h | 23 ++ tests/regression/vm_sparse/Makefile | 16 + tests/regression/vm_sparse/common.h | 20 ++ tests/regression/vm_sparse/kernel.cpp | 25 ++ tests/regression/vm_sparse/main.cpp | 395 +++++++++++++++++++++++ tests/regression/vm_test/main.cpp | 2 +- 32 files changed, 998 insertions(+), 118 deletions(-) create mode 100644 tests/regression/vm_sparse/Makefile create mode 100644 tests/regression/vm_sparse/common.h create mode 100644 tests/regression/vm_sparse/kernel.cpp create mode 100644 tests/regression/vm_sparse/main.cpp diff --git a/VX_types.toml b/VX_types.toml index 35be7531f4..76111bdb07 100644 --- a/VX_types.toml +++ b/VX_types.toml @@ -78,6 +78,9 @@ VX_VM_PT_LEVEL = "expr: 3 if ($XLEN == 64) else 2" VX_VM_PTE_SIZE = "expr: 8 if ($XLEN == 64) else 4" VX_VM_PT_SIZE = "expr: $VX_VM_PAGE_SIZE" VX_VM_PT_SIZE_LIMIT = "expr: (1 << 25) if ($XLEN == 64) else (1 << 23)" +# A leaf PTE with this RSW bit set is a null translation: the page is reserved +# but unbound, so reads return 0 and writes are discarded (sparse residency). +VX_VM_PTE_SPARSE_BIT = 8 [dcr_base] VX_DCR_BASE_STATE_BEGIN = 0x000 diff --git a/ci/testcases/vm.yaml b/ci/testcases/vm.yaml index 561a6192f5..20be63b200 100644 --- a/ci/testcases/vm.yaml +++ b/ci/testcases/vm.yaml @@ -284,6 +284,17 @@ tests: target: run-{driver} vars: OPTS: -t0 +# Sparse reservations (VX_MEM_SPARSE): unbound pages read 0 and discard stores +# and atomics without a fault, bound pages reach the memory behind them, two +# pages may map one, and a rebind holds for the next launch and the CP's copies. +- id: vm-sparse + via: make-run + drivers: + - simx + - rtlsim + dir: tests/regression/vm_sparse + target: run-{driver} + configs+: -DVX_CFG_EXT_A_ENABLE # vm-fault-perm (-t1, read-only-store permission fault) needs L1 permission-fault # reporting, which is not currently implemented; only structural faults (-t0, # above) are reported, via the shared walker. Re-enable when L1 permission-fault @@ -364,6 +375,12 @@ tests: via: blackbox app: vecadd args: -n16384 +- id: parity-vm-sparse + check: model_parity + via: blackbox + app: vm_sparse + configs+: -DVX_CFG_EXT_A_ENABLE + # A Kepler SMX's core (keplertitan profile): 16 warps behind each of four fetch # slices and four 8-lane LSU blocks keep the kernel's code and argument pages # busy on every MMU lane, so once a page fills its accesses must hit the TLB diff --git a/docs/assets/img/vm_tlb_l2_uarch.svg b/docs/assets/img/vm_tlb_l2_uarch.svg index 6d7b0569dc..3b0c096146 100644 --- a/docs/assets/img/vm_tlb_l2_uarch.svg +++ b/docs/assets/img/vm_tlb_l2_uarch.svg @@ -78,7 +78,8 @@ MSHR_SIZE entries · 4 tokens token = client id VPN dedup - alloc → issue → fill → drain + alloc → issue → fill → drain + per-slot valid/MRU row copy → victim Install diff --git a/docs/designs/virtual_memory_subsystem.md b/docs/designs/virtual_memory_subsystem.md index ce39069db7..2a9c083027 100644 --- a/docs/designs/virtual_memory_subsystem.md +++ b/docs/designs/virtual_memory_subsystem.md @@ -145,7 +145,30 @@ The runtime sets `V|R|X|U|A|D` on every leaf and adds `W` for `VX_MEM_WRITE` buffers; `A`/`D` are pre-set because the device never writes them back. -### 2.4 What is translated, and what is not +### 2.4 Null translations (sparse residency) + +A leaf PTE whose RSW bit 8 is set (`VX_VM_PTE_SPARSE_BIT`, Sv32 and Sv39 +alike) is a **null translation**: the page belongs to a sparse reservation but +nothing is bound behind it. Its PPN is ignored. The flags every TLB level keeps +are therefore nine bits, `{N, D, A, G, U, X, W, R, V}` (`TLB_FLAGS_WIDTH`). + +- The walker returns a null leaf like any leaf; it is not a fault. +- The cluster TLB caches it like any translation. +- The L1 stage never installs it. The requests parked on the walk drain as + replays, and a replay of a null translation that passes its permission check + takes the kill teardown with no fault report: a load or an atomic is answered + with zeroed data, a store retires. The hit path is unchanged; each access to + an unbound page pays a cluster-TLB round trip instead. +- The emulation CP's copies translate page by page; a null page reads 0 and + drops writes. + +The runtime builds sparse reservations from these +(`VX_MEM_SPARSE`, `vx_buffer_bind`, §8.4). A bind rewrites base-page PTEs and +commits `SATP_HI` behind them on the command processor, which flushes every TLB +level before any later launch. Several reservation pages may map one physical +page. + +### 2.5 What is translated, and what is not `VX_mmu` bypasses translation for a request when `¬vm_active ∨ attr[FLUSH] ∨ attr[IO] ∨ attr[OM]`: BARE mode (satp not yet @@ -202,7 +225,7 @@ storage be reused by the cluster TLB's megapage side array. ### 3.3 The hit path -With `REQ_SKID` (the socket's dMMU and iMMU), each lane takes its requests +With `REQ_SKID` (the socket's dMMU and iMMU, and the cluster unit MMU `cmmu`), each lane takes its requests through a zero-latency skid register (`VX_bypass_buffer`): the lane's accept follows the lookup of the offered request, and the skid keeps that cone out of the client's output register by presenting a registered ready. An empty skid @@ -371,9 +394,12 @@ differences: entry that filled and freed while the park was staged still matches: it is re-armed as filled and replays from its kept translation (`retired_r`), so the staged park neither walks the page again nor installs it twice. -- **`WRITE_ENABLE = 0`.** Its clients only read, so a parked request keeps - `{rw, addr, attr, tag}` and the replay restores zero data and all byte - enables; the miss-station payload is a line's address, not a line. +- **`WRITE_ENABLE` follows the RTU.** The tcache and the DXA only read; the + rtcache writes a trace's spill record (write-through). With the RTU built a + parked request keeps `{data, byteen}` in the miss station's pool and in the + park stage; without it a parked request keeps `{rw, addr, attr, tag}` and + the replay restores zero data and all byte enables, and a read-only MMU + asserts that it never parks a write. - **The unit caches are virtually indexed and tagged**, since translation happens after them. They are invalidated whenever translation changes: the socket snoop's `SATP_HI` flush (§8.2) also flushes the unit MMU's TLB and, @@ -382,8 +408,8 @@ differences: graphics flush), held until both caches report done. The two legs are independent: a cache flush waits for its outstanding misses, which may need a unit-TLB park, and a TLB under flush refuses parks, so holding the TLB - flush for a cache's walk could deadlock. Both caches are read-only, so the - flush only invalidates. + flush for a cache's walk could deadlock. The tcache is read-only and the rtcache + write-through, so the flush only invalidates. A single address space has no synonyms, so a VIVT read-only cache flushed on every `satp` change is exact. @@ -403,15 +429,18 @@ Raster and OM live in the cluster (`VX_graphics`) and reach the L2 directly through the rcache and the ocache, past every socket. Under VM a fourth `VX_mmu`, `cmmu` ([`VX_cluster.sv`](../../hw/rtl/VX_cluster.sv)), sits between those caches' memory ports and their L2 client slots (`L2_GFX_RASTER_IDX`, -`L2_GFX_OM_IDX`), one lane each (`CMMU_RCACHE_IDX`, `CMMU_OCACHE_IDX`), with +`L2_GFX_OM_IDX`), one lane each (`CMMU_RCACHE_IDX`, `CMMU_OCACHE_IDX`), plus the +geometry front end's port (`CMMU_GEOM_IDX`) under GEOM, with the same registered reply (`RSP_OUT_BUF = 2`) and registered park -(`PARK_REG = 1`) as the socket unit MMU; the rcache and ocache register their +(`PARK_REG = 1`) as the socket unit MMU, and the request skid (`REQ_SKID`, +§3.3) of the dMMU and iMMU, so the TLB lookup stays off the upstream +arbiters' enables; the rcache and ocache register their memory requests (`MEM_OUT_BUF`). Its TLB is `VX_CFG_CTLB_SIZE` (8) entries, and its misses enter the cluster TLB arbiter as one more client after the sockets (`CLUSTER_NUM_TLB_PORTS`), its slot id -zero-extended to the socket buses' width. `WRITE_ENABLE` follows OM, since the -ocache writes (write-through) through it, so its park stage holds a full -line. `vm_active` comes from the device's +zero-extended to the socket buses' width. `WRITE_ENABLE` follows OM or GEOM, +since the ocache (write-through) and the geometry front end's record writes +pass through it, so its park stage holds a full line. `vm_active` comes from the device's `satp` mode, fanned to the clusters from [`Vortex.sv`](../../hw/rtl/Vortex.sv). The rcache and ocache are virtually tagged, so the device's `SATP_HI` flush @@ -484,6 +513,10 @@ one-request-per-cycle lookup engine in front of the walker: misses on one VPN from any sockets share one walk (`DEDUP_LIVE_EXCLUDES_FAULT = 0` here: joiners share a faulted result, since each requester kills its own accesses). The issue side is `ptw_if.req {id = slot, access, amo, vpn}`. + Each slot keeps a registered copy of its set's `{valid, mru}` row, updated + by the same fill and hit writes as the arrays (a free slot follows the pipe + head's set; asserted equal at every fill), so a fill picks its victim from + the copy its walk id selects, not through the id → VPN → set-row select. - **Response arbitration.** Pipe-head hits and miss-station drains share the single client response port through a `VX_stream_arb` (`OUT_BUF = 2`). - **Update order.** A fill and a same-set hit in one cycle resolve @@ -679,12 +712,18 @@ DCRs. Then: ~1024 (Sv32) PTEs, the host-shadow / batched-update pattern of mainstream GPU drivers. `init()` reserves the PT region in the PA allocator so no later allocation can overlap it, allocates the root, and installs the identity - maps of §2.4. + maps of §2.5. - **Freeing** a buffer mapped at a minted VA clears its PTEs, forgets its pages' VAs and returns the VA range, so a later buffer on the same physical pages gets fresh VAs and no translation outlives its pages. The free then commits satp again (`commit_mmu_satp()`), queued behind its PTE writes, which flushes every TLB level before any later launch. +- **Sparse reservations.** `vx_buffer_create(VX_MEM_SPARSE)` takes VAs only, + each page a null translation (§2.4). `vx_buffer_bind` checks every page, + then points reservation pages at another buffer's pages, or back to null, + and commits satp behind its PTE writes; it is ordered on the command + processor, not on a queue. Freeing the memory behind bound pages makes them + null again; releasing the reservation clears its PTEs. - **`vx_mem_alloc`** takes a PA from the global pool, mints a VA (identity by default; `VORTEX_RANDOMIZE_VA=1` picks a random page-aligned base seeded by `VORTEX_VA_SEED`, keeping multi-page buffers VA-contiguous @@ -704,14 +743,17 @@ DCRs. Then: ### 8.5 The command processor Both command processors are MMU-aware: the emulation CP -([`cmd_processor.cpp`](../../sim/common/cmd_processor.cpp), `cp_translate()`) -and the RTL DMA ([`VX_cp_dma.sv`](../../hw/rtl/cp/VX_cp_dma.sv), the -`S_XLATE_*` states) perform the same Sv32/Sv39 walk as -`VMManager::page_table_walk` against device memory for every `CMD_MEM_*` VA -operand, skipped by `F_MEM_PHYSICAL`. Their root is `CP_SATP_LO/HI` (regfile -0x028/0x02C), programmed at open, and both advertise `DEV_CAPS.VM_ENABLED` -in a VM build, so VM runs the same on simulators and FPGA -([`command_processor.md`](command_processor.md) §8). +([`cmd_processor.cpp`](../../sim/common/cmd_processor.cpp), +`cp_translate_page()`) and the RTL DMA +([`VX_cp_dma.sv`](../../hw/rtl/cp/VX_cp_dma.sv), the `S_XLATE_*` states) +perform the same Sv32/Sv39 walk as `VMManager::page_table_walk` against device +memory for every `CMD_MEM_*` VA operand, skipped by `F_MEM_PHYSICAL`. The +emulation CP walks page by page, and also for the descriptors and arguments it +reads itself (`cp_dev_read`: QMD, indirect-launch header, record and +predicate, draw descriptor); a null translation reads 0 and drops writes. +Their root is `CP_SATP_LO/HI` (regfile 0x028/0x02C), programmed at open, and +both advertise `DEV_CAPS.VM_ENABLED` in a VM build, so VM runs the same on +simulators and FPGA ([`command_processor.md`](command_processor.md) §8). --- @@ -857,7 +899,8 @@ sizes must be powers of two ≥ 2 (static asserts). | `vm-stress` | `vm_stress` | paged and `VX_MEM_PHYS` identity translations contending | | `tlb-concurrent`, `mc-l2-amo`, `mc-l3` | 2–4 cores, L2 / L3 | shared cluster TLB and walker across cores and cache levels | | `vm-fault` | `vm_fault -t0` | unmapped page → device error and first-fault report | -| `parity-vm-sgemm/vecadd` | `check: model_parity` | exact instret + cycles within tolerance, simx vs rtlsim | +| `vm-sparse` | `vm_sparse`, `EXT_A` | null translations: unbound pages read 0 and drop stores and atomics, rebinds, two pages on one, CP copies | +| `parity-vm-sgemm/vecadd/sparse` | `check: model_parity` | exact instret + cycles within tolerance, simx vs rtlsim | | `vm-rtu` | `rt_smoke`, `EXT_RTU`, randomized VA | rtcache misses through the socket unit MMU | | `vm-dxa` | `sgemm2_dxa`, `EXT_DXA`, randomized VA | DXA gmem reads through the socket unit MMU | | `parity-vm-rt_raycast`, `parity-vm-dxa_copy` | `check: model_parity`, RTU + DXA | unit-MMU timing, simx vs rtlsim | @@ -897,7 +940,8 @@ Grades: ✅ done · ⚠️ partial · ❌ pending. | Structural fault kill + first-fault DCR report | ✅ | walker faults only | | Single DCR translation root, flush done-tree, socket snoop | ✅ | `csrw satp` is a mirror | | Host-shadowed page tables, batched PT flush, randomized VA | ✅ | `VMManager` | -| Emulation CP MMU-aware DMA | ✅ | `cp_translate` | +| Emulation CP MMU-aware DMA | ✅ | `cp_translate_page`, per page | +| Null translations for sparse reservations | ✅ | RTL + SimX + CP; `VX_MEM_SPARSE`, `vx_buffer_bind` | | **L1 permission-fault report** | ⚠️ | detected and killed in RTL, not surfaced to the host; SimX reports it. `vm_fault -t1` waits on this | | **RTL MMU perf counters** | ⚠️ | computed at the socket, not routed through `sysmem_perf`; MPM reads zero on rtlsim / FPGA | | **SimX L1 placement** | ⚠️ | per core, vs per socket in RTL — identical only at `SOCKET_SIZE = 1` | diff --git a/hw/rtl/vm/VX_mmu.sv b/hw/rtl/vm/VX_mmu.sv index 78a875fe8c..ec6b89e28e 100644 --- a/hw/rtl/vm/VX_mmu.sv +++ b/hw/rtl/vm/VX_mmu.sv @@ -448,15 +448,21 @@ module VX_mmu import VX_gpu_pkg::*, VX_tlb_pkg::*; #( wire replay_amo = replay_rattr[MEM_ATTR_AMO_OFFS]; wire replay_perm = tlb_perm_ok(replay_flags, replay_acc, replay_amo); - wire replay_push = replay_valid && replay_perm; // forwards into a lane + // A null translation (an unbound sparse page) is never installed at this + // level, so it reaches the lanes only as a replay: it is torn down like a + // fault, without the report. + wire replay_null = replay_flags[TLB_FLAG_N]; + wire replay_push = replay_valid && replay_perm && !replay_null; // forwards into a lane wire replay_drop = replay_valid && !replay_perm; // permission fault + wire replay_void = replay_valid && replay_perm && replay_null; // Kill teardown: a faulting access — a structural fault drained from the // miss station (kill_valid) or a permission fault caught re-checking a - // replay (replay_drop) — still owes the pipeline a response. A data-side - // load or atomic is answered with zeroed data; a plain store and every - // fetch retire silently. `kill_*` reuse the replay decode. - wire kill_any = kill_valid || replay_drop; + // replay (replay_drop) — or an access to an unbound page (replay_void) + // still owes the pipeline a response. A data-side load or atomic is + // answered with zeroed data; a plain store and every fetch retire + // silently. `kill_*` reuse the replay decode. + wire kill_any = kill_valid || replay_drop || replay_void; wire [TAG_WIDTH-1:0] kill_tag = replay_fields[F_TAG_LO +: TAG_WIDTH]; wire kill_needs_rsp = (EXEC_SIDE == 0) && (!replay_rw || replay_amo); wire [NUM_REQS-1:0] kill_to_lane; @@ -576,7 +582,7 @@ module VX_mmu import VX_gpu_pkg::*, VX_tlb_pkg::*; #( assign mem_bus_if[l].rsp_ready = req_if[l].rsp_ready && ~inj_rsp; end - assign replay_ready = replay_valid && (replay_perm ? pipe_ready[replay_lane] : kill_ready); + assign replay_ready = replay_valid && (replay_push ? pipe_ready[replay_lane] : kill_ready); // --------------------------------------------------------------------- // Per-lane parked count. A flush token bypasses translation, so it would diff --git a/hw/rtl/vm/VX_tlb_l1.sv b/hw/rtl/vm/VX_tlb_l1.sv index 7ca3d4150d..e8a5dd4c71 100644 --- a/hw/rtl/vm/VX_tlb_l1.sv +++ b/hw/rtl/vm/VX_tlb_l1.sv @@ -103,7 +103,7 @@ module VX_tlb_l1 import VX_gpu_pkg::*, VX_tlb_pkg::*; #( `UNUSED_PIN (lookup_ppn_raw), `UNUSED_PIN (lookup_level), .access_hit (access_hit), - .install_valid (install_valid), + .install_valid (install_valid && !install_entry.flags[TLB_FLAG_N]), .install_entry (install_entry), .install_evict (install_evict), .flush (flush) @@ -157,6 +157,7 @@ module VX_tlb_l1 import VX_gpu_pkg::*, VX_tlb_pkg::*; #( .alloc_lane (park_lane), .alloc_qdata (park_payload), .alloc_ready (park_ready), + `UNUSED_PIN (slot_valid), .issue_valid (tlb_bus_if.req_valid), .issue_slot (tlb_req_id), .issue_access (tlb_req_access), diff --git a/hw/rtl/vm/VX_tlb_l2.sv b/hw/rtl/vm/VX_tlb_l2.sv index cd052fca09..e3a36a705b 100644 --- a/hw/rtl/vm/VX_tlb_l2.sv +++ b/hw/rtl/vm/VX_tlb_l2.sv @@ -157,9 +157,20 @@ module VX_tlb_l2 import VX_gpu_pkg::*, VX_tlb_pkg::*; #( wire [TAG_BITS-1:0] fill_tag = install_entry.vpn[TLB_VPN_WIDTH-1:SET_SEL_BITS]; wire set_fill = install_valid && ~install_is_mega; + // Each miss-station slot keeps a registered copy of its set's {valid, mru} + // row, updated by the same fill and hit writes the arrays take, so it + // always equals the arrays' row (asserted at every fill). The fill's + // victim reads its slot's copy, a select of flops by the walk's id, not + // the id -> VPN -> set-row mux chain. + wire [MSHR_SIZE-1:0] mshr_slot_valid; + reg [SET_SEL_BITS-1:0] slot_set_r [MSHR_SIZE]; + reg [NUM_WAYS-1:0] slot_valid_r [MSHR_SIZE]; + reg [NUM_WAYS-1:0] slot_mru_r [MSHR_SIZE]; + wire [`UP(SLOT_W)-1:0] fill_slot_idx = `UP(SLOT_W)'(ptw_if.rsp_data.id); + // Victim within the fill's set: first invalid, else first non-MRU, else 0. - wire [NUM_WAYS-1:0] fill_valid = set_valid_r[fill_set]; - wire [NUM_WAYS-1:0] fill_mru = set_mru_r[fill_set]; + wire [NUM_WAYS-1:0] fill_valid = slot_valid_r[fill_slot_idx]; + wire [NUM_WAYS-1:0] fill_mru = slot_mru_r[fill_slot_idx]; wire has_invalid = (| (~fill_valid)); wire has_non_mru = (| (fill_valid & ~fill_mru)); reg [WAY_W-1:0] victim_way; @@ -286,6 +297,7 @@ module VX_tlb_l2 import VX_gpu_pkg::*, VX_tlb_pkg::*; #( .alloc_lane (alloc_lane), .alloc_qdata (t_id), .alloc_ready (alloc_ready), + .slot_valid (mshr_slot_valid), .issue_valid (ptw_if.req_valid), .issue_slot (ptw_req_slot), .issue_access (ptw_req_acc), @@ -402,6 +414,37 @@ module VX_tlb_l2 import VX_gpu_pkg::*, VX_tlb_pkg::*; #( end end + // The slots' row copies take the same updates (see fill_valid). A free + // slot follows the pipe head's set: an allocation takes a free slot and + // gives it the head's VPN (alloc_vpn = t_vpn) at this edge, so the copy + // is right from its first cycle, without the allocate's match logic. + wire [NUM_WAYS-1:0] victim_oh = NUM_WAYS'(1) << victim_way; + wire [NUM_WAYS-1:0] hit_oh = NUM_WAYS'(1) << hit_way; + for (genvar e = 0; e < MSHR_SIZE; ++e) begin : g_slot_row + wire load = ~mshr_slot_valid[e]; + wire [SET_SEL_BITS-1:0] row_set = load ? t_set : slot_set_r[e]; + wire [NUM_WAYS-1:0] row_vld = load ? set_valid_r[t_set] : slot_valid_r[e]; + wire [NUM_WAYS-1:0] row_mru = load ? set_mru_r[t_set] : slot_mru_r[e]; + wire fill_hit = set_fill && (fill_set == row_set); + wire bump_hit = set_hit_fire && (t_set == row_set); + always @(posedge clk) begin + if (reset || flush_clear) begin + slot_valid_r[e] <= '0; + slot_mru_r[e] <= '0; + end else begin + slot_valid_r[e] <= row_vld | (fill_hit ? victim_oh : '0); + slot_mru_r[e] <= ((fill_hit && all_mru_fill) ? '0 : row_mru) + | (fill_hit ? victim_oh : '0) + | (bump_hit ? hit_oh : '0); + end + slot_set_r[e] <= row_set; + end + end + `RUNTIME_ASSERT (~set_fill || ((slot_set_r[fill_slot_idx] == fill_set) + && (fill_valid == set_valid_r[fill_set]) + && (fill_mru == set_mru_r[fill_set])), + ("%t: L2 TLB slot row copy out of sync (slot=%0d, set=%0d)", $time, fill_slot_idx, fill_set)) + // --------------------------------------------------------------------- // Drain / flush // --------------------------------------------------------------------- diff --git a/hw/rtl/vm/VX_tlb_mshr.sv b/hw/rtl/vm/VX_tlb_mshr.sv index bcabeded7a..97d609cb4e 100644 --- a/hw/rtl/vm/VX_tlb_mshr.sv +++ b/hw/rtl/vm/VX_tlb_mshr.sv @@ -64,6 +64,8 @@ module VX_tlb_mshr import VX_tlb_pkg::*; #( input wire [`UP(`CLOG2(NUM_REQS))-1:0] alloc_lane, input wire [QDATA_W-1:0] alloc_qdata, output wire alloc_ready, + // Occupied slots (registered); an allocation takes a free one at its edge. + output wire [MSHR_SIZE-1:0] slot_valid, // Walk issue. output wire issue_valid, @@ -229,6 +231,7 @@ module VX_tlb_mshr import VX_tlb_pkg::*; #( // --------------------------------------------------------------------- assign alloc_ready = !flush && (has_match ? !q_full[match_slot] : has_free); wire alloc_fire = alloc_valid && alloc_ready; + assign slot_valid = valid_r; // --------------------------------------------------------------------- // Issue diff --git a/hw/rtl/vm/VX_tlb_pkg.sv b/hw/rtl/vm/VX_tlb_pkg.sv index bc9aa17da4..88ed201c67 100644 --- a/hw/rtl/vm/VX_tlb_pkg.sv +++ b/hw/rtl/vm/VX_tlb_pkg.sv @@ -25,7 +25,7 @@ package VX_tlb_pkg; localparam TLB_LEVEL_BITS = `CLOG2(`VX_VM_PT_SIZE / `VX_VM_PTE_SIZE); localparam TLB_VPN_WIDTH = TLB_PT_LEVELS * TLB_LEVEL_BITS; localparam TLB_PPN_WIDTH = `VX_CFG_MEM_ADDR_WIDTH - `VX_VM_PAGE_LOG2_SIZE; - localparam TLB_FLAGS_WIDTH = 8; + localparam TLB_FLAGS_WIDTH = `VX_VM_PTE_SPARSE_BIT + 1; // Page-level index: 0 = base page, N = superpage spanning N index groups. localparam TLB_LEVEL_WIDTH = `UP(`CLOG2(TLB_PT_LEVELS)); @@ -44,12 +44,14 @@ package VX_tlb_pkg; logic [TLB_FLAGS_WIDTH-1:0] flags; } tlb_entry_t; - // PTE flag bit positions: {D,A,G,U,X,W,R,V} = flags[7:0]. V is checked only by - // the PTW walker (VX_ptw_walker), which is elaborated only when VM is enabled; - // entry validity is tracked separately here, so waive the unused-param lint when - // the package is compiled with the walker excluded. + // PTE flag bit positions: {N,D,A,G,U,X,W,R,V} = flags[8:0], N the RSW bit + // marking a null translation (an unbound sparse page). V is checked only by + // the PTW walker (VX_ptw_walker) and N only by the MMU and the L1 TLB, all + // elaborated only when VM is enabled; entry validity is tracked separately + // here, so waive the unused-param lint when the package is compiled without VM. /* verilator lint_off UNUSEDPARAM */ localparam TLB_FLAG_V = 0; + localparam TLB_FLAG_N = `VX_VM_PTE_SPARSE_BIT; /* verilator lint_on UNUSEDPARAM */ localparam TLB_FLAG_R = 1; localparam TLB_FLAG_W = 2; diff --git a/hw/unittest/mmu_park/VX_mmu_park_top.sv b/hw/unittest/mmu_park/VX_mmu_park_top.sv index d6ffc6ba4e..53f7bcc00f 100644 --- a/hw/unittest/mmu_park/VX_mmu_park_top.sv +++ b/hw/unittest/mmu_park/VX_mmu_park_top.sv @@ -45,7 +45,8 @@ module VX_mmu_park_top import VX_gpu_pkg::*, VX_tlb_pkg::*; ( .data_out (walk.rsp_data.id) ); assign walk.rsp_data.ppn = '0; - assign walk.rsp_data.flags = 8'h13; // user-readable leaf + // user-readable leaf (V|R|U), not a sparse page: TLB_FLAG_N clear + assign walk.rsp_data.flags = TLB_FLAGS_WIDTH'(8'h13); assign walk.rsp_data.level = '0; assign walk.rsp_data.fault = 1'b0; assign flush.req = 1'b0; diff --git a/sim/common/cmd_processor.cpp b/sim/common/cmd_processor.cpp index 200b7904eb..dd19406b06 100644 --- a/sim/common/cmd_processor.cpp +++ b/sim/common/cmd_processor.cpp @@ -8,6 +8,7 @@ #include #include +#include #include namespace vortex { @@ -171,13 +172,22 @@ uint32_t CommandProcessor::mmio_read(uint32_t off) const { // VM — page-table walk (the CP DMA is an MMU-aware copy engine) // ============================================================================ -uint64_t CommandProcessor::cp_translate(uint64_t vaddr, bool physical) const { +bool CommandProcessor::cp_paged(bool physical) const { #ifdef VX_CFG_VM_ENABLE - if (physical || satp_ == 0) - return vaddr; + return !physical && satp_ != 0 && SATP_t(satp_).get_mode() != BARE; +#else + (void)physical; + return false; +#endif +} + +bool CommandProcessor::cp_translate_page(uint64_t vaddr, bool physical, uint64_t* paddr) const { + *paddr = vaddr; +#ifdef VX_CFG_VM_ENABLE + if (!cp_paged(physical)) { + return true; + } SATP_t satp(satp_); - if (satp.get_mode() == BARE) - return vaddr; // Sv32/Sv39 walk — mirrors VMManager::page_table_walk so the CP DMA and // the host driver resolve addresses identically. int i = VX_VM_PT_LEVEL - 1; @@ -187,17 +197,23 @@ uint64_t CommandProcessor::cp_translate(uint64_t vaddr, bool physical) const { uint64_t pte_addr = cur_base_ppn * VX_VM_PT_SIZE + va.vpn[i] * VX_VM_PTE_SIZE; uint64_t pte_bytes = 0; - if (hooks_.dram_read) + if (hooks_.dram_read) { hooks_.dram_read(pte_addr, &pte_bytes, VX_VM_PTE_SIZE); + } PTE_t pte(pte_bytes); - if (pte.v == 0) - return vaddr; // unmapped — pass through (defensive) + if (pte.v == 0) { + return true; // unmapped — pass through (defensive) + } if (pte.r == 0 && pte.w == 0 && pte.x == 0) { - if (--i < 0) - return vaddr; // no leaf — pass through + if (--i < 0) { + return true; // no leaf — pass through + } cur_base_ppn = pte.ppn; continue; } + if ((pte.tlb_flags() >> VX_VM_PTE_SPARSE_BIT) & 1) { + return false; // null translation + } cur_base_ppn = pte.ppn; // leaf found at level i break; } @@ -209,14 +225,80 @@ uint64_t CommandProcessor::cp_translate(uint64_t vaddr, bool physical) const { constexpr unsigned VPN_BITS = cp_clog2(VX_VM_PT_SIZE / VX_VM_PTE_SIZE); const uint64_t off_mask = (uint64_t(1) << (VX_VM_PAGE_LOG2_SIZE + i * VPN_BITS)) - 1; - return ((cur_base_ppn << VX_VM_PAGE_LOG2_SIZE) & ~off_mask) - | (vaddr & off_mask); + *paddr = ((cur_base_ppn << VX_VM_PAGE_LOG2_SIZE) & ~off_mask) + | (vaddr & off_mask); + return true; #else (void)physical; - return vaddr; + return true; #endif } +void CommandProcessor::cp_dev_read(uint64_t vaddr, void* dst, uint64_t size) const { + constexpr uint64_t PAGE = uint64_t(1) << VX_VM_PAGE_LOG2_SIZE; + auto out = static_cast(dst); + const bool paged = cp_paged(false); + for (uint64_t done = 0; done < size; ) { + uint64_t n = size - done; + if (paged) { + n = std::min(n, PAGE - ((vaddr + done) & (PAGE - 1))); + } + uint64_t pa = 0; + if (cp_translate_page(vaddr + done, false, &pa)) { + hooks_.dram_read(pa, out + done, n); + } else { + std::fill(out + done, out + done + n, 0); + } + done += n; + } +} + +void CommandProcessor::cp_mem_copy(uint64_t dst, bool dst_dev, uint64_t src, bool src_dev, + uint64_t size, bool physical) { + constexpr uint64_t CHUNK = 64 * 1024; + constexpr uint64_t PAGE = uint64_t(1) << VX_VM_PAGE_LOG2_SIZE; + std::vector buf(std::size_t(size < CHUNK ? size : CHUNK)); + const bool paged = cp_paged(physical); + const bool no_alloc = hooks_.dma_no_alloc_min != 0 && size >= hooks_.dma_no_alloc_min; + for (uint64_t done = 0; done < size; ) { + uint64_t n = std::min(size - done, CHUNK); + uint64_t dpa = dst + done; + uint64_t spa = src + done; + bool dst_bound = true; + bool src_bound = true; + // A translated operand is contiguous only to the end of its page. + if (dst_dev) { + dst_bound = cp_translate_page(dst + done, physical, &dpa); + if (paged) { + n = std::min(n, PAGE - ((dst + done) & (PAGE - 1))); + } + } + if (src_dev) { + src_bound = cp_translate_page(src + done, physical, &spa); + if (paged) { + n = std::min(n, PAGE - ((src + done) & (PAGE - 1))); + } + } + if (!src_dev) { + this->host_read_(spa, buf.data(), n); + } else if (src_bound) { + hooks_.dram_read(spa, buf.data(), n); + } else { + std::fill(buf.begin(), buf.begin() + n, 0); + } + if (!dst_dev) { + this->host_write_(dpa, buf.data(), n); + } else if (dst_bound) { + if (hooks_.dma_write) { + hooks_.dma_write(dpa, buf.data(), n, no_alloc); + } else { + hooks_.dram_write(dpa, buf.data(), n); + } + } + done += n; + } +} + // ============================================================================ // Fetch + unpack // ============================================================================ @@ -340,15 +422,15 @@ bool CommandProcessor::event_wait_satisfied_() { // staged it at (VM walk when active, passthrough otherwise). void CommandProcessor::apply_qmd_(uint64_t qmd_addr) { if (!hooks_.dram_read || !hooks_.vortex_dcr_write) return; - uint64_t addr = cp_translate(qmd_addr, /*physical=*/false); + uint64_t addr = qmd_addr; uint32_t count = 0; - hooks_.dram_read(addr, &count, sizeof(count)); + cp_dev_read(addr, &count, sizeof(count)); addr += sizeof(count); constexpr uint32_t MAX_QMD_DCRS = 64; // backstop against a corrupt count if (count > MAX_QMD_DCRS) count = MAX_QMD_DCRS; for (uint32_t i = 0; i < count; ++i) { uint32_t pair[2] = {0, 0}; // {dcr_addr, value} - hooks_.dram_read(addr, pair, sizeof(pair)); + cp_dev_read(addr, pair, sizeof(pair)); addr += sizeof(pair); hooks_.vortex_dcr_write(pair[0] & 0xFFF, pair[1]); // VX_DCR_ADDR_BITS=12 } @@ -415,9 +497,9 @@ void CommandProcessor::draw_load_step_() { draw_cmd_ = Cmd{}; if (!hooks_.dram_read) return; uint8_t buf[DRAW_STEP_BYTES] = {0}; - const uint64_t at = draw_phys_ + 4 + const uint64_t at = draw_addr_ + 4 + uint64_t(draw_step_) * DRAW_STEP_BYTES; - hooks_.dram_read(at, buf, DRAW_STEP_BYTES); + cp_dev_read(at, buf, DRAW_STEP_BYTES); decode_cmd_bytes(buf, DRAW_STEP_BYTES, 0, draw_cmd_); } @@ -506,11 +588,11 @@ void CommandProcessor::tick_engine() { // Device-orchestrated draw: arg0 → resident draw descriptor // {uint32 num_steps, steps[28 B]...}. Walk the embedded command // bundle (DrawStep), retiring the one OP_DRAW when drained. - draw_phys_ = cp_translate(cur_cmd_.arg0, /*physical=*/false); + draw_addr_ = cur_cmd_.arg0; draw_num_steps_ = 0; if (hooks_.dram_read) - hooks_.dram_read(draw_phys_, &draw_num_steps_, - sizeof(draw_num_steps_)); + cp_dev_read(draw_addr_, &draw_num_steps_, + sizeof(draw_num_steps_)); if (draw_num_steps_ > MAX_DRAW_STEPS) draw_num_steps_ = MAX_DRAW_STEPS; draw_step_ = 0; @@ -560,49 +642,16 @@ void CommandProcessor::tick_engine() { // host memory and writes device memory, MEM_READ the // reverse, MEM_COPY is device to device. The CP DMA is an // MMU-aware copy engine: a device-side operand is a virtual - // address, translated here by a page-table walk; host-side - // operands and physical-flagged commands pass through - // untranslated. A buffer is one contiguous PA allocation, so - // translating the base covers the transfer. + // address, translated here by a page-table walk, page by + // page; host-side operands and physical-flagged commands + // pass through untranslated. if (hooks_.dram_read && hooks_.dram_write && cur_cmd_.arg2 != 0) { const bool physical = (cur_cmd_.flags & MEM_FLAG_PHYSICAL) != 0; - uint64_t dst = cur_cmd_.arg0; - uint64_t src = cur_cmd_.arg1; - if (cur_cmd_.opcode == OP_MEM_WRITE) { - dst = cp_translate(dst, physical); - } else if (cur_cmd_.opcode == OP_MEM_READ) { - src = cp_translate(src, physical); - } else { // OP_MEM_COPY — both operands are device - dst = cp_translate(dst, physical); - src = cp_translate(src, physical); - } - const bool src_host = (cur_cmd_.opcode == OP_MEM_WRITE); - const bool dst_host = (cur_cmd_.opcode == OP_MEM_READ); - const uint64_t total = cur_cmd_.arg2; - const bool no_alloc = hooks_.dma_no_alloc_min != 0 - && total >= hooks_.dma_no_alloc_min; - constexpr uint64_t CHUNK = 64 * 1024; - std::vector buf( - std::size_t(total < CHUNK ? total : CHUNK)); - for (uint64_t done = 0; done < total; ) { - uint64_t n = total - done; - if (n > CHUNK) n = CHUNK; - if (src_host) { - this->host_read_(src + done, buf.data(), n); - } else { - hooks_.dram_read(src + done, buf.data(), n); - } - if (dst_host) { - this->host_write_(dst + done, buf.data(), n); - } else if (hooks_.dma_write) { - hooks_.dma_write(dst + done, buf.data(), n, no_alloc); - } else { - hooks_.dram_write(dst + done, buf.data(), n); - } - done += n; - } + cp_mem_copy(cur_cmd_.arg0, cur_cmd_.opcode != OP_MEM_READ, + cur_cmd_.arg1, cur_cmd_.opcode != OP_MEM_WRITE, + cur_cmd_.arg2, physical); } eng_state_ = EngState::Retire; } else { diff --git a/sim/common/cmd_processor.h b/sim/common/cmd_processor.h index 1802036ba5..a6d52a71c6 100644 --- a/sim/common/cmd_processor.h +++ b/sim/common/cmd_processor.h @@ -245,7 +245,7 @@ class CommandProcessor { bool cur_is_no_resource_ = false; // ----- Draw-bundle state (OP_DRAW walk) ----- - uint64_t draw_phys_ = 0; // descriptor base (translated) + uint64_t draw_addr_ = 0; // descriptor base (device VA) uint32_t draw_num_steps_ = 0; uint32_t draw_step_ = 0; Cmd draw_cmd_{}; // decoded current step @@ -296,8 +296,19 @@ class CommandProcessor { void host_read_(uint64_t addr, void* dst, std::size_t bytes); void host_write_(uint64_t addr, const void* src, std::size_t bytes); // VM: translate a device virtual address to physical via a page-table - // walk. A no-op when VM is disabled, SATP is unset/BARE, or physical. - uint64_t cp_translate(uint64_t vaddr, bool physical) const; + // walk; the identity when VM is disabled, SATP is unset/BARE, or + // physical. False for a null translation (an unbound sparse page, which + // reads 0 and drops writes). + bool cp_translate_page(uint64_t vaddr, bool physical, uint64_t* paddr) const; + // Whether device addresses are translated (VM on, SATP set, not BARE). + bool cp_paged(bool physical) const; + // Read `size` bytes at device VA `vaddr`, page by page, 0 from unbound + // pages: a descriptor or argument may cross a page of a reservation. + void cp_dev_read(uint64_t vaddr, void* dst, uint64_t size) const; + // CMD_MEM_*: copy `size` bytes, translating each device operand page by + // page, since a virtual range need not be physically contiguous. + void cp_mem_copy(uint64_t dst, bool dst_dev, uint64_t src, bool src_dev, + uint64_t size, bool physical); }; } // namespace vortex diff --git a/sim/simx/mem/mmu.cpp b/sim/simx/mem/mmu.cpp index 5689dc7443..edd95ec76e 100644 --- a/sim/simx/mem/mmu.cpp +++ b/sim/simx/mem/mmu.cpp @@ -238,6 +238,12 @@ void Mmu::replay_or_kill(uint32_t port, const MemReq& req, uint64_t ppn, << (req.addr >> VX_VM_PAGE_LOG2_SIZE) << std::dec); return; } + if (tlb_null(flags)) { + // Unbound sparse page: a load or an atomic reads 0, nothing is written, + // and nothing is reported. + kill_request(port, req); + return; + } uint64_t page_mask = (uint64_t(1) << VX_VM_PAGE_LOG2_SIZE) - 1; uint64_t low_mask = (uint64_t(1) << (level * TLB_VPN_LEVEL_BITS)) - 1; uint64_t vpn = req.addr >> VX_VM_PAGE_LOG2_SIZE; @@ -329,7 +335,9 @@ void Mmu::on_tick() { // Dropping a fill would leave its parked requests waiting forever. VX_ASSERT(id >= 0 && id < (int)mshr_.size() && mshr_[id].valid, "TLB fill does not match an outstanding miss"); - if (!rsp.fault) { + // A null translation is never cached here: its accesses are answered + // as kills, so keeping it would need a response path off the hit path. + if (!rsp.fault && !tlb_null(rsp.flags)) { tlb_.fill(mshr_[id].vpn, rsp.ppn, rsp.flags, rsp.level); } for (auto& [port, req] : mshr_[id].parked) { diff --git a/sim/simx/mem/mmu_tlb.cpp b/sim/simx/mem/mmu_tlb.cpp index 38ae29abcf..02977e92fe 100644 --- a/sim/simx/mem/mmu_tlb.cpp +++ b/sim/simx/mem/mmu_tlb.cpp @@ -42,7 +42,7 @@ Tlb::Result Tlb::lookup(uint64_t vpn) { return {}; } -void Tlb::fill(uint64_t vpn, uint64_t ppn, uint8_t flags, uint8_t level) { +void Tlb::fill(uint64_t vpn, uint64_t ppn, uint16_t flags, uint8_t level) { // Prefer an invalid slot; fall back to a non-MRU victim. If all slots // are valid AND every slot has mru=true, clear all MRU bits and evict slot 0. int victim = -1; diff --git a/sim/simx/mem/mmu_tlb.h b/sim/simx/mem/mmu_tlb.h index 6e3756e106..483e7e210b 100644 --- a/sim/simx/mem/mmu_tlb.h +++ b/sim/simx/mem/mmu_tlb.h @@ -26,7 +26,7 @@ class Tlb { bool hit = false; uint64_t ppn = 0; // 4KB-granule translation (superpage entries // splice the vpn low bits back in) - uint8_t flags = 0; + uint16_t flags = 0; uint8_t level = 0; }; @@ -37,7 +37,7 @@ class Tlb { // 1 = mega, 2 = giga); one superpage entry covers its whole range. // Evicts a non-MRU entry when the TLB is full; updates `evictions_` // if the chosen slot was previously valid. - void fill(uint64_t vpn, uint64_t ppn, uint8_t flags, uint8_t level); + void fill(uint64_t vpn, uint64_t ppn, uint16_t flags, uint8_t level); // Invalidate every entry (sfence.vma equivalent). void flush(); @@ -53,7 +53,7 @@ class Tlb { bool mru = false; uint64_t vpn = 0; uint64_t ppn = 0; // aligned down to the entry's level - uint8_t flags = 0; + uint16_t flags = 0; uint8_t level = 0; }; diff --git a/sim/simx/mem/ptw.cpp b/sim/simx/mem/ptw.cpp index 6108d6ed92..e99da6216a 100644 --- a/sim/simx/mem/ptw.cpp +++ b/sim/simx/mem/ptw.cpp @@ -106,7 +106,7 @@ void Ptw::on_pte_response(Walker& w, const MemRsp& rsp) { return; } w.final_ppn = pte.ppn; - w.flags = pte.flags; + w.flags = pte.tlb_flags(); w.leaf_level = w.level; w.state = W_FILL; return; diff --git a/sim/simx/mem/ptw.h b/sim/simx/mem/ptw.h index eeecf80b58..55e4145f22 100644 --- a/sim/simx/mem/ptw.h +++ b/sim/simx/mem/ptw.h @@ -86,7 +86,7 @@ class Ptw : public SimObject { uint64_t cur_ppn = 0; uint64_t pte_addr = 0; uint64_t final_ppn = 0; - uint8_t flags = 0; + uint16_t flags = 0; uint8_t leaf_level = 0; bool fault = false; uint64_t start_cycle = 0; diff --git a/sim/simx/mem/tlb_l2.cpp b/sim/simx/mem/tlb_l2.cpp index 0997ac65b8..d36082fe78 100644 --- a/sim/simx/mem/tlb_l2.cpp +++ b/sim/simx/mem/tlb_l2.cpp @@ -57,7 +57,7 @@ bool L2Tlb::busy() const { return false; } -bool L2Tlb::lookup(uint64_t vpn, uint64_t* ppn, uint8_t* flags, uint8_t* level) { +bool L2Tlb::lookup(uint64_t vpn, uint64_t* ppn, uint16_t* flags, uint8_t* level) { // Megapage side array first (one entry covers the whole range). { auto res = mega_.lookup(vpn); @@ -81,7 +81,7 @@ bool L2Tlb::lookup(uint64_t vpn, uint64_t* ppn, uint8_t* flags, uint8_t* level) return false; } -void L2Tlb::fill(uint64_t vpn, uint64_t ppn, uint8_t flags, uint8_t level) { +void L2Tlb::fill(uint64_t vpn, uint64_t ppn, uint16_t flags, uint8_t level) { if (level != 0) { mega_.fill(vpn, ppn, flags, level); return; @@ -166,7 +166,8 @@ void L2Tlb::on_tick() { return; } uint64_t ppn; - uint8_t flags, level; + uint16_t flags; + uint8_t level; if (lookup(req.vpn, &ppn, &flags, &level)) { ++perf_.hits; TlbRsp out; diff --git a/sim/simx/mem/tlb_l2.h b/sim/simx/mem/tlb_l2.h index 5b3ea8c14d..26819ba610 100644 --- a/sim/simx/mem/tlb_l2.h +++ b/sim/simx/mem/tlb_l2.h @@ -73,7 +73,7 @@ class L2Tlb : public SimObject { bool mru = false; uint64_t vpn = 0; uint64_t ppn = 0; - uint8_t flags = 0; + uint16_t flags = 0; }; struct MshrEntry { @@ -85,8 +85,8 @@ class L2Tlb : public SimObject { std::vector> requesters; // (client, slot) }; - bool lookup(uint64_t vpn, uint64_t* ppn, uint8_t* flags, uint8_t* level); - void fill(uint64_t vpn, uint64_t ppn, uint8_t flags, uint8_t level); + bool lookup(uint64_t vpn, uint64_t* ppn, uint16_t* flags, uint8_t* level); + void fill(uint64_t vpn, uint64_t ppn, uint16_t flags, uint8_t level); uint32_t num_clients_; uint32_t num_sets_; diff --git a/sim/simx/mem/tlb_types.h b/sim/simx/mem/tlb_types.h index 07bb486131..c16eca56ed 100644 --- a/sim/simx/mem/tlb_types.h +++ b/sim/simx/mem/tlb_types.h @@ -31,11 +31,16 @@ enum class TlbAccess : uint8_t { Exec = 2 }; +// A null translation: the page is reserved but unbound (VX_VM_PTE_SPARSE_BIT). +inline bool tlb_null(uint16_t flags) { + return (flags >> VX_VM_PTE_SPARSE_BIT) & 1; +} + // Permission test against a leaf PTE's flag bits. Kernels run in U-mode, // so U is always required; W covers stores and the write half of an AMO. // Shared by the walker and by every TLB that hands out a translation, so // the two can never disagree about what a page permits. -inline bool tlb_perm_ok(uint8_t flags, TlbAccess access, bool amo) { +inline bool tlb_perm_ok(uint16_t flags, TlbAccess access, bool amo) { const bool r = (flags & (1u << 1)) != 0; const bool w = (flags & (1u << 2)) != 0; const bool x = (flags & (1u << 3)) != 0; @@ -68,7 +73,7 @@ struct TlbReq { // Fill (or fault) response back to the requesting L1. struct TlbRsp { uint64_t ppn = 0; - uint8_t flags = 0; + uint16_t flags = 0; uint8_t level = 0; // 0 = base page, 1 = mega, 2 = giga bool fault = false; // no translation installed when set uint32_t client_id = 0; diff --git a/sw/common/vm_types.h b/sw/common/vm_types.h index 7230674cad..b50b8ce2ea 100644 --- a/sw/common/vm_types.h +++ b/sw/common/vm_types.h @@ -114,6 +114,12 @@ class PTE_t { bool d, a, g, u, x, w, r, v; uint64_t pte_bytes; + // The flags a TLB keeps: {N, D, A, G, U, X, W, R, V}, N the sparse + // null-translation bit. + uint32_t tlb_flags() const { + return (uint32_t)bits(pte_bytes, 0, VX_VM_PTE_SPARSE_BIT); + } + void set_flags(uint32_t flag) { this->flags = flag; d = bit(flags, 7); diff --git a/sw/runtime/common/buffer.cpp b/sw/runtime/common/buffer.cpp index 78c9f1805a..d96c15db80 100644 --- a/sw/runtime/common/buffer.cpp +++ b/sw/runtime/common/buffer.cpp @@ -49,6 +49,21 @@ vx_result_t Buffer::reserve(Device* dev, uint64_t address, uint64_t size, return VX_SUCCESS; } +vx_result_t Buffer::bind(uint64_t off, Buffer* mem, uint64_t mem_off, uint64_t size) { + if (!(flags_ & VX_MEM_SPARSE) || off + size > size_ || off + size < off) { + return VX_ERR_INVALID_VALUE; + } + // Only memory the page table maps by a minted VA can be bound: its + // frees unbind the pages bound to it. + const uint32_t unbindable = VX_MEM_SPARSE | VX_MEM_PHYS | VX_MEM_HOST; + if (mem && (mem->device_ != device_ || (mem->flags_ & unbindable) || + mem_off + size > mem->size_ || mem_off + size < mem_off)) { + return VX_ERR_INVALID_VALUE; + } + return device_->mem_bind(dev_addr_ + off, mem != nullptr, + mem ? mem->dev_addr_ + mem_off : 0, size); +} + vx_result_t Buffer::place(Device* dev, uint64_t hint, uint64_t size, uint32_t flags, Buffer** out) { if (!dev || !out || size == 0) { @@ -169,6 +184,18 @@ extern "C" vx_result_t vx_buffer_reserve(vx_device_h dev, uint64_t address, VX_C_ENTRY_CATCH } +extern "C" vx_result_t vx_buffer_bind(vx_buffer_h sparse, uint64_t offset, + vx_buffer_h mem, uint64_t mem_offset, + uint64_t size) { + VX_C_ENTRY_TRY + if (!sparse) { + return VX_ERR_INVALID_HANDLE; + } + return to_buffer(sparse)->bind(offset, mem ? to_buffer(mem) : nullptr, + mem_offset, size); + VX_C_ENTRY_CATCH +} + extern "C" vx_result_t vx_buffer_retain(vx_buffer_h buf) { if (!buf) return VX_ERR_INVALID_HANDLE; to_buffer(buf)->retain(); diff --git a/sw/runtime/common/device.cpp b/sw/runtime/common/device.cpp index 96bd4901d6..f9f7503db7 100644 --- a/sw/runtime/common/device.cpp +++ b/sw/runtime/common/device.cpp @@ -1140,6 +1140,21 @@ vx_result_t Device::mem_alloc(uint64_t size, uint32_t flags, // Neither the cores nor the CP's device-side DMA reach host memory, so a // host-memory buffer could serve no kernel or copy. if (flags & VX_MEM_HOST) return VX_ERR_INVALID_VALUE; + if (flags & VX_MEM_SPARSE) { + if (!vm_mgr_) { + return VX_ERR_NOT_SUPPORTED; + } + const uint64_t asize = (size + VX_VM_PAGE_SIZE - 1) & ~uint64_t(VX_VM_PAGE_SIZE - 1); + { + std::lock_guard g(vm_mu_); + if (vm_mgr_->reserve_sparse(asize, out_addr) != 0) { + return VX_ERR_OUT_OF_DEVICE_MEMORY; + } + } + std::lock_guard g(mu_); + sparse_[*out_addr] = asize; + return VX_SUCCESS; + } // Under VM the page table is the protection structure, so a page must // belong to one buffer: two sub-page allocations sharing a page can // only carry one set of PTE permissions, and the second buffer would @@ -1230,6 +1245,42 @@ vx_result_t Device::mem_reserve(uint64_t addr, uint64_t size, uint32_t flags) { return VX_SUCCESS; } +vx_result_t Device::mem_bind(uint64_t addr, bool bound, uint64_t mem_addr, + uint64_t size) { + const uint64_t page = VX_VM_PAGE_SIZE; + if (!vm_mgr_) { + return VX_ERR_NOT_SUPPORTED; + } + if ((addr | mem_addr | size) & (page - 1)) { + return VX_ERR_INVALID_VALUE; + } + std::lock_guard g(vm_mu_); + // Every page is checked before any is rewritten, so a bind either applies + // whole or leaves the page table as it was. + std::vector pas(size / page, 0); + for (uint64_t i = 0; i < pas.size(); ++i) { + if (!vm_mgr_->bindable(addr + i * page)) { + return VX_ERR_INVALID_VALUE; + } + if (bound) { + try { + pas[i] = vm_mgr_->page_table_walk(mem_addr + i * page); + } catch (...) { + return VX_ERR_INVALID_VALUE; + } + } + } + for (uint64_t i = 0; i < pas.size(); ++i) { + vm_mgr_->bind_page(addr + i * page, bound, pas[i]); + } + if (vm_mgr_->flush() != 0) { + return VX_ERR_INVALID_VALUE; + } + // The TLBs may hold the old translations: commit satp behind the PTE + // writes, which flushes every level before any later launch. + return vm_enabled_ ? commit_mmu_satp() : VX_SUCCESS; +} + vx_result_t Device::mem_place(uint64_t hint, uint64_t size, uint32_t flags, uint64_t* out_addr) { if (!out_addr || size == 0) { @@ -1259,6 +1310,22 @@ vx_result_t Device::mem_place(uint64_t hint, uint64_t size, uint32_t flags, } vx_result_t Device::mem_free(uint64_t addr) { + uint64_t sparse_size = 0; + { + std::lock_guard g(mu_); + auto it = sparse_.find(addr); + if (it != sparse_.end()) { + sparse_size = it->second; + sparse_.erase(it); + } + } + if (sparse_size != 0) { + std::lock_guard g(vm_mu_); + if (vm_mgr_->release_sparse(addr, sparse_size) != 0) { + return VX_ERR_INVALID_VALUE; + } + return vm_enabled_ ? commit_mmu_satp() : VX_SUCCESS; + } // VM: `addr` is a VA — resolve to the PA the allocator handed out. vx_result_t committed = VX_SUCCESS; if (vm_mgr_) { diff --git a/sw/runtime/common/vm.cpp b/sw/runtime/common/vm.cpp index 31a3c0db6d..748fd73ac6 100644 --- a/sw/runtime/common/vm.cpp +++ b/sw/runtime/common/vm.cpp @@ -80,6 +80,12 @@ VMManager::~VMManager() { } int VMManager::virtual_mem_reserve(uint64_t dev_addr, uint64_t size, int /*flags*/) { + // A range inside an identity-mapped region, as the OM aperture is inside + // the superpage heap, is held out of the VA space already. + for (auto [start, end] : identity_ranges_) { + if (dev_addr >= start && dev_addr + size <= end) + return 0; + } CHECK_ERR(virtual_mem_->reserve(dev_addr, size), { return err; }); @@ -373,6 +379,22 @@ int16_t VMManager::update_page_table(uint64_t ppn, uint64_t vpn, uint32_t pte_fl return 0; } +int VMManager::reserve_sparse(uint64_t size, uint64_t* va) { + const uint64_t num_pages = (size + VX_VM_PAGE_SIZE - 1) >> VX_VM_PAGE_LOG2_SIZE; + uint64_t base_va = 0; + CHECK_ERR(virtual_mem_->allocate(num_pages << VX_VM_PAGE_LOG2_SIZE, &base_va), { return -1; }); + const uint32_t null_flags = PTE_V | PTE_R | PTE_W | PTE_U | PTE_A | PTE_D | PTE_N; + for (uint64_t i = 0; i < num_pages; ++i) { + const uint64_t vpn = (base_va >> VX_VM_PAGE_LOG2_SIZE) + i; + if (update_page_table(0, vpn, null_flags) != 0) { + release_sparse(base_va, i << VX_VM_PAGE_LOG2_SIZE); + return -1; + } + } + *va = base_va; + return flush(); +} + uint64_t VMManager::leaf_pte_addr(uint64_t va) { vAddr_t vaddr(va); uint64_t base_ppn = get_base_ppn(); @@ -399,11 +421,70 @@ int VMManager::unmap(uint64_t va, uint64_t size) { addr_mapping.erase(it); } write_pte(pte_addr, 0); + // Sparse pages bound to this page lose their memory with it: unbound, + // they read 0 rather than whatever is allocated here next. + auto range = sparse_aliases_.equal_range(pte.ppn); + std::vector aliases; + for (auto a = range.first; a != range.second; ++a) { + aliases.push_back(a->second); + } + for (uint64_t vpn : aliases) { + bind_page(vpn << VX_VM_PAGE_LOG2_SIZE, false, 0); + } } virtual_mem_->release(va & ~uint64_t(VX_VM_PAGE_SIZE - 1)); return flush(); } +bool VMManager::bindable(uint64_t va) { + return leaf_pte_addr(va) != 0; +} + +void VMManager::forget_alias(uint64_t vpn) { + auto it = sparse_bound_.find(vpn); + if (it == sparse_bound_.end()) { + return; + } + auto range = sparse_aliases_.equal_range(it->second); + for (auto a = range.first; a != range.second; ++a) { + if (a->second == vpn) { + sparse_aliases_.erase(a); + break; + } + } + sparse_bound_.erase(it); +} + +int VMManager::bind_page(uint64_t va, bool bound, uint64_t pa) { + const uint64_t pte_addr = leaf_pte_addr(va); + if (pte_addr == 0) { + return -1; + } + const uint64_t vpn = va >> VX_VM_PAGE_LOG2_SIZE; + forget_alias(vpn); + const uint32_t flags = PTE_V | PTE_R | PTE_W | PTE_U | PTE_A | PTE_D | (bound ? 0u : PTE_N); + PTE_t pte(bound ? (pa & ~uint64_t(VX_VM_PAGE_SIZE - 1)) : 0, flags); + write_pte(pte_addr, pte.pte_bytes); + if (bound) { + const uint64_t ppn = pa >> VX_VM_PAGE_LOG2_SIZE; + sparse_bound_[vpn] = ppn; + sparse_aliases_.emplace(ppn, vpn); + } + return 0; +} + +int VMManager::release_sparse(uint64_t va, uint64_t size) { + for (uint64_t off = 0; off < size; off += VX_VM_PAGE_SIZE) { + forget_alias((va + off) >> VX_VM_PAGE_LOG2_SIZE); + const uint64_t pte_addr = leaf_pte_addr(va + off); + if (pte_addr != 0) { + write_pte(pte_addr, 0); + } + } + CHECK_ERR(virtual_mem_->release(va), { return -1; }); + return flush(); +} + bool VMManager::identity_map_available(uint64_t addr, uint64_t size) { for (auto [start, end] : identity_ranges_) { if (addr >= start && addr + size <= end) { diff --git a/sw/runtime/common/vm.h b/sw/runtime/common/vm.h index b55795401c..ff2331d15b 100644 --- a/sw/runtime/common/vm.h +++ b/sw/runtime/common/vm.h @@ -34,6 +34,9 @@ constexpr uint32_t PTE_X = 1u << 3; constexpr uint32_t PTE_U = 1u << 4; constexpr uint32_t PTE_A = 1u << 6; constexpr uint32_t PTE_D = 1u << 7; +// RSW bit: a null translation, the page of a sparse reservation with nothing +// bound (reads return 0, writes are discarded). +constexpr uint32_t PTE_N = 1u << VX_VM_PTE_SPARSE_BIT; // Driver-supplied raw device-memory I/O. PA-addressed bulk read/write // with no ACL semantics — VMManager batches all PT updates at PT-page @@ -97,6 +100,15 @@ class VMManager { // Undo phy_to_virt_map for a freed buffer: clear its PTEs, forget its pages' // VAs and return the VA range, so neither outlives the physical pages. int unmap(uint64_t va, uint64_t size); + // Sparse reservations: a VA range of base pages with no PA behind it, every + // page a null translation until bound. bind_page points one page at a PA, + // or back to null; several VAs may map one PA. release_sparse clears the + // range's PTEs and returns its VAs. + int reserve_sparse(uint64_t size, uint64_t* va); + // Whether `va` is a base page bind_page can rewrite. + bool bindable(uint64_t va); + int bind_page(uint64_t va, bool bound, uint64_t pa); + int release_sparse(uint64_t va, uint64_t size); // Push every dirty shadow PT page to device memory (one device write // per dirty page). Implicitly invoked at the end of init() / @@ -135,6 +147,11 @@ class VMManager { MemoryAllocator* page_table_mem_; MemoryAllocator* virtual_mem_; std::unordered_map addr_mapping; + // Bound sparse pages: reservation VPN -> PPN, and each PPN's reservation + // VPNs, so freeing the memory behind them unbinds them. + std::unordered_map sparse_bound_; + std::unordered_multimap sparse_aliases_; + void forget_alias(uint64_t vpn); // Host shadow: key = PT-page-aligned PA, value = VX_VM_PT_SIZE bytes. std::unordered_map> shadow_pt_; diff --git a/sw/runtime/common/vortex2_internal.h b/sw/runtime/common/vortex2_internal.h index 0d887b12e4..4598417550 100644 --- a/sw/runtime/common/vortex2_internal.h +++ b/sw/runtime/common/vortex2_internal.h @@ -354,6 +354,10 @@ class Device : public RefCounted { vx_result_t mem_place (uint64_t hint, uint64_t size, uint32_t flags, uint64_t* out_addr); vx_result_t mem_free (uint64_t addr); + // Point the pages of a VX_MEM_SPARSE range at the pages behind mem_addr, + // or back to unbound. + vx_result_t mem_bind (uint64_t addr, bool bound, uint64_t mem_addr, + uint64_t size); vx_result_t memory_info(uint64_t* out_free, uint64_t* out_used); // Decode a VX_CAPS_* id: the CP caps window (read via cp_reg_read + @@ -445,6 +449,9 @@ class Device : public RefCounted { std::unique_ptr pinned_mem_; uint64_t pinned_size_ = 0; uint64_t pinned_base_ = 0; + // Sparse reservations (VX_MEM_SPARSE), keyed by device address: their + // page-rounded size. + std::map sparse_; // Lazily-loaded device/ISA caps words (read once from the CP regfile). uint64_t dev_caps_ = 0; @@ -555,6 +562,7 @@ class Buffer : public RefCounted { Buffer** out); static vx_result_t reserve(Device* dev, uint64_t address, uint64_t size, uint32_t flags, Buffer** out); + vx_result_t bind(uint64_t off, Buffer* mem, uint64_t mem_off, uint64_t size); // At `hint` when that range is free, else anywhere (Device::mem_place). static vx_result_t place (Device* dev, uint64_t hint, uint64_t size, uint32_t flags, Buffer** out); diff --git a/sw/runtime/include/vortex2.h b/sw/runtime/include/vortex2.h index 4692d9258e..28a9ef07e9 100644 --- a/sw/runtime/include/vortex2.h +++ b/sw/runtime/include/vortex2.h @@ -128,6 +128,11 @@ typedef struct vx_kernel* vx_kernel_h; // which the runtime allocates itself for the command ring and DMA staging. // Neither kernels nor device copies reach it, so buffer creation rejects it. #define VX_MEM_HOST 0x10 +// A sparse reservation: device virtual addresses with no memory behind them. +// Every page reads 0 and discards writes until vx_buffer_bind maps memory +// there. Needs a device with virtual memory; others return +// VX_ERR_NOT_SUPPORTED. +#define VX_MEM_SPARSE 0x40 // ============================================================================ // Result type @@ -281,6 +286,24 @@ vx_result_t vx_buffer_reserve (vx_device_h dev, uint64_t address, uint64_t size, uint32_t flags, vx_buffer_h* out); +// Map the pages [offset, offset + size) of a VX_MEM_SPARSE buffer onto the +// pages of `mem` from mem_offset, or back to unbound when mem is NULL. Offsets +// and size are 4 KiB-aligned; several reservations may map the same memory, +// which must be a buffer mapped at a device-chosen address (not VX_MEM_PHYS or +// VX_MEM_HOST). Releasing `mem` unbinds every page bound to it. A bind applies +// whole or not at all. +// +// A bind is not a queue command: it rewrites the page table through the +// command processor before it returns. Commands the command processor has +// already executed used the old mapping; every command it executes afterwards +// uses the new one -- including copies and launches enqueued earlier that a +// queue has not handed to it yet, since copies are translated when they +// execute and the bind flushes the TLBs ahead of any later launch. To order a bind +// after work already enqueued, finish those queues (vx_queue_finish) first. +vx_result_t vx_buffer_bind (vx_buffer_h sparse, uint64_t offset, + vx_buffer_h mem, uint64_t mem_offset, + uint64_t size); + vx_result_t vx_buffer_retain (vx_buffer_h buf); vx_result_t vx_buffer_release (vx_buffer_h buf); vx_result_t vx_buffer_address (vx_buffer_h buf, uint64_t* out_addr); diff --git a/tests/regression/vm_sparse/Makefile b/tests/regression/vm_sparse/Makefile new file mode 100644 index 0000000000..b5e2a8b790 --- /dev/null +++ b/tests/regression/vm_sparse/Makefile @@ -0,0 +1,16 @@ +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +PROJECT := vm_sparse + +SRC_DIR := $(VORTEX_HOME)/tests/regression/$(PROJECT) + +SRCS := $(SRC_DIR)/main.cpp + +VX_SRCS := $(SRC_DIR)/kernel.cpp + +OPTS ?= + +KERNEL_LIB := vortex2 + +include ../common.mk diff --git a/tests/regression/vm_sparse/common.h b/tests/regression/vm_sparse/common.h new file mode 100644 index 0000000000..c8a2d4e0d6 --- /dev/null +++ b/tests/regression/vm_sparse/common.h @@ -0,0 +1,20 @@ +#ifndef _COMMON_H_ +#define _COMMON_H_ + +// Every probed page holds SLOTS slots, SLOT_STRIDE words apart, so a page's +// slots sit on different cache lines. A slot is three words: one read, one +// stored, one atomically incremented. +#define SPARSE_PAGES 16u +#define SLOTS 16u +#define SLOT_STRIDE 64u + +typedef struct { + uint64_t sparse_addr; // the reservation + uint64_t read_addr; // per-thread word read from its slot + uint64_t amo_addr; // per-thread value its atomic add returned + uint32_t tag; // stored value = tag | thread + uint32_t num_threads; // SPARSE_PAGES * SLOTS + uint64_t count_addr; // nonzero: each launched thread only counts itself here +} kernel_arg_t; + +#endif diff --git a/tests/regression/vm_sparse/kernel.cpp b/tests/regression/vm_sparse/kernel.cpp new file mode 100644 index 0000000000..4b5ec69609 --- /dev/null +++ b/tests/regression/vm_sparse/kernel.cpp @@ -0,0 +1,25 @@ +#include +#include +#include "common.h" + +#define WORDS_PER_PAGE (4096u / sizeof(uint32_t)) + +__kernel void kernel_main(kernel_arg_t* __UNIFORM__ arg) { + if (arg->count_addr) { + __atomic_fetch_add(reinterpret_cast(arg->count_addr), 1u, __ATOMIC_RELAXED); + return; + } + uint32_t tid = blockIdx.x * blockDim.x + threadIdx.x; + if (tid >= arg->num_threads) { + return; + } + auto sparse = reinterpret_cast(arg->sparse_addr); + auto reads = reinterpret_cast(arg->read_addr); + auto amos = reinterpret_cast(arg->amo_addr); + uint32_t page = tid / SLOTS; + uint32_t slot = tid % SLOTS; + uint32_t* w = sparse + page * WORDS_PER_PAGE + slot * SLOT_STRIDE; + reads[tid] = *reinterpret_cast(w); + *reinterpret_cast(w + 1) = arg->tag | tid; + amos[tid] = __atomic_fetch_add(w + 2, 1u, __ATOMIC_RELAXED); +} diff --git a/tests/regression/vm_sparse/main.cpp b/tests/regression/vm_sparse/main.cpp new file mode 100644 index 0000000000..432ff1af7e --- /dev/null +++ b/tests/regression/vm_sparse/main.cpp @@ -0,0 +1,395 @@ +#include +#include +#include +#include +#include +#include +#include "common.h" + +// A sparse reservation (VX_MEM_SPARSE) bound page by page onto two memory +// buffers. Unbound pages must read 0 and discard stores and atomics, bound +// pages must reach exactly the memory page behind them, and a rebind must be +// seen by the next launch and by the command processor's copies. + +#define PAGE_SIZE 4096u +#define WORDS_PER_PAGE (PAGE_SIZE / sizeof(uint32_t)) +#define MEM_PAGES (SPARSE_PAGES / 2) +#define NUM_THREADS (SPARSE_PAGES * SLOTS) + +#define RT_CHECK(_expr) \ + do { \ + int _ret = _expr; \ + if (0 == _ret) \ + break; \ + printf("Error: '%s' returned %d!\n", #_expr, (int)_ret); \ + cleanup(); \ + exit(-1); \ + } while (false) + +const char* kernel_file = "kernel.vxbin"; + +vx_device_h device = nullptr; +vx_queue_h queue = nullptr; +vx_module_h module_ = nullptr; +vx_kernel_h kernel = nullptr; +vx_buffer_h sparse_buffer = nullptr; +vx_buffer_h mem_buffer[2] = { nullptr, nullptr }; +vx_buffer_h read_buffer = nullptr; +vx_buffer_h amo_buffer = nullptr; + +void cleanup() { + if (device) { + for (auto b : { sparse_buffer, mem_buffer[0], mem_buffer[1], read_buffer, amo_buffer }) { + if (b) { + vx_buffer_release(b); + } + } + if (kernel) { + vx_kernel_release(kernel); + } + if (module_) { + vx_module_release(module_); + } + if (queue) { + vx_queue_release(queue); + } + vx_device_dump_perf(device, stdout); + vx_device_release(device); + } +} + +static void wait(vx_event_h ev) { + RT_CHECK(vx_event_wait_value(ev, 1, VX_TIMEOUT_INFINITE)); + vx_event_release(ev); +} + +static void write_buffer(vx_buffer_h buf, const std::vector& data) { + vx_event_h ev = nullptr; + RT_CHECK(vx_enqueue_write(queue, buf, 0, data.data(), data.size() * sizeof(uint32_t), 0, nullptr, &ev)); + wait(ev); +} + +static std::vector read_buffer_words(vx_buffer_h buf, uint32_t words) { + std::vector data(words); + vx_event_h ev = nullptr; + RT_CHECK(vx_enqueue_read(queue, data.data(), buf, 0, words * sizeof(uint32_t), 0, nullptr, &ev)); + wait(ev); + return data; +} + +// The binding of a phase: mem[p] = which memory buffer page p of the +// reservation maps (-1: unbound), at memory page page_of(p). +struct Binding { + int mem[SPARSE_PAGES]; +}; + +static uint32_t page_of(uint32_t p) { + return p / 2; +} + +static void apply(const Binding& b) { + for (uint32_t p = 0; p < SPARSE_PAGES; ++p) { + vx_buffer_h m = b.mem[p] < 0 ? nullptr : mem_buffer[b.mem[p]]; + RT_CHECK(vx_buffer_bind(sparse_buffer, uint64_t(p) * PAGE_SIZE, m, + uint64_t(page_of(p)) * PAGE_SIZE, PAGE_SIZE)); + } +} + +static uint32_t pattern(int m, uint32_t w) { + return (m == 0 ? 0xA0000000u : 0xB0000000u) | w; +} + +static void launch(uint32_t tag) { + kernel_arg_t arg = {}; + RT_CHECK(vx_buffer_address(sparse_buffer, &arg.sparse_addr)); + RT_CHECK(vx_buffer_address(read_buffer, &arg.read_addr)); + RT_CHECK(vx_buffer_address(amo_buffer, &arg.amo_addr)); + arg.tag = tag; + arg.num_threads = NUM_THREADS; + uint32_t max_bx = 1, max_by = 1, max_bz = 1; + RT_CHECK(vx_kernel_get_max_block_size(kernel, &max_bx, &max_by, &max_bz)); + uint32_t block_x = std::min(NUM_THREADS, max_bx * max_by * max_bz); + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.kernel = kernel; + li.args_host = &arg; + li.args_size = sizeof(arg); + li.ndim = 1; + li.grid_dim[0] = (NUM_THREADS + block_x - 1) / block_x; + li.block_dim[0] = block_x; + vx_event_h ev = nullptr; + RT_CHECK(vx_enqueue_launch(queue, &li, 0, nullptr, &ev)); + wait(ev); +} + +static int errors = 0; + +static void expect(const char* what, uint32_t i, uint32_t expected, uint32_t actual) { + if (expected == actual) { + return; + } + if (errors < 16) { + printf("*** error: %s[%u] expected=0x%x, actual=0x%x\n", what, i, expected, actual); + } + ++errors; +} + +// Runs one launch under `b` and checks it against `mem`, the host's copy of +// both memory buffers, which it updates with the launch's effects. +static void run_phase(const char* name, const Binding& b, uint32_t tag, + std::vector mem[2]) { + apply(b); + launch(tag); + auto reads = read_buffer_words(read_buffer, NUM_THREADS); + auto amos = read_buffer_words(amo_buffer, NUM_THREADS); + for (uint32_t t = 0; t < NUM_THREADS; ++t) { + uint32_t p = t / SLOTS; + uint32_t w = page_of(p) * WORDS_PER_PAGE + (t % SLOTS) * SLOT_STRIDE; + int m = b.mem[p]; + if (m < 0) { + expect("unbound read", t, 0u, reads[t]); + expect("unbound atomic", t, 0u, amos[t]); + continue; + } + expect("bound read", t, mem[m][w], reads[t]); + expect("bound atomic", t, mem[m][w + 2], amos[t]); + mem[m][w + 1] = tag | t; + mem[m][w + 2] += 1; + } + for (int m = 0; m < 2; ++m) { + auto data = read_buffer_words(mem_buffer[m], MEM_PAGES * WORDS_PER_PAGE); + for (uint32_t w = 0; w < data.size(); ++w) { + expect(m == 0 ? "memory A" : "memory B", w, mem[m][w], data[w]); + } + } + std::cout << name << ": " << (errors ? "errors" : "ok") << std::endl; +} + +int main() { + std::cout << "vm_sparse: " << SPARSE_PAGES << " sparse pages over two " + << MEM_PAGES << "-page buffers" << std::endl; + + RT_CHECK(vx_device_open(0, &device)); + vx_queue_info_t qi = { sizeof(qi), nullptr, VX_QUEUE_PRIORITY_NORMAL, 0 }; + RT_CHECK(vx_queue_create(device, &qi, &queue)); + + uint64_t vm_enabled = 0; + RT_CHECK(vx_device_query(device, VX_CAPS_VM_SUPPORT, &vm_enabled)); + if (0 == vm_enabled) { + // Sparse reservations are page-table mappings: without VM there are none. + std::cout << "vm_sparse: device has no VM support, skipping" << std::endl; + std::cout << "PASSED!" << std::endl; + cleanup(); + return 0; + } + + RT_CHECK(vx_buffer_create(device, SPARSE_PAGES * PAGE_SIZE, VX_MEM_READ_WRITE | VX_MEM_SPARSE, + &sparse_buffer)); + for (int m = 0; m < 2; ++m) { + RT_CHECK(vx_buffer_create(device, MEM_PAGES * PAGE_SIZE, VX_MEM_READ_WRITE, &mem_buffer[m])); + } + RT_CHECK(vx_buffer_create(device, NUM_THREADS * sizeof(uint32_t), VX_MEM_READ_WRITE, &read_buffer)); + RT_CHECK(vx_buffer_create(device, NUM_THREADS * sizeof(uint32_t), VX_MEM_READ_WRITE, &amo_buffer)); + RT_CHECK(vx_module_load_file(device, kernel_file, &module_)); + RT_CHECK(vx_module_get_kernel(module_, "main", &kernel)); + + std::vector mem[2]; + for (int m = 0; m < 2; ++m) { + mem[m].resize(MEM_PAGES * WORDS_PER_PAGE); + for (uint32_t w = 0; w < mem[m].size(); ++w) { + mem[m][w] = pattern(m, w); + } + write_buffer(mem_buffer[m], mem[m]); + } + + // Phase 1: even pages on A, odd pages unbound. + Binding b1; + for (uint32_t p = 0; p < SPARSE_PAGES; ++p) { + b1.mem[p] = (p % 2 == 0) ? 0 : -1; + } + run_phase("phase 1 (even pages bound)", b1, 0x10000000u, mem); + + // Phase 2: the even pages unbound, the odd ones on B. Translations of the + // first launch must not survive into this one. + Binding b2; + for (uint32_t p = 0; p < SPARSE_PAGES; ++p) { + b2.mem[p] = (p % 2 == 1) ? 1 : -1; + } + run_phase("phase 2 (rebound)", b2, 0x20000000u, mem); + + // Phase 3: two reservation pages on one memory page, the rest unbound. + // Pages 4 and 5 both map B's page 2: the second page's slots see the + // first page's stores and atomics. + Binding b3; + for (uint32_t p = 0; p < SPARSE_PAGES; ++p) { + b3.mem[p] = (p == 4 || p == 5) ? 1 : -1; + } + apply(b3); + launch(0x30000000u); + { + auto reads = read_buffer_words(read_buffer, NUM_THREADS); + auto amos = read_buffer_words(amo_buffer, NUM_THREADS); + for (uint32_t t = 0; t < NUM_THREADS; ++t) { + uint32_t p = t / SLOTS; + uint32_t w = page_of(p) * WORDS_PER_PAGE + (t % SLOTS) * SLOT_STRIDE; + if (p == 4 || p == 5) { + expect("aliased read", t, mem[1][w], reads[t]); + // Both aliases increment the one word; either may come first. + if (amos[t] != mem[1][w + 2] && amos[t] != mem[1][w + 2] + 1) { + expect("aliased atomic", t, mem[1][w + 2], amos[t]); + } + } else { + expect("unbound read", t, 0u, reads[t]); + expect("unbound atomic", t, 0u, amos[t]); + } + } + auto stored = read_buffer_words(mem_buffer[1], MEM_PAGES * WORDS_PER_PAGE); + for (uint32_t s = 0; s < SLOTS; ++s) { + uint32_t w = page_of(4) * WORDS_PER_PAGE + s * SLOT_STRIDE; + mem[1][w + 2] += 2; + // The two aliases store to the same word: either store may land last. + uint32_t t4 = 4 * SLOTS + s, t5 = 5 * SLOTS + s; + uint32_t v = stored[w + 1]; + if (v != (0x30000000u | t4) && v != (0x30000000u | t5)) { + expect("aliased store", w + 1, 0x30000000u | t5, v); + } + mem[1][w + 1] = v; + } + for (int m = 0; m < 2; ++m) { + auto data = read_buffer_words(mem_buffer[m], MEM_PAGES * WORDS_PER_PAGE); + for (uint32_t w = 0; w < data.size(); ++w) { + expect(m == 0 ? "memory A" : "memory B", w, mem[m][w], data[w]); + } + } + std::cout << "phase 3 (aliased): " << (errors ? "errors" : "ok") << std::endl; + } + + // Phase 4: command-processor copies through the phase-2 binding. A write + // across the whole reservation lands only in the bound pages; a read of it + // returns 0 for the unbound ones. + apply(b2); + { + std::vector fill(SPARSE_PAGES * WORDS_PER_PAGE); + for (uint32_t w = 0; w < fill.size(); ++w) { + fill[w] = 0xC0000000u | w; + } + write_buffer(sparse_buffer, fill); + auto back = read_buffer_words(sparse_buffer, SPARSE_PAGES * WORDS_PER_PAGE); + for (uint32_t p = 0; p < SPARSE_PAGES; ++p) { + for (uint32_t i = 0; i < WORDS_PER_PAGE; ++i) { + uint32_t w = p * WORDS_PER_PAGE + i; + uint32_t expected = (b2.mem[p] < 0) ? 0u : fill[w]; + expect("copy readback", w, expected, back[w]); + if (b2.mem[p] >= 0) { + mem[b2.mem[p]][page_of(p) * WORDS_PER_PAGE + i] = fill[w]; + } + } + } + for (int m = 0; m < 2; ++m) { + auto data = read_buffer_words(mem_buffer[m], MEM_PAGES * WORDS_PER_PAGE); + for (uint32_t w = 0; w < data.size(); ++w) { + expect(m == 0 ? "memory A" : "memory B", w, mem[m][w], data[w]); + } + } + std::cout << "phase 4 (copies): " << (errors ? "errors" : "ok") << std::endl; + } + + // Phase 5: indirect launches whose record and predicate lie in the + // reservation. The record straddles two pages bound to unrelated memory + // pages: x comes from A's page 3, y from B's page 3, not from A's page 4 + // that follows A's page 3 physically. + { + Binding b5; + for (uint32_t p = 0; p < SPARSE_PAGES; ++p) { + b5.mem[p] = (p == 6) ? 0 : (p == 7) ? 1 : -1; + } + apply(b5); + const uint32_t x_groups = 4, y_groups = 1, decoy_y = 7; + auto put = [&](vx_buffer_h buf, uint64_t off, uint32_t v) { + vx_event_h ev = nullptr; + RT_CHECK(vx_enqueue_write(queue, buf, off, &v, sizeof(v), 0, nullptr, &ev)); + wait(ev); + }; + put(mem_buffer[0], 3 * PAGE_SIZE + PAGE_SIZE - 8, x_groups); // record word 0 + put(mem_buffer[0], 4 * PAGE_SIZE + 4, decoy_y); // where a contiguous read finds word 3 + put(mem_buffer[1], 3 * PAGE_SIZE + 4, y_groups); // record word 3 + vx_buffer_h count_buffer = nullptr; + RT_CHECK(vx_buffer_create(device, sizeof(uint32_t), VX_MEM_READ_WRITE, &count_buffer)); + put(count_buffer, 0, 0u); + kernel_arg_t arg = {}; + RT_CHECK(vx_buffer_address(count_buffer, &arg.count_addr)); + uint64_t sparse_addr = 0; + RT_CHECK(vx_buffer_address(sparse_buffer, &sparse_addr)); + vx_launch_indirect_t ind = {}; + ind.struct_size = sizeof(ind); + ind.type = VX_STRUCT_TYPE_LAUNCH_INDIRECT; + ind.record_addr = sparse_addr + 7 * uint64_t(PAGE_SIZE) - 8; + ind.grid_word[0] = 0; + ind.grid_word[1] = 3; + ind.grid_word[2] = VX_INDIRECT_ONE; + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.next = &ind; + li.kernel = kernel; + li.args_host = &arg; + li.args_size = sizeof(arg); + li.ndim = 2; + li.block_dim[0] = 1; + li.block_dim[1] = 1; + vx_event_h ev = nullptr; + RT_CHECK(vx_enqueue_launch(queue, &li, 0, nullptr, &ev)); + wait(ev); + auto count = read_buffer_words(count_buffer, 1); + expect("indirect grid threads", 0, x_groups * y_groups, count[0]); + + // An unbound page reads 0 for the command processor too: a predicate + // there (page 0, unbound under b5) is 0, so the guarded launch is skipped. + put(count_buffer, 0, 0u); + vx_launch_indirect_t pred = {}; + pred.struct_size = sizeof(pred); + pred.type = VX_STRUCT_TYPE_LAUNCH_INDIRECT; + pred.pred_addr = sparse_addr; + pred.pred_ref = 0; + li.next = &pred; + li.ndim = 1; + li.grid_dim[0] = 4; + RT_CHECK(vx_enqueue_launch(queue, &li, 0, nullptr, &ev)); + wait(ev); + count = read_buffer_words(count_buffer, 1); + expect("threads under an unbound predicate", 0, 0u, count[0]); + RT_CHECK(vx_buffer_release(count_buffer)); + std::cout << "phase 5 (indirect record and predicate in the reservation): " << (errors ? "errors" : "ok") << std::endl; + } + + // Phase 6: freeing the memory behind a bound page unbinds the page. A + // buffer allocated on the freed pages afterwards must not show through the + // reservation. + { + vx_buffer_h m = nullptr, n = nullptr; + RT_CHECK(vx_buffer_create(device, PAGE_SIZE, VX_MEM_READ_WRITE, &m)); + RT_CHECK(vx_buffer_bind(sparse_buffer, 8 * uint64_t(PAGE_SIZE), m, 0, PAGE_SIZE)); + RT_CHECK(vx_buffer_release(m)); + RT_CHECK(vx_buffer_create(device, PAGE_SIZE, VX_MEM_READ_WRITE, &n)); + std::vector fill(WORDS_PER_PAGE, 0xD3000000u); + write_buffer(n, fill); + std::vector page(WORDS_PER_PAGE); + vx_event_h ev = nullptr; + RT_CHECK(vx_enqueue_read(queue, page.data(), sparse_buffer, 8 * uint64_t(PAGE_SIZE), + PAGE_SIZE, 0, nullptr, &ev)); + wait(ev); + for (uint32_t i = 0; i < WORDS_PER_PAGE; ++i) { + expect("page whose memory was freed", i, 0u, page[i]); + } + RT_CHECK(vx_buffer_release(n)); + std::cout << "phase 6 (memory freed under a bound page): " << (errors ? "errors" : "ok") << std::endl; + } + + cleanup(); + + if (errors != 0) { + std::cout << "FAILED! - " << errors << " errors" << std::endl; + return 1; + } + std::cout << "PASSED!" << std::endl; + return 0; +} diff --git a/tests/regression/vm_test/main.cpp b/tests/regression/vm_test/main.cpp index 019b04cf9b..2583712f2d 100644 --- a/tests/regression/vm_test/main.cpp +++ b/tests/regression/vm_test/main.cpp @@ -331,7 +331,7 @@ int main(int argc, char* argv[]) { if (errors != 0) { std::cout << "FAILED! - " << errors << " errors" << std::endl; - return errors != 0; + return 1; } std::cout << "PASSED!" << std::endl; return 0; From cc19f0bac90ef19ab9af2ebfaabb225d863bcf26 Mon Sep 17 00:00:00 2001 From: Blaise Tine Date: Mon, 30 Nov 2026 18:32:37 -0800 Subject: [PATCH 4/4] cp: indirect launch (grid from device memory, predicate, zero-grid skip) and draw-descriptor steps Vulkan's vkCmdDispatchIndirect, indirect draws and conditional rendering need the device to read a launch's grid, or whether to launch at all, from device memory when the launch reaches the head of the queue, with no host read-back. - vx_launch_indirect_t, chained on vx_launch_info_t (VX_CAPS_CP_INDIRECT): a predicate (pred > ref, optionally inverted), a grid from a record of 32-bit words (per dimension: word index, shift, an x bias and divisor), and a skip count for the commands of the same submission when the launch does not execute; a zero dimension never starts a kernel. - The RTL command processor gains a launch sequencer (VX_cp_launch_seq), opcode 0x0D and the caps bits SUPPORTS_QMD/INDIRECT; the C++ CP model (sim/common/cmd_processor) and the runtime queue implement the same. - The CP walks every step of a draw descriptor; a launch on a backend busy from its start waits only for the busy fall (firesim, foldsim, gem5 declare it too). Tests: tests/regression/indirect, tests/runtime/test_indirect, tests/unittest/cp_model, hw/unittest cp_launch/cp_core/cp_engine (CI hw-cp). Default behaviour: existing commands are unchanged in the model (SimX and rtlsim identical); the RTL CP runs only on xrt/FPGA. Branch commits: a343f8c13, cd7a99d33, 7299ec588, 24669bcc4, 641d3e7e4, 0d623eef5. Co-Authored-By: Claude Opus 5.5 --- ci/testcases/cache.yaml | 6 +- ci/testcases/core.yaml | 16 +- ci/testcases/fpga_gate.yaml | 11 + ci/testcases/regression.yaml | 8 + ci/testcases/sw/runtime.yaml | 7 +- ci/testcases/unittest.yaml | 7 + docs/assets/img/cp_architecture.svg | 4 +- docs/designs/command_processor.md | 140 +++- docs/designs/vortex_runtime_api.md | 24 +- hw/rtl/cp/VX_cp_axil_regfile.sv | 10 +- hw/rtl/cp/VX_cp_core.sv | 163 +++- hw/rtl/cp/VX_cp_dcr_proxy.sv | 2 + hw/rtl/cp/VX_cp_engine.sv | 28 +- hw/rtl/cp/VX_cp_launch.sv | 71 -- hw/rtl/cp/VX_cp_launch_seq.sv | 496 +++++++++++ hw/rtl/cp/VX_cp_pkg.sv | 42 +- hw/unittest/Makefile | 12 + hw/unittest/cp_core/main.cpp | 211 ++++- .../cp_dcr_proxy/VX_cp_dcr_proxy_top.sv | 1 + hw/unittest/cp_engine/VX_cp_engine_top.sv | 4 + hw/unittest/cp_engine/main.cpp | 42 +- hw/unittest/cp_launch/Makefile | 6 +- hw/unittest/cp_launch/VX_cp_launch_seq_top.sv | 113 +++ hw/unittest/cp_launch/VX_cp_launch_top.sv | 32 - hw/unittest/cp_launch/main.cpp | 615 ++++++++++++-- sim/common/cmd_processor.cpp | 191 ++++- sim/common/cmd_processor.h | 30 +- sw/common/cp_launch_abi.h | 105 +++ sw/runtime/common/device.cpp | 67 +- sw/runtime/common/queue.cpp | 264 +++++- sw/runtime/common/vortex2_internal.h | 14 +- sw/runtime/include/vortex2.h | 49 ++ tests/regression/indirect/Makefile | 16 + tests/regression/indirect/common.h | 32 + tests/regression/indirect/kernel.cpp | 62 ++ tests/regression/indirect/main.cpp | 196 +++++ tests/runtime/Makefile | 12 +- tests/runtime/test_indirect.cpp | 792 ++++++++++++++++++ tests/unittest/cp_model/Makefile | 12 + tests/unittest/cp_model/main.cpp | 244 ++++++ tests/vulkan/dispatchindirect/Makefile | 30 + tests/vulkan/dispatchindirect/args.comp | 29 + tests/vulkan/dispatchindirect/main.c | 420 ++++++++++ tests/vulkan/dispatchindirect/mark.comp | 34 + 44 files changed, 4301 insertions(+), 369 deletions(-) delete mode 100644 hw/rtl/cp/VX_cp_launch.sv create mode 100644 hw/rtl/cp/VX_cp_launch_seq.sv create mode 100644 hw/unittest/cp_launch/VX_cp_launch_seq_top.sv delete mode 100644 hw/unittest/cp_launch/VX_cp_launch_top.sv create mode 100644 sw/common/cp_launch_abi.h create mode 100644 tests/regression/indirect/Makefile create mode 100644 tests/regression/indirect/common.h create mode 100644 tests/regression/indirect/kernel.cpp create mode 100644 tests/regression/indirect/main.cpp create mode 100644 tests/runtime/test_indirect.cpp create mode 100644 tests/unittest/cp_model/Makefile create mode 100644 tests/unittest/cp_model/main.cpp create mode 100644 tests/vulkan/dispatchindirect/Makefile create mode 100644 tests/vulkan/dispatchindirect/args.comp create mode 100644 tests/vulkan/dispatchindirect/main.c create mode 100644 tests/vulkan/dispatchindirect/mark.comp diff --git a/ci/testcases/cache.yaml b/ci/testcases/cache.yaml index e3f48c9006..0a21c9b3ad 100644 --- a/ci/testcases/cache.yaml +++ b/ci/testcases/cache.yaml @@ -350,6 +350,10 @@ tests: args: -f -n1 configs: -DVX_CFG_EXT_A_ENABLE -DVX_CFG_DCACHE_LAZY_FETCH=1 flags: --perf=7 +# The host's pre-pattern must sit in memory, not in the L2: with the command +# processor's DMA on the LLC (the default), the upload leaves every sector +# fully written and resident, and the partially stored control lines then +# loop back instead of reading memory. The DMA goes straight to memory here. - id: lazy_fetch-4 via: blackbox drivers: @@ -357,7 +361,7 @@ tests: - rtlsim app: lazy_fetch args: -f -n1 - configs: -DVX_CFG_EXT_A_ENABLE -DVX_CFG_SOCKET_SIZE=1 -DVX_CFG_L2_WRITEBACK=1 -DVX_CFG_L2_LAZY_FETCH=1 + configs: -DVX_CFG_EXT_A_ENABLE -DVX_CFG_SOCKET_SIZE=1 -DVX_CFG_L2_WRITEBACK=1 -DVX_CFG_L2_LAZY_FETCH=1 -DVX_CFG_CP_LLC_CLIENT=0 flags: --perf=7 shape: cores: 4 diff --git a/ci/testcases/core.yaml b/ci/testcases/core.yaml index 3fe85a90b1..26e0a2b779 100644 --- a/ci/testcases/core.yaml +++ b/ci/testcases/core.yaml @@ -160,12 +160,14 @@ tests: configs: -DVX_CFG_DCACHE_LAZY_FETCH=1 # Fully written sectors on a lazy-fetch write-back L2 shared by 4 cores: # partial-miss loads and parked chain heads refetch them through the loopback. +# The CP DMA bypasses the L2, as in cache:lazy_fetch-4, so the host's +# pre-pattern is not already resident and fully written at launch. - id: parity-lazy-fetch-full check: model_parity via: blackbox app: lazy_fetch args: -f -n1 - configs: -DVX_CFG_EXT_A_ENABLE -DVX_CFG_SOCKET_SIZE=1 -DVX_CFG_L2_WRITEBACK=1 -DVX_CFG_L2_LAZY_FETCH=1 + configs: -DVX_CFG_EXT_A_ENABLE -DVX_CFG_SOCKET_SIZE=1 -DVX_CFG_L2_WRITEBACK=1 -DVX_CFG_L2_LAZY_FETCH=1 -DVX_CFG_CP_LLC_CLIENT=0 flags: --perf=7 shape: cores: 4 @@ -224,11 +226,13 @@ tests: check: model_parity # Tighter than the default: the shape exercises those entries and the # collectors' output register exactly. + # The CP DMA stays off the LLC: on it, the RTL settles into one of two + # warp phasings (~145k or ~156k cycles) on an 8-cycle DRAM-latency change. tolerance: 0.03 via: blackbox app: sgemm args: -n64 - configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 + configs: -DVX_CFG_NUM_THREADS=8 -DVX_CFG_NUM_WARPS=8 -DVX_CFG_CP_LLC_CLIENT=0 shape: {cores: 2, l2cache: true} # The same shape behind a 20-cycle link to the L2, each way: both cores' L2 # traffic, its fills and its back-pressure cross the link's delay buffers. @@ -475,6 +479,14 @@ tests: via: blackbox app: stencil3d args: -n32 +# Command-processor indirect launch: a kernel writes the grid record, the next +# launch takes its grid from it, a predicated-off launch skips itself and the +# launch behind it, and a dependent kernel consumes the result. +- id: parity-indirect + check: model_parity + via: blackbox + app: indirect + args: -n16384 # Software raycaster: divergent control flow + mixed ALU/FPU. - id: parity-raycast check: model_parity diff --git a/ci/testcases/fpga_gate.yaml b/ci/testcases/fpga_gate.yaml index c808db1ce4..e6a2041d6e 100644 --- a/ci/testcases/fpga_gate.yaml +++ b/ci/testcases/fpga_gate.yaml @@ -111,6 +111,17 @@ builds: -DVX_CFG_EXT_A_ENABLE -DVX_CFG_VM_ENABLE -DVX_CFG_DCACHE_LATENCY=3 +# --- command processor --------------------------------------------------------- + +# Command processor: ring fetch/unpack, per-queue engine, resource arbiters, +# DMA, event unit, DCR proxy and KMU launch sequencer behind the host and +# device AXI crossbars. +- id: cp + group: core + dut: cp + clock_mhz: 300 + configs: "" + # --- dxa --------------------------------------------------------------------- # DXA engine: descriptor queue, address generation, multicast distribution. diff --git a/ci/testcases/regression.yaml b/ci/testcases/regression.yaml index 14329c7edb..51b684eed1 100644 --- a/ci/testcases/regression.yaml +++ b/ci/testcases/regression.yaml @@ -560,6 +560,14 @@ tests: drivers: - rtlsim app: single_cta +# Command-processor indirect launch through the RTL command processor (the +# xrt path runs VX_cp_core; simx/rtlsim run its C++ model, covered by isa-*). +- id: indirect-xrt + via: blackbox + drivers: + - xrt + app: indirect + args: -n1024 - id: module_reload-1 via: blackbox drivers: diff --git a/ci/testcases/sw/runtime.yaml b/ci/testcases/sw/runtime.yaml index d5e696bd25..e1bc8540f6 100644 --- a/ci/testcases/sw/runtime.yaml +++ b/ci/testcases/sw/runtime.yaml @@ -4,8 +4,9 @@ # (libvortex-simx.so) at vx_dev_open; `make software` only builds # kernel+stub, and this host case has no driver sim_build to produce it, # so build it explicitly here. -# 2. `make -C tests/regression/basic kernel.vxbin` — test_module_kernel -# consumes the `basic` regression .vxbin, which run-simx does NOT build. +# 2. `make -C tests/regression/{basic,indirect} kernel.vxbin` — +# test_module_kernel and test_indirect consume those regression .vxbins, +# which run-simx does NOT build. # 3. `make -C tests/runtime run-simx` — build + run the test binaries. category: sw defaults: @@ -16,4 +17,4 @@ defaults: tests: - id: runtime-1 via: script - run: "make -C sw/runtime simx && make -C tests/regression/basic kernel.vxbin && make -C tests/runtime run-simx" + run: "make -C sw/runtime simx && make -C tests/regression/basic kernel.vxbin && make -C tests/regression/indirect kernel.vxbin && make -C tests/runtime run-simx" diff --git a/ci/testcases/unittest.yaml b/ci/testcases/unittest.yaml index 0c1712bd24..a4c120d4a8 100644 --- a/ci/testcases/unittest.yaml +++ b/ci/testcases/unittest.yaml @@ -92,6 +92,13 @@ tests: - id: hw-fpu via: script run: "make -C hw/unittest run-fpu" + # Command processor (fetch/unpack/engine/arbiters/DMA/DCR proxy/launch + # sequencer/full core): the `hw` lane only builds these; this lane executes + # them so a CP RTL change is gated against its cycle-level unit models. + - id: hw-cp + via: script + run: "make -C hw/unittest run-cp" + touches: [hw/rtl/cp, hw/unittest/cp_] # TCU FEDP datapath: the `hw` lane only builds it; this lane executes tcu_fedp # per format (native TFR + DPI). touches gates it on tcu changes. - id: hw-tcu diff --git a/docs/assets/img/cp_architecture.svg b/docs/assets/img/cp_architecture.svg index 862476f650..2213e11708 100644 --- a/docs/assets/img/cp_architecture.svg +++ b/docs/assets/img/cp_architecture.svg @@ -135,8 +135,8 @@ shared resource units - VX_cp_launch - pulse start, hold until busy falls + VX_cp_launch_seq + replay QMD/ILD, start, hold until busy falls VX_cp_dcr_proxy diff --git a/docs/designs/command_processor.md b/docs/designs/command_processor.md index a68004f86a..53418c8460 100644 --- a/docs/designs/command_processor.md +++ b/docs/designs/command_processor.md @@ -131,16 +131,15 @@ come from `cmd_size_bytes` | `CMD_EVENT_SIGNAL` | 0x08 | 20 | EVENT | yes | yes | Write a counter slot | | `CMD_EVENT_WAIT` | 0x09 | 28 | EVENT | yes | yes | Spin until a counter satisfies a compare | | `CMD_CACHE_FLUSH` | 0x0A | 12 | DCR | yes | yes | Cache flush: broadcast start, per-core completion | -| `CMD_LAUNCH_QMD` | 0x0B | 12 | KMU | **no** | yes | Atomic launch: KMU descriptor read from memory (§2.3) | +| `CMD_LAUNCH_QMD` | 0x0B | 12 | KMU | yes | yes | Atomic launch: KMU descriptor read from memory (§2.3) | | `CMD_DRAW` | 0x0C | 12 | KMU | **no** | yes | Device-orchestrated graphics draw (§8.1) | +| `CMD_LAUNCH_INDIRECT` | 0x0D | 12 | KMU | yes | yes | Predicated launch with a device-sourced grid (§2.4) | `+8 B` to any size when `F_PROFILE` is set. -> **The last two opcodes are Emulation-CP only.** `VX_cp_pkg`'s -> `cp_opcode_e` enum stops at `CMD_CACHE_FLUSH`, so `cmd_opcode_valid()` -> ([`VX_cp_pkg.sv:163-178`](../../hw/rtl/cp/VX_cp_pkg.sv#L163)) rejects -> 0x0B and 0x0C and the RTL unpacker treats both as end-of-line. Each is -> capability-gated (§6) so the runtime only emits it where it is decoded. +> **`CMD_DRAW` is Emulation-CP only.** `cmd_opcode_valid()` in `VX_cp_pkg` +> rejects 0x0C and the RTL unpacker treats it as end-of-line. The optional +> opcodes are capability-gated (§6) so the runtime only emits what is decoded. ### 2.3 Per-opcode semantics @@ -154,18 +153,17 @@ come from `cmd_size_bytes` - **`CMD_DCR_READ`** — `arg0` = DCR address, `arg1` = tag placed on the DCR data bus. The response lands in `Q_LAST_DCR_RSP` (`+0x30`), which the host reads after observing the seqnum advance. -- **`CMD_LAUNCH`** — payload carries nothing the hardware reads. - `VX_cp_launch` only pulses `start`, and `VX_cp_core` explicitly discards - the granted command (`UNUSED_VAR (granted_kmu_cmd)`, - [`VX_cp_core.sv:309`](../../hw/rtl/cp/VX_cp_core.sv#L309)). Grid geometry - must already have been programmed by preceding `CMD_DCR_WRITE`s — which - is exactly why a launch costs 22 commands (§4.4). -- **`CMD_LAUNCH_QMD`** — `arg0` points at an in-memory KMU descriptor, - `{u32 count, count × (u32 dcr_addr, u32 value)}`. The CP reads it and - replays the pairs through the DCR write path, then pulses start — - collapsing the 20-write launch dance into one command - ([`cmd_processor.cpp:308-322`](../../sim/common/cmd_processor.cpp#L308)). - This is the NVIDIA QMD model. A 64-pair backstop guards a corrupt count. +- **`CMD_LAUNCH`** — payload carries nothing the hardware reads: the launch + sequencer only pulses `start` and waits for the drain. Grid geometry must + already have been programmed by preceding `CMD_DCR_WRITE`s — which is + exactly why a launch costs 22 commands (§4.4). +- **`CMD_LAUNCH_QMD`** — `arg0` points at a 64-byte-aligned in-memory KMU + descriptor, `{u32 count, u32 reserved, count × (u32 dcr_addr, u32 value)}` + ([`cp_launch_abi.h`](../../sw/common/cp_launch_abi.h)); the reserved word + keeps every pair inside one 64-byte line. The CP reads it and replays the + pairs through the DCR write path, then pulses start — collapsing the + 20-write launch dance into one command. This is the NVIDIA QMD model. A + 64-pair backstop guards a corrupt count. - **`CMD_FENCE`** — scope masks in `arg0[1:0]` (`FENCE_DMA_BIT`, `FENCE_GPU_BIT`, [`VX_cp_pkg.sv:120-121`](../../hw/rtl/cp/VX_cp_pkg.sv#L120)). - **`CMD_EVENT_WAIT`** — compare op in `arg2[1:0]` @@ -183,6 +181,44 @@ come from `cmd_size_bytes` system-scope flush ahead of the next device-memory transfer (see the launch encoding in §9). +### 2.4 Indirect launch (`CMD_LAUNCH_INDIRECT`) + +`arg0` points at an indirect launch descriptor (ILD, +[`cp_launch_abi.h`](../../sw/common/cp_launch_abi.h)): a 64-byte header line +followed by an ordinary QMD body of pairs. The header carries a control word +(per-dimension word select 0..14 or constant 1, per-dimension ceil-shift, +`HAS_RECORD`, `HAS_PRED`, `PRED_INV`, `NO_LAUNCH`), a `skip_n`, the record +and predicate addresses, the predicate reference, the pair count, and an +x-only bias and divisor. Executing it: + +1. **Predicate** (`HAS_PRED`): `exec = (*pred_addr > pred_ref) ^ PRED_INV`, + unsigned 32-bit. +2. **Grid** (`HAS_RECORD`): each dimension selects a 32-bit record word (or + 1); x becomes `max(w - bias, 0) / div` (`div` 0 or 1 bypasses); then + `g = ceil(w / 2^shift)`. Any `g == 0` clears `exec`, so a device-computed + zero never reaches the KMU, where a zero grid means a raster kick. +3. **Not executed**: the command retires and its queue retires the next + `skip_n` commands without executing them (inside an `OP_DRAW` bundle the + walk skips `skip_n` steps). No DCR is written. +4. **`NO_LAUNCH`**: retire once the predicate and grid pass — a predicate + guarding the commands after it (AMD `COND_EXEC`). +5. **Otherwise** the pairs replay with `GRID_DIM_X/Y/Z` replaced by `g`, + then the kernel starts and drains as for `CMD_LAUNCH_QMD`. + +This is the fixed-function core of AMD's `DISPATCH_INDIRECT` / +`COND_EXEC` / `SET_PREDICATION` and of NVIDIA's indirect fetch: indirect +dispatch, conditional rendering, indirect-count unrolls and byte-count +derivation without a host read-back or a programmable CP sequencer. + +The CP reads the descriptor, record and predicate from DRAM below the +caches. A record a kernel produced is visible because the runtime posts +`CMD_CACHE_FLUSH` after every launch and the CP retires in order, so a +producer earlier in the stream is always flushed first. The runtime counts +`skip_count` in API commands and translates it to ring commands (a launch is +its launch command plus the trailing flush). Commands inside a skip range are +launches and DCR writes only, which is all `vx_command_t` can express — an +event signal or a download skipped there would hang the host. + --- ## 3. RTL CP module inventory @@ -200,7 +236,7 @@ come from `cmd_size_bytes` | [`VX_cp_unpack.sv`](../../hw/rtl/cp/VX_cp_unpack.sv) | Per-offset single-command decoder (one command/cycle; refactored from a combinational whole-line walk that was a 35-level path). | | [`VX_cp_engine.sv`](../../hw/rtl/cp/VX_cp_engine.sv) | Per-queue FSM `IDLE→DECODE→BID→WAIT_DONE→RETIRE`; classifies opcode→resource and retires via valid/ready handshake. | | [`VX_cp_arbiter.sv`](../../hw/rtl/cp/VX_cp_arbiter.sv) | Thin wrapper over `VX_rr_arbiter`, instantiated 4× (one per resource). | -| [`VX_cp_launch.sv`](../../hw/rtl/cp/VX_cp_launch.sv) | KMU start/busy wrapper: pulse start, hold grant until `busy` deasserts (drain). | +| [`VX_cp_launch_seq.sv`](../../hw/rtl/cp/VX_cp_launch_seq.sv) | KMU launch sequencer: plain launch, QMD replay, indirect launch (predicate, grid select/divide/ceil-shift, skip); reads descriptors over the dev xbar; pulses start and holds the grant until `busy` deasserts (drain). | | [`VX_cp_dcr_proxy.sv`](../../hw/rtl/cp/VX_cp_dcr_proxy.sv) | DCR req/rsp gateway; also drives the per-core `CMD_CACHE_FLUSH` sweep; publishes last read in `Q_LAST_DCR_RSP`. | | [`VX_cp_dma.sv`](../../hw/rtl/cp/VX_cp_dma.sv) | Dual-port burst DMA (`axi_host` + `axi_dev`); opcode routes ports; ≤4 KB INCR chunks. | | [`VX_cp_event_unit.sv`](../../hw/rtl/cp/VX_cp_event_unit.sv) | `EVENT_SIGNAL` write + `EVENT_WAIT` poll-spin against counter slots. | @@ -317,15 +353,17 @@ is a single-engine CP. Three things gate raising it: geometry lives in *global* KMU DCR state. Two queues launching concurrently would interleave each other's `CMD_DCR_WRITE`s. `CMD_LAUNCH_QMD` is the fix — it makes a launch self-describing — and - it exists in the Emulation CP but not the RTL CP. + the launch sequencer holds the DCR arbiter for the whole replay, so + another queue's DCR writes cannot interleave with it. The KMU DCRs are + still one global state, so concurrent launches remain serialized. 2. **Resource re-entry.** The arbiters grant for one cycle with no in-flight tracking, and the resource units latch their command only in their own `S_IDLE`. A second grant issued while a unit is busy is ignored by the unit, but the newly-granted CPE still advances to `S_WAIT_DONE` and will retire on the *first* command's `done` pulse — its own command never executes. Multi-queue therefore needs the - arbiters to hold the grant for the resource's whole occupancy (as - `VX_cp_launch` already assumes for KMU), or the resource units to + arbiters to hold the grant for the resource's whole occupancy (as the + launch sequencer already assumes for KMU), or the resource units to backpressure the arbiter. 3. **The host serializes anyway.** All host queues funnel into one ring behind one mutex (§9). @@ -334,7 +372,7 @@ The **host-side** scaling limit is the launch path, not the ring: 21 commands per launch, unbatched, each with its own doorbell and its own busy-poll loop (§9). `CMD_LAUNCH_QMD` collapses the 20 DCR writes to one command; batching collapses 21 doorbells to one. Both are implemented in -the Emulation CP and the runtime; the RTL CP needs the QMD mirror. +both CPs and the runtime. ### 4.5 The submit handshake end to end @@ -466,10 +504,15 @@ upper byte of the CP's own caps word is free, and the Emulation CP uses it | 24 | `VM_ENABLED` | The CP DMA does a page-table walk (§8) | | 25 | `SUPPORTS_DRAW` | The CP decodes `CMD_DRAW` / `OP_DRAW` (§8.1) | | 26 | `SUPPORTS_QMD` | The CP decodes `CMD_LAUNCH_QMD` (§2.3) | - -**The RTL CP sets `VM_ENABLED` from `VX_CFG_VM_ENABLE` and hardwires -`SUPPORTS_DRAW` / `SUPPORTS_QMD` to zero**, so on FPGA every launch takes the -20-DCR fallback and draws stream as a ring batch. The runtime consumes the +| 27 | `MMU_FAULT_REPORT` | The device answers the MMU fault-report DCRs | +| 28 | `SUPPORTS_INDIRECT` | The CP decodes `CMD_LAUNCH_INDIRECT` (§2.4) | +| 29 | `DMA_LLC_CLIENT` | The CP DMA is a client of the last-level cache, the point of coherence for host transfers | + +**The RTL CP sets `VM_ENABLED` from `VX_CFG_VM_ENABLE`, `SUPPORTS_QMD`, +`SUPPORTS_INDIRECT`, and `DMA_LLC_CLIENT` from its `DMA_LLC_CLIENT` parameter** +([`VX_cp_axil_regfile.sv`](../../hw/rtl/cp/VX_cp_axil_regfile.sv)): on FPGA +launches replay QMDs and indirect launches run in hardware, and draws stream +as a ring batch. The runtime consumes the bits at open ([`device.cpp:274-282`](../../sw/runtime/common/device.cpp#L274)) and branches accordingly, so the graphics driver calls `vx_enqueue_draw` unconditionally on every backend. @@ -478,11 +521,20 @@ unconditionally on every backend. ## 7. Resource units -- **KMU launch** ([`VX_cp_launch.sv`](../../hw/rtl/cp/VX_cp_launch.sv)) — - `IDLE→PULSE_START→WAIT_BUSY→WAIT_DRAIN`; holds the KMU grant until - `busy` falls, so a queue serializes its own launches. `done` fires on the - falling edge of `busy`, which makes **the kernel drain itself the - barrier** — the property §8.1 depends on. +- **KMU launch sequencer** ([`VX_cp_launch_seq.sv`](../../hw/rtl/cp/VX_cp_launch_seq.sv)) — + reads the descriptor lines it needs over its own dev-xbar port (one + aligned 64-byte line per read, so no burst crosses a 4 KiB page; sub-line + words are selected by address), derives the grid with one shared word + select, a serial divider (`VX_serial_div`, x only, only when the divisor + exceeds 1) and a ceil-shift, then replays the pairs from the held read + beat (`rready` low) through a registered DCR request stage. While it + replays, `dcr_hold` masks the DCR arbiter's bids and the replay waits for + the DCR proxy to go idle, so no other DCR command interleaves with a + launch descriptor. It then pulses start, holds the KMU grant until `busy` + falls, and fires `done` on that falling edge, which makes **the kernel + drain itself the barrier** — the property §8.1 depends on. A + predicated-off launch finishes with `skip`/`skip_n` instead, which loads + the engine's skip counter. - **DCR proxy** ([`VX_cp_dcr_proxy.sv`](../../hw/rtl/cp/VX_cp_dcr_proxy.sv)) — `IDLE→REQ→(WAIT_RSP)→DONE`. Writes complete at `REQ`; reads wait for `dcr_rsp_valid`. `CMD_CACHE_FLUSH` first passes through `START`: one DCR @@ -571,7 +623,9 @@ address equal to a device address is never confused with it. A backend whose CP-visible host memory is device memory (gem5) leaves the host hooks unset, and they fall back to the device ones. Its engine FSM mirrors the RTL's (`Idle/Decode/Bid/WaitDone/Retire`) plus two states for the draw walk, and -its `LaunchState` mirrors `VX_cp_launch` exactly. Having no arbiters is not +its `LaunchState` mirrors the RTL sequencer's start/busy/drain states. It is +functional: descriptor reads and the replay take no simulated cycles, where +the RTL sequencer spends a few DRAM round trips per launch (§10). Having no arbiters is not a divergence — with one queue the RTL's arbiters are degenerate too. The Emulation CP's MMIO map matches the RTL regfile **plus**: @@ -579,7 +633,7 @@ The Emulation CP's MMIO map matches the RTL regfile **plus**: - the `CP_DEV_CAPS` feature bits 25-26 (§6), - byte-exact `CMD_MEM_*` copies, staged through a 64 KiB bounce buffer ([`:531-541`](../../sim/common/cmd_processor.cpp#L531)), -- the two extra opcodes, `CMD_LAUNCH_QMD` (§2.3) and `CMD_DRAW` (§8.1). +- the extra opcode `CMD_DRAW` (§8.1). Both CPs are MMU-aware: with a root in `CP_SATP`, each `CMD_MEM_*` walks the Sv32/Sv39 table (megapage-aware) for its device operands, once per @@ -601,8 +655,9 @@ DCR writes. `CMD_DRAW`'s `arg0` points at a resident **draw descriptor** issuing each stage's DCR config + KMU launch and **draining each launch as the inter-stage barrier** — the same drain-ordering the sort-middle front end (expand→setup→bin→RASTER→FS→OM) needs, with no host round-trip mid-draw. The host -records the descriptor once and rings the doorbell once. A corrupt `num_steps` is -clamped to 256. +records the descriptor once and rings the doorbell once. The CP walks every one +of the `num_steps` steps, as it would stream the same commands through the ring: +a draw's length is not bounded by the descriptor. ![CMD_DRAW device-orchestrated draw](../assets/img/cp_draw_sequence.svg) @@ -773,13 +828,12 @@ The following gaps remain **open**. **Performance / feature gaps:** -4. **QMD `CMD_LAUNCH_QMD` in the RTL CP.** The atomic-launch opcode, the - in-memory descriptor format, the runtime encoder, and the - `SUPPORTS_QMD` gate all exist and are validated on the Emulation CP - (§2.3); the RTL CP does not decode 0x0B and advertises 0. Until it does, - every FPGA launch pays the 20-`CMD_DCR_WRITE` dance, and per-queue - launch concurrency stays blocked on item 4. -5. **`CMD_DRAW` in the RTL CP** (§8.1) — same shape: shipped in emulation, +6. **Launch-descriptor latency is not modelled.** The RTL sequencer reads + the header, predicate, record and body lines one at a time, and the + Emulation CP takes no cycles for them, so the per-launch descriptor cost + is visible only on xrt/opae. Per-queue launch concurrency stays blocked + on item 5. +7. **`CMD_DRAW` in the RTL CP** (§8.1) — same shape: shipped in emulation, cap bit cleared in RTL. 6. **Multi-queue everywhere.** RTL is parameterized on `NUM_QUEUES` but defaults to 1; the Emulation CP models only `q0_`; the runtime programs diff --git a/docs/designs/vortex_runtime_api.md b/docs/designs/vortex_runtime_api.md index d687f2b7eb..3003d392cd 100644 --- a/docs/designs/vortex_runtime_api.md +++ b/docs/designs/vortex_runtime_api.md @@ -67,6 +67,24 @@ into the KMU ARG DCRs. The caller never allocates an args buffer. A `kernel == NULL` (and `args_host == NULL`, `ndim == 0`) "legacy escape hatch" lets a caller pre-program the KMU PC/ARG DCRs directly. +### 2.4 Indirect launch (extension struct) + +Device-sourced launch arguments are an extension struct on +`vx_launch_info_t.next`, not a new entry point: `vx_launch_indirect_t` +(`type = VX_STRUCT_TYPE_LAUNCH_INDIRECT`). Every extension struct begins +`{struct_size, next, type}` so a chain can carry more than one. It names a +grid record (word select, ceil-shift, x bias and divisor), a predicate +(`*pred > ref`, optionally inverted), the predicate-only form, and a +`skip_count` of following commands to skip when the launch does not run. +It works in `vx_enqueue_launch` (skip 0), `vx_enqueue_commands` and +`vx_enqueue_draw`; the command processor evaluates it on the device +(`CMD_LAUNCH_INDIRECT`, [`command_processor.md`](command_processor.md) §2.4). +`VX_CAPS_CP_INDIRECT` reports support; without it a chained launch is +refused with `VX_ERR_NOT_SUPPORTED` — the runtime never reads the record on +the host. Vulkan (indirect dispatch/draw, conditional rendering, byte-count +draws, trace rays indirect), Metal (indirect threadgroups and draws) and +OpenGL (`glDispatchComputeIndirect`, conditional render) all map onto it. + --- ## 3. Proposed but not yet implemented @@ -74,9 +92,9 @@ hatch" lets a caller pre-program the KMU PC/ARG DCRs directly. The API ships the locked post-removal shape directly (no deprecation-shim transition window was used). Deferred, out-of-scope-by-design: -1. **Memory/event pools, indirect dispatch, host functions, SVM, command - buffers, per-arg setters** — explicitly deferred (the "additive" - surface for a future v2). +1. **Memory/event pools, host functions, SVM, command buffers, per-arg + setters** — explicitly deferred (the "additive" surface for a future + v2). 2. **Risk-register items** worth preserving as forward guidance: waiter wakeup-storm mitigation; buffer-pointer width marshalling (a proposed `vx_kernel_get_pointer_size` helper — only `get_max_block_size` diff --git a/hw/rtl/cp/VX_cp_axil_regfile.sv b/hw/rtl/cp/VX_cp_axil_regfile.sv index 455acb64c1..1945b3e62a 100644 --- a/hw/rtl/cp/VX_cp_axil_regfile.sv +++ b/hw/rtl/cp/VX_cp_axil_regfile.sv @@ -16,7 +16,8 @@ // 0x004 CP_STATUS RO bit0=busy, bit1=error // 0x008 CP_DEV_CAPS RO [7:0]NUM_QUEUES | [15:8]RING_SIZE_LOG2_MAX // [23:16]AXI_TID_WIDTH | [24]VM_ENABLED -// [28]DMA_LLC_CLIENT +// [26]SUPPORTS_QMD | [28]SUPPORTS_INDIRECT +// [29]DMA_LLC_CLIENT // 0x00C GPU_DEV_CAPS_EXT RO device-config caps extension: [7:0]SOCKET_SIZE // 0x010 CP_CYCLE_LO RO free-running cycle counter low 32 bits // 0x014 CP_CYCLE_HI RO high 32 bits @@ -221,9 +222,12 @@ module VX_cp_axil_regfile case (addr[5:0]) 6'h00: return r_cp_ctrl; 6'h04: return {30'd0, cp_error, cp_busy}; - 6'h08: return {3'd0, + 6'h08: return {2'd0, 1'(DMA_LLC_CLIENT), - 3'd0, + 1'b1, // SUPPORTS_INDIRECT + 1'b0, + 1'b1, // SUPPORTS_QMD + 1'b0, 1'(`VX_CFG_VM_ENABLED), 8'(AXI_TID_W), 8'(RING_SIZE_LOG2_MAX), diff --git a/hw/rtl/cp/VX_cp_core.sv b/hw/rtl/cp/VX_cp_core.sv index 28995c62fe..b60616ac60 100644 --- a/hw/rtl/cp/VX_cp_core.sv +++ b/hw/rtl/cp/VX_cp_core.sv @@ -23,7 +23,7 @@ // ▼ ▼ ▼ // ┌──────────────────────────────┐ ┌────────────────────────┐ // │ host xbar: fetch[N] + cmpl │ │ dev xbar: DMA(dev) + │ -// │ + DMA(host) │ │ event │ +// │ + DMA(host) │ │ event + launch seq │ // └───────────────┬──────────────┘ └───────────┬────────────┘ // ▼ axi_host (AXI4) ▼ axi_dev (AXI4) // @@ -33,7 +33,8 @@ // axi_dev reaches device memory. The DMA engine straddles both: its // opcode picks the read-source and write-destination port. // -// The shared KMU launch / DCR proxy connect to gpu_if (Vortex side). +// The shared KMU launch sequencer / DCR proxy connect to gpu_if (Vortex +// side). The sequencer reads launch descriptors through the dev xbar. // // AXI master TID layout (per xbar): // bit [ID_W-1 : ID_W-SRC_W] = source index (xbar sets/inspects this for @@ -114,14 +115,15 @@ module VX_cp_core // Host xbar sources: fetch[NUM_QUEUES] + completion + DMA(host side). localparam int N_SRC_HOST = NUM_QUEUES + 2; - // Device xbar sources: DMA(dev side) + event unit. - localparam int N_SRC_DEV = 2; + // Device xbar sources: DMA(dev side) + event unit + launch sequencer. + localparam int N_SRC_DEV = 3; // Source-slot indices. localparam int SLOT_CMPL = NUM_QUEUES; // host xbar localparam int SLOT_DMA_HOST = NUM_QUEUES + 1; // host xbar localparam int SLOT_DMA_DEV = 0; // dev xbar localparam int SLOT_EVENT = 1; // dev xbar + localparam int SLOT_LAUNCH = 2; // dev xbar // ----- Regfile-owned per-queue programmable state ----- cpe_state_t q_state [NUM_QUEUES]; @@ -131,6 +133,7 @@ module VX_cp_core logic [63:0] q_head_to_reg [NUM_QUEUES]; logic [63:0] q_seqnum_to_reg [NUM_QUEUES]; logic [31:0] q_error_to_reg [NUM_QUEUES]; + logic [Q_ERROR_DESC_ALIGN:0] q_error_r [NUM_QUEUES]; // Aggregated CP status seen by the host through CP_STATUS. logic cp_busy; @@ -197,8 +200,11 @@ module VX_cp_core cmd_t cpe_cmd [NUM_QUEUES]; logic cpe_cmd_ready [NUM_QUEUES]; - // Shared-resource done pulses. + // Shared-resource done pulses; a launch may also finish predicated off. logic launch_done, dma_done, dcr_done, event_done; + logic launch_skip; + logic [15:0] launch_skip_n; + logic launch_fault; // Per-CPE AXI sub-master ports (fetch is the only AXI user per CPE). VX_mem_axi_if #(.ADDR_W(ADDR_W), .DATA_W(DATA_W), .ID_W(ID_W)) @@ -237,6 +243,8 @@ module VX_cp_core // every CPE; only the granted CPE is in S_WAIT_DONE when the // matching pulse arrives. .kmu_done_i (launch_done), + .kmu_skip_i (launch_skip), + .kmu_skip_n_i (launch_skip_n), .dma_done_i (dma_done), .dcr_done_i (dcr_done), .event_done_i (event_done), @@ -253,7 +261,7 @@ module VX_cp_core // Telemetry up to the regfile. assign q_seqnum_to_reg[q] = seqnum_out[q]; - assign q_error_to_reg [q] = 32'd0; // per-queue error reporting reserved + assign q_error_to_reg [q] = 32'(q_error_r[q]); end endgenerate @@ -269,6 +277,8 @@ module VX_cp_core logic dma_grant [NUM_QUEUES]; wire dcr_valid [NUM_QUEUES]; + wire dcr_bid [NUM_QUEUES]; + logic seq_dcr_hold; wire [1:0] dcr_prio [NUM_QUEUES]; cmd_t dcr_cmd [NUM_QUEUES]; logic dcr_grant [NUM_QUEUES]; @@ -291,6 +301,8 @@ module VX_cp_core assign bid_dma[q].grant = dma_grant[q]; assign dcr_valid[q] = bid_dcr[q].valid; + // No DCR command may interleave with a launch descriptor replay. + assign dcr_bid[q] = dcr_valid[q] && !seq_dcr_hold; assign dcr_prio[q] = bid_dcr[q].priority_; assign dcr_cmd[q] = bid_dcr[q].cmd; assign bid_dcr[q].grant = dcr_grant[q]; @@ -302,21 +314,41 @@ module VX_cp_core end endgenerate - VX_cp_arbiter #(.N(NUM_QUEUES)) u_arb_kmu ( - .clk(clk), .reset(reset), - .bid_valid(kmu_valid), .bid_priority(kmu_prio), .bid_grant(kmu_grant) + VX_cp_arbiter #( + .N (NUM_QUEUES) + ) u_arb_kmu ( + .clk (clk), + .reset (reset), + .bid_valid (kmu_valid), + .bid_priority (kmu_prio), + .bid_grant (kmu_grant) ); - VX_cp_arbiter #(.N(NUM_QUEUES)) u_arb_dma ( - .clk(clk), .reset(reset), - .bid_valid(dma_valid), .bid_priority(dma_prio), .bid_grant(dma_grant) + VX_cp_arbiter #( + .N (NUM_QUEUES) + ) u_arb_dma ( + .clk (clk), + .reset (reset), + .bid_valid (dma_valid), + .bid_priority (dma_prio), + .bid_grant (dma_grant) ); - VX_cp_arbiter #(.N(NUM_QUEUES)) u_arb_dcr ( - .clk(clk), .reset(reset), - .bid_valid(dcr_valid), .bid_priority(dcr_prio), .bid_grant(dcr_grant) + VX_cp_arbiter #( + .N (NUM_QUEUES) + ) u_arb_dcr ( + .clk (clk), + .reset (reset), + .bid_valid (dcr_bid), + .bid_priority (dcr_prio), + .bid_grant (dcr_grant) ); - VX_cp_arbiter #(.N(NUM_QUEUES)) u_arb_event ( - .clk(clk), .reset(reset), - .bid_valid(event_valid), .bid_priority(event_prio), .bid_grant(event_grant) + VX_cp_arbiter #( + .N (NUM_QUEUES) + ) u_arb_event ( + .clk (clk), + .reset (reset), + .bid_valid (event_valid), + .bid_priority (event_prio), + .bid_grant (event_grant) ); // ----- Pick the granted bid's cmd for each shared resource ----- @@ -335,39 +367,103 @@ module VX_cp_core end end - `UNUSED_VAR (granted_kmu_cmd) // Internal CP-side bundle; the register slice isolating it from the Vortex // boundary (gpu_if) is instantiated at the bottom of the module. VX_cp_gpu_if gpu_if_int(); - // ----- Shared KMU launch (consumes the kmu bid grant) ----- - VX_cp_launch u_launch ( - .clk (clk), - .reset (reset), - .grant (any_kmu_grant), - .start (gpu_if_int.start), - .gpu_busy (gpu_if_int.busy), - .done (launch_done) - ); + VX_mem_axi_if #( + .ADDR_W (ADDR_W), + .DATA_W (DATA_W), + .ID_W (ID_W) + ) launch_axi (); // ----- Shared DCR proxy ----- + wire proxy_idle; + wire proxy_req_valid; + wire proxy_req_rw; + wire [`VX_DCR_ADDR_BITS-1:0] proxy_req_addr; + wire [`VX_DCR_DATA_BITS-1:0] proxy_req_data; + VX_cp_dcr_proxy u_dcr ( .clk (clk), .reset (reset), .grant (any_dcr_grant), .cmd (granted_dcr_cmd), .done (dcr_done), + .idle (proxy_idle), .last_rsp_data (dcr_last_rsp_data), - .dcr_req_valid (gpu_if_int.dcr_req_valid), - .dcr_req_rw (gpu_if_int.dcr_req_rw), - .dcr_req_addr (gpu_if_int.dcr_req_addr), - .dcr_req_data (gpu_if_int.dcr_req_data), + .dcr_req_valid (proxy_req_valid), + .dcr_req_rw (proxy_req_rw), + .dcr_req_addr (proxy_req_addr), + .dcr_req_data (proxy_req_data), .dcr_rsp_valid (gpu_if_int.dcr_rsp_valid), .dcr_rsp_data (gpu_if_int.dcr_rsp_data), .gpu_busy (gpu_if_int.busy) ); - `UNUSED_VAR (gpu_if_int.dcr_req_ready) + + // ----- Shared KMU launch sequencer (consumes the kmu bid grant) ----- + wire seq_req_valid; + wire [`VX_DCR_ADDR_BITS-1:0] seq_req_addr; + wire [`VX_DCR_DATA_BITS-1:0] seq_req_data; + + VX_cp_launch_seq #( + .ADDR_W (ADDR_W), + .DATA_W (DATA_W), + .ID_W (ID_W) + ) u_launch ( + .clk (clk), + .reset (reset), + .grant (any_kmu_grant), + .cmd (granted_kmu_cmd), + .done (launch_done), + .skip (launch_skip), + .skip_n (launch_skip_n), + .fault (launch_fault), + .dcr_hold (seq_dcr_hold), + .dcr_proxy_idle (proxy_idle), + .dcr_req_valid (seq_req_valid), + .dcr_req_addr (seq_req_addr), + .dcr_req_data (seq_req_data), + .dcr_req_ready (gpu_if_int.dcr_req_ready), + .start (gpu_if_int.start), + .gpu_busy (gpu_if_int.busy), + .axi_m (launch_axi) + ); + + // Q_ERROR: sticky per queue until the queue is reset. A launch fault belongs + // to the queue that holds the KMU grant. + localparam int QW = `UP($clog2(NUM_QUEUES)); + logic [QW-1:0] kmu_owner; + always_ff @(posedge clk) begin + if (reset) begin + kmu_owner <= '0; + end else begin + for (int i = 0; i < NUM_QUEUES; ++i) begin + if (kmu_grant[i]) begin + kmu_owner <= QW'(i); + end + end + end + end + generate + for (genvar q = 0; q < NUM_QUEUES; ++q) begin : g_q_error + always_ff @(posedge clk) begin + if (reset || q_clear[q]) begin + q_error_r[q] <= '0; + end else if (launch_fault && (kmu_owner == QW'(q))) begin + q_error_r[q][Q_ERROR_DESC_ALIGN] <= 1'b1; + end + end + end + endgenerate + + // The sequencer drives the DCR bus only while it holds the arbiter with the + // proxy idle, so the two requesters are never active together. + assign gpu_if_int.dcr_req_valid = seq_req_valid || proxy_req_valid; + assign gpu_if_int.dcr_req_rw = seq_req_valid ? 1'b1 : proxy_req_rw; + assign gpu_if_int.dcr_req_addr = seq_req_valid ? seq_req_addr : proxy_req_addr; + assign gpu_if_int.dcr_req_data = seq_req_valid ? seq_req_data : proxy_req_data; // ----- DMA (straddles host + dev xbars) ----- VX_mem_axi_if #(.ADDR_W(ADDR_W), .DATA_W(DATA_W), .ID_W(ID_W)) dma_host_axi (); @@ -475,6 +571,7 @@ module VX_cp_core `CP_AXI_LINK(xbar_dev_src[SLOT_DMA_DEV], dma_dev_axi); `CP_AXI_LINK(xbar_dev_src[SLOT_EVENT], event_axi); + `CP_AXI_LINK(xbar_dev_src[SLOT_LAUNCH], launch_axi); // Register slice on the path to device memory (memory subsystem). VX_mem_axi_if #( diff --git a/hw/rtl/cp/VX_cp_dcr_proxy.sv b/hw/rtl/cp/VX_cp_dcr_proxy.sv index 95c159e34c..8ac7019d75 100644 --- a/hw/rtl/cp/VX_cp_dcr_proxy.sv +++ b/hw/rtl/cp/VX_cp_dcr_proxy.sv @@ -48,6 +48,7 @@ module VX_cp_dcr_proxy input cmd_t cmd, // verilator lint_on UNUSED output logic done, + output logic idle, // Most recent CMD_DCR_READ response value (valid while `done` is high // after a read; tied to 0 after writes). Engine snapshots this when it @@ -189,6 +190,7 @@ module VX_cp_dcr_proxy dcr_req_data = pending_data; end done = (state == S_DONE) && !flush_drain; + idle = (state == S_IDLE); last_rsp_data = rsp_data_r; end diff --git a/hw/rtl/cp/VX_cp_engine.sv b/hw/rtl/cp/VX_cp_engine.sv index 1c76d937cf..85f156efc2 100644 --- a/hw/rtl/cp/VX_cp_engine.sv +++ b/hw/rtl/cp/VX_cp_engine.sv @@ -20,10 +20,14 @@ // // Opcodes handled: // - CMD_NOP / CMD_FENCE (retire immediately) -// - CMD_LAUNCH (bid KMU) +// - CMD_LAUNCH / CMD_LAUNCH_QMD / CMD_LAUNCH_INDIRECT (bid KMU) // - CMD_DCR_WRITE / CMD_DCR_READ / CMD_CACHE_FLUSH (bid DCR) // - CMD_MEM_* (bid DMA) // - CMD_EVENT_SIGNAL / CMD_EVENT_WAIT (bid EVENT) +// +// A predicated-off CMD_LAUNCH_INDIRECT finishes with `kmu_skip_i`: the next +// `kmu_skip_n_i` commands of this queue then retire from DECODE without +// bidding for any resource. // ============================================================================ module VX_cp_engine @@ -58,6 +62,8 @@ module VX_cp_engine // the resource finishes the current command. The engine consumes them // in S_WAIT_DONE to know when to retire. input wire kmu_done_i, + input wire kmu_skip_i, + input wire [15:0] kmu_skip_n_i, input wire dma_done_i, input wire dcr_done_i, input wire event_done_i, @@ -95,6 +101,7 @@ module VX_cp_engine cp_resource_e cur_res; logic no_resource; // true for opcodes that bypass arbiters (NOP, FENCE, EVENT_*) logic [63:0] seqnum_r; + logic [15:0] skip_cnt; // S_IDLE with no command presented means nothing is in flight and no // resource grant is held, so the retire counter can be cleared safely. @@ -107,7 +114,8 @@ module VX_cp_engine output logic skip); skip = 1'b0; case (op) - CMD_LAUNCH: return RES_KMU; + CMD_LAUNCH, CMD_LAUNCH_QMD, + CMD_LAUNCH_INDIRECT: return RES_KMU; CMD_DCR_WRITE, CMD_DCR_READ, CMD_CACHE_FLUSH: return RES_DCR; CMD_MEM_WRITE, @@ -141,6 +149,7 @@ module VX_cp_engine cur_res <= RES_KMU; no_resource <= 1'b0; seqnum_r <= '0; + skip_cnt <= '0; end else if (clear) begin // Only asserted while `idle` holds — see VX_cp_core. fsm <= S_IDLE; @@ -148,6 +157,7 @@ module VX_cp_engine cur_res <= RES_KMU; no_resource <= 1'b0; seqnum_r <= '0; + skip_cnt <= '0; end else begin case (fsm) S_IDLE: begin @@ -160,7 +170,10 @@ module VX_cp_engine res = classify(cp_opcode_e'(cur_cmd.hdr.opcode), skip_flag); cur_res <= res; no_resource <= skip_flag; - if (skip_flag) begin + if (skip_cnt != '0) begin + skip_cnt <= skip_cnt - 16'd1; + fsm <= S_RETIRE; + end else if (skip_flag) begin fsm <= S_RETIRE; end else begin fsm <= S_BID; @@ -179,7 +192,14 @@ module VX_cp_engine S_WAIT_DONE: begin // Wait for the resource's actual done pulse before retiring. case (cur_res) - RES_KMU: if (kmu_done_i) fsm <= S_RETIRE; + RES_KMU: begin + if (kmu_done_i) begin + if (kmu_skip_i) begin + skip_cnt <= kmu_skip_n_i; + end + fsm <= S_RETIRE; + end + end RES_DMA: if (dma_done_i) fsm <= S_RETIRE; RES_DCR: if (dcr_done_i) fsm <= S_RETIRE; RES_EVT: if (event_done_i) fsm <= S_RETIRE; diff --git a/hw/rtl/cp/VX_cp_launch.sv b/hw/rtl/cp/VX_cp_launch.sv deleted file mode 100644 index 32751bace6..0000000000 --- a/hw/rtl/cp/VX_cp_launch.sv +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright © 2019-2023 -// Licensed under the Apache License, Version 2.0. - -`include "VX_define.vh" - -// ============================================================================ -// VX_cp_launch — KMU start/busy wrapper. Owned by the KMU resource arbiter. -// -// KMU arbitration holds for the entire duration of a launch: -// IDLE : no grant yet -// PULSE_START : grant just observed; assert `start` for one cycle -// WAIT_BUSY : Vortex pulls `busy` high (kernel started) -// WAIT_DRAIN : Vortex drops `busy` low (kernel done) → fire `done`, -// go back to IDLE -// -// The CPE that won the KMU arbiter holds its bid across all of these -// states; `done` releasing the bid lets the next CPE take its turn. -// -// `grant` is the OR of per-CPE grants from the KMU arbiter (the CP core -// glues all N bids onto this single input). -// ============================================================================ - -module VX_cp_launch ( - input wire clk, - input wire reset, - - input wire grant, // OR of per-CPE grants from KMU arbiter - output logic start, // pulsed to gpu_if.start (Vortex) - input wire gpu_busy, // from gpu_if.busy (Vortex) - output logic done // back to engine: launch fully drained -); - - typedef enum logic [1:0] { - S_IDLE, - S_PULSE_START, - S_WAIT_BUSY, - S_WAIT_DRAIN - } state_e; - - state_e state; - - always_ff @(posedge clk) begin - if (reset) begin - state <= S_IDLE; - end else begin - case (state) - S_IDLE: begin - if (grant) state <= S_PULSE_START; - end - S_PULSE_START: begin - state <= S_WAIT_BUSY; - end - S_WAIT_BUSY: begin - // Vortex's busy might rise the next cycle after `start` fires; - // we wait for that rising edge. - if (gpu_busy) state <= S_WAIT_DRAIN; - end - S_WAIT_DRAIN: begin - if (!gpu_busy) state <= S_IDLE; - end - default: state <= S_IDLE; - endcase - end - end - - always_comb begin - start = (state == S_PULSE_START); - done = (state == S_WAIT_DRAIN) && !gpu_busy; - end - -endmodule : VX_cp_launch diff --git a/hw/rtl/cp/VX_cp_launch_seq.sv b/hw/rtl/cp/VX_cp_launch_seq.sv new file mode 100644 index 0000000000..3669d28673 --- /dev/null +++ b/hw/rtl/cp/VX_cp_launch_seq.sv @@ -0,0 +1,496 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +`include "VX_define.vh" + +// ============================================================================ +// VX_cp_launch_seq — KMU launch sequencer, owned by the KMU resource arbiter. +// +// CMD_LAUNCH start, wait for busy to rise and fall. +// CMD_LAUNCH_QMD replay the in-memory descriptor {count, reserved, +// count x (dcr_addr, value)} as DCR writes, then start. +// CMD_LAUNCH_INDIRECT read the 64-byte header line, then optionally a +// predicate word and a grid record; derive the grid +// (select, x bias and divide, ceil-shift); either skip +// (done + skip, skip_n), retire without a launch, or +// replay the descriptor body from line 1 with the grid +// substituted, then start. +// +// Every read is one 64-byte line (arlen 0), so no burst crosses a 4 KiB page, +// and sub-line words are selected by address. A read beat is held (rready +// low) while it is used -- the record's three words, the eight pair slots +// written out -- so no beat buffer is needed; a registered rready then +// releases it. A descriptor address that is not line aligned is not executed: +// the command finishes with `fault` and no DCR write or start. While replaying, `dcr_hold` keeps the DCR arbiter from granting and +// the replay waits for the DCR proxy to go idle, so no other DCR command can +// interleave with a launch descriptor. +// ============================================================================ + +module VX_cp_launch_seq + import VX_cp_pkg::*; +#( + parameter int ADDR_W = 64, + parameter int DATA_W = 512, + parameter int ID_W = VX_CP_AXI_TID_WIDTH_C, + parameter logic [ID_W-1:0] TID_PREFIX = '0 +) ( + input wire clk, + input wire reset, + + input wire grant, + input cmd_t cmd, + output logic done, + output logic skip, + output logic [15:0] skip_n, + output logic fault, + + output logic dcr_hold, + input wire dcr_proxy_idle, + output logic dcr_req_valid, + output logic [`VX_DCR_ADDR_BITS-1:0] dcr_req_addr, + output logic [`VX_DCR_DATA_BITS-1:0] dcr_req_data, + input wire dcr_req_ready, + + output logic start, + input wire gpu_busy, + + VX_mem_axi_if.master axi_m +); + `STATIC_ASSERT(DATA_W == CL_BITS, ("invalid parameter: DATA_W=%0d", DATA_W)) + + localparam int LINE_LG = $clog2(CL_BYTES); + `STATIC_ASSERT(LINE_LG == LAUNCH_DESC_ALIGN_LG, ("descriptors are one line aligned")) + localparam int MAX_PAIRS = 64; + localparam int CNT_W = $clog2(MAX_PAIRS + 1); + // Cycles for the last replayed DCR write to reach Vortex ahead of start: + // the request path is an elastic buffer, the start path a single register. + localparam int SETTLE = 3; + + typedef enum logic [4:0] { + S_IDLE, + S_HDR_AR, + S_HDR_R, + S_PRED_AR, + S_PRED_R, + S_REC_AR, + S_REC_R, + S_GRID, + S_DIV, + S_SHIFT, + S_EVAL, + S_DCR_ACQ, + S_BODY_AR, + S_BODY_R, + S_START, + S_WAIT_BUSY, + S_WAIT_DRAIN + } state_e; + + state_e state; + + // Descriptor fields. + logic op_qmd; + logic qmd_first; + logic [ILD_CTL_W-1:0] ild_ctl; + logic [15:0] ild_skip_n; + logic [ADDR_W-1:0] rec_addr; + logic [ADDR_W-1:0] pred_addr; + logic [31:0] pred_ref; + logic [31:0] x_bias; + logic [31:0] x_div; + + logic [ADDR_W-1:0] line_addr; + logic rec_beat; + logic [1:0] dim; + logic [2:0] slot; + logic [CNT_W-1:0] pairs_left; + logic [SETTLE-1:0] settle; + logic exec; + logic fault_r; + logic rready_r; + logic [2:0][31:0] grid; + + wire has_record = ild_ctl[ILD_CTL_HAS_RECORD]; + wire pred_inv = ild_ctl[ILD_CTL_PRED_INV]; + wire no_launch = ild_ctl[ILD_CTL_NO_LAUNCH]; + + wire [3:0] sel_d = ild_ctl[ILD_CTL_SEL_LSB + 4 * dim +: 4]; + wire [3:0] shift_d = ild_ctl[ILD_CTL_SHIFT_LSB + 4 * dim +: 4]; + wire sel_one = (sel_d == ILD_SEL_ONE); + + // The held read beat, until the registered rready releases it. + wire beat = axi_m.rvalid && !rready_r; + + function automatic logic [31:0] hdr_word(input logic [DATA_W-1:0] line, + input int off); + return line[off * 8 +: 32]; + endfunction + + // Word position of the current dimension: bit 4 picks the line. + wire [4:0] rec_pos = {1'b0, rec_addr[5:2]} + {1'b0, sel_d}; + + function automatic logic [31:0] line_word(input logic [DATA_W-1:0] line, + input logic [3:0] idx); + return line[idx * 32 +: 32]; + endfunction + + // A record needs its second line when any used word lands past the first. + logic need_beat1; + always_comb begin + need_beat1 = 1'b0; + for (int d = 0; d < 3; ++d) begin + if ((ild_ctl[ILD_CTL_SEL_LSB + 4 * d +: 4] != ILD_SEL_ONE) + && ((5'(rec_addr[5:2]) + 5'(ild_ctl[ILD_CTL_SEL_LSB + 4 * d +: 4])) >= 5'd16)) begin + need_beat1 = 1'b1; + end + end + end + + // ---- x divider --------------------------------------------------------- + logic div_strobe; + wire div_busy; + wire [31:0] div_quot; + logic [31:0] grid_v; + + VX_serial_div #( + .WIDTHN (32), + .WIDTHD (32), + .WIDTHQ (32), + .WIDTHR (32), + .LANES (1) + ) x_divider ( + .clk (clk), + .reset (reset), + .strobe (div_strobe), + .busy (div_busy), + .is_signed (1'b0), + .numer (grid_v), + .denom (x_div), + .quotient (div_quot), + `UNUSED_PIN (remainder) + ); + + // Selected (and for x, biased) value of the current dimension. + always_comb begin + grid_v = sel_one ? 32'd1 : grid[dim]; + if (dim == 2'd0) begin + grid_v = (grid_v > x_bias) ? (grid_v - x_bias) : 32'd0; + end + end + + wire use_div = (dim == 2'd0) && (x_div > 32'd1); + assign div_strobe = (state == S_GRID) && use_div; + + // ceil(v / 2^shift) of the current dimension. + wire [32:0] ceil_sum = {1'b0, grid[dim]} + {1'b0, (32'd1 << shift_d) - 32'd1}; + wire [31:0] ceil_shift = 32'(ceil_sum >> shift_d); + + // ---- body pair replay -------------------------------------------------- + wire [63:0] pair = axi_m.rdata[slot * 64 +: 64]; + wire [`VX_DCR_ADDR_BITS-1:0] pair_addr = pair[`VX_DCR_ADDR_BITS-1:0]; + wire is_grid = has_record && !op_qmd + && (pair_addr >= `VX_DCR_ADDR_BITS'(`VX_DCR_KMU_GRID_DIM_X)) + && (pair_addr <= `VX_DCR_ADDR_BITS'(`VX_DCR_KMU_GRID_DIM_Z)); + wire [1:0] grid_idx = 2'(pair_addr - `VX_DCR_ADDR_BITS'(`VX_DCR_KMU_GRID_DIM_X)); + wire [31:0] pair_data = is_grid ? grid[grid_idx] : pair[63:32]; + `UNUSED_VAR (pair[31:`VX_DCR_ADDR_BITS]) + + // Registered DCR request stage (the sequencer's outgoing DCR interface). + wire out_ready = !dcr_req_valid || dcr_req_ready; + wire emit = (state == S_BODY_R) && beat && !qmd_first + && (pairs_left != '0) && out_ready; + wire last_pair = (pairs_left == CNT_W'(1)); + wire beat_end = emit && (last_pair || (slot == 3'd7)); + + wire [31:0] qmd_count = axi_m.rdata[31:0]; + wire [31:0] hdr_ctl = hdr_word(axi_m.rdata, ILD_OFF_CTL); + wire misaligned = (cmd.arg0[LINE_LG-1:0] != '0) + && ((cmd.hdr.opcode == 8'(CMD_LAUNCH_QMD)) + || (cmd.hdr.opcode == 8'(CMD_LAUNCH_INDIRECT))); + wire [CNT_W-1:0] qmd_pairs = (qmd_count > 32'(MAX_PAIRS)) ? CNT_W'(MAX_PAIRS) + : CNT_W'(qmd_count); + + always_ff @(posedge clk) begin + if (reset) begin + dcr_req_valid <= 1'b0; + end else if (out_ready) begin + dcr_req_valid <= emit; + end + if (out_ready && emit) begin + dcr_req_addr <= pair_addr; + dcr_req_data <= pair_data; + end + end + + // ---- FSM --------------------------------------------------------------- + always_ff @(posedge clk) begin + if (reset) begin + state <= S_IDLE; + op_qmd <= 1'b0; + qmd_first <= 1'b0; + ild_ctl <= '0; + ild_skip_n <= '0; + exec <= 1'b0; + fault_r <= 1'b0; + rready_r <= 1'b0; + dim <= '0; + slot <= '0; + pairs_left <= '0; + rec_beat <= 1'b0; + settle <= '0; + end else begin + rready_r <= 1'b0; + case (state) + S_IDLE: begin + if (grant) begin + line_addr <= {cmd.arg0[ADDR_W-1:LINE_LG], LINE_LG'(0)}; + op_qmd <= (cmd.hdr.opcode == 8'(CMD_LAUNCH_QMD)); + qmd_first <= (cmd.hdr.opcode == 8'(CMD_LAUNCH_QMD)); + ild_ctl <= '0; + exec <= 1'b1; + slot <= '0; + // Nothing was replayed ahead of a plain launch. + settle <= '1; + fault_r <= misaligned; + if (misaligned) begin + state <= S_EVAL; + end else begin + case (cmd.hdr.opcode) + 8'(CMD_LAUNCH_QMD): state <= S_DCR_ACQ; + 8'(CMD_LAUNCH_INDIRECT): state <= S_HDR_AR; + default: state <= S_START; + endcase + end + end + end + S_HDR_AR: begin + if (axi_m.arready) begin + state <= S_HDR_R; + end + end + S_HDR_R: begin + if (beat) begin + ild_ctl <= ILD_CTL_W'(hdr_ctl); + ild_skip_n <= 16'(hdr_word(axi_m.rdata, ILD_OFF_SKIP)); + rec_addr <= axi_m.rdata[ILD_OFF_RECORD * 8 +: ADDR_W]; + pred_addr <= axi_m.rdata[ILD_OFF_PRED * 8 +: ADDR_W]; + pred_ref <= hdr_word(axi_m.rdata, ILD_OFF_PRED_REF); + pairs_left <= (hdr_word(axi_m.rdata, ILD_OFF_COUNT) > 32'(MAX_PAIRS)) + ? CNT_W'(MAX_PAIRS) : CNT_W'(hdr_word(axi_m.rdata, ILD_OFF_COUNT)); + x_bias <= hdr_word(axi_m.rdata, ILD_OFF_X_BIAS); + x_div <= hdr_word(axi_m.rdata, ILD_OFF_X_DIV); + line_addr <= line_addr + ADDR_W'(CL_BYTES); + rec_beat <= 1'b0; + dim <= '0; + rready_r <= 1'b1; + if (hdr_ctl[ILD_CTL_HAS_PRED]) begin + state <= S_PRED_AR; + end else if (hdr_ctl[ILD_CTL_HAS_RECORD]) begin + state <= S_REC_AR; + end else begin + state <= S_EVAL; + end + end + end + S_PRED_AR: begin + if (axi_m.arready) begin + state <= S_PRED_R; + end + end + S_PRED_R: begin + if (beat) begin + rready_r <= 1'b1; + exec <= (line_word(axi_m.rdata, pred_addr[5:2]) > pred_ref) ^ pred_inv; + if (((line_word(axi_m.rdata, pred_addr[5:2]) > pred_ref) ^ pred_inv) + && has_record) begin + state <= S_REC_AR; + end else begin + state <= S_EVAL; + end + end + end + S_REC_AR: begin + if (axi_m.arready) begin + state <= S_REC_R; + end + end + S_REC_R: begin + // One dimension per cycle from the held beat. + if (beat) begin + if (!sel_one && (rec_pos[4] == rec_beat)) begin + grid[dim] <= line_word(axi_m.rdata, rec_pos[3:0]); + end + if (dim == 2'd2) begin + dim <= '0; + rready_r <= 1'b1; + if (!rec_beat && need_beat1) begin + rec_beat <= 1'b1; + state <= S_REC_AR; + end else begin + state <= S_GRID; + end + end else begin + dim <= dim + 2'd1; + end + end + end + S_GRID: begin + // Select and bias, then divide (x only) or go to the shift. + grid[dim] <= grid_v; + state <= use_div ? S_DIV : S_SHIFT; + end + S_DIV: begin + if (!div_busy) begin + grid[0] <= div_quot; + state <= S_SHIFT; + end + end + S_SHIFT: begin + grid[dim] <= ceil_shift; + if (ceil_shift == 32'd0) begin + exec <= 1'b0; + end + if (dim == 2'd2) begin + state <= S_EVAL; + end else begin + dim <= dim + 2'd1; + state <= S_GRID; + end + end + S_EVAL: begin + if (!exec || no_launch || fault_r) begin + state <= S_IDLE; + end else begin + state <= S_DCR_ACQ; + end + end + S_DCR_ACQ: begin + if (dcr_proxy_idle) begin + if (!op_qmd && (pairs_left == '0)) begin + state <= S_START; + end else begin + state <= S_BODY_AR; + end + end + end + S_BODY_AR: begin + if (axi_m.arready) begin + state <= S_BODY_R; + end + end + S_BODY_R: begin + if (beat && qmd_first) begin + qmd_first <= 1'b0; + pairs_left <= qmd_pairs; + slot <= 3'(QMD_PAIRS_SLOT); + if (qmd_pairs == '0) begin + rready_r <= 1'b1; + state <= S_START; + end + end else if (emit) begin + pairs_left <= pairs_left - CNT_W'(1); + slot <= slot + 3'd1; + if (beat_end) begin + rready_r <= 1'b1; + end + if (last_pair) begin + state <= S_START; + end else if (slot == 3'd7) begin + line_addr <= line_addr + ADDR_W'(CL_BYTES); + state <= S_BODY_AR; + end + end + end + S_START: begin + // Wait for the replayed writes to drain toward Vortex. + if (dcr_req_valid) begin + settle <= '0; + end else if (!settle[SETTLE-1]) begin + settle <= {settle[SETTLE-2:0], 1'b1}; + end else begin + settle <= '0; + state <= S_WAIT_BUSY; + end + end + S_WAIT_BUSY: begin + if (gpu_busy) begin + state <= S_WAIT_DRAIN; + end + end + S_WAIT_DRAIN: begin + if (!gpu_busy) begin + state <= S_IDLE; + end + end + default: state <= S_IDLE; + endcase + end + end + + wire eval_retire = (state == S_EVAL) && (!exec || no_launch || fault_r); + + always_comb begin + start = (state == S_START) && !dcr_req_valid && settle[SETTLE-1]; + done = ((state == S_WAIT_DRAIN) && !gpu_busy) || eval_retire; + skip = eval_retire && !exec; + fault = eval_retire && fault_r; + skip_n = ild_skip_n; + dcr_hold = (state == S_DCR_ACQ) || (state == S_BODY_AR) || (state == S_BODY_R) + || (state == S_START); + + axi_m.arvalid = (state == S_HDR_AR) || (state == S_PRED_AR) + || (state == S_REC_AR) || (state == S_BODY_AR); + case (state) + S_PRED_AR: axi_m.araddr = {pred_addr[ADDR_W-1:LINE_LG], LINE_LG'(0)}; + S_REC_AR: axi_m.araddr = {rec_addr[ADDR_W-1:LINE_LG], LINE_LG'(0)} + + (rec_beat ? ADDR_W'(CL_BYTES) : ADDR_W'(0)); + default: axi_m.araddr = line_addr; + endcase + axi_m.arid = TID_PREFIX; + axi_m.arlen = 8'd0; + axi_m.arsize = 3'(LINE_LG); + axi_m.arburst = 2'b01; + + axi_m.rready = rready_r; + + axi_m.awvalid = 1'b0; + axi_m.awaddr = '0; + axi_m.awid = TID_PREFIX; + axi_m.awlen = 8'd0; + axi_m.awsize = 3'(LINE_LG); + axi_m.awburst = 2'b01; + axi_m.wvalid = 1'b0; + axi_m.wdata = '0; + axi_m.wstrb = '0; + axi_m.wlast = 1'b0; + axi_m.bready = 1'b0; + end + + `UNUSED_VAR (rec_addr[1:0]) + `UNUSED_VAR (pred_addr[1:0]) + `UNUSED_VAR (cmd.hdr.flags) + `UNUSED_VAR (cmd.hdr.reserved) + `UNUSED_VAR (cmd.arg0[LINE_LG-1:0]) + `UNUSED_VAR (cmd.arg1) + `UNUSED_VAR (cmd.arg2) + `UNUSED_VAR (cmd.profile_slot) + `UNUSED_VAR (axi_m.awready) + `UNUSED_VAR (axi_m.wready) + `UNUSED_VAR (axi_m.bvalid) + `UNUSED_VAR (axi_m.bid) + `UNUSED_VAR (axi_m.bresp) + `UNUSED_VAR (axi_m.rid) + `UNUSED_VAR (axi_m.rlast) + `UNUSED_VAR (axi_m.rresp) + +endmodule : VX_cp_launch_seq diff --git a/hw/rtl/cp/VX_cp_pkg.sv b/hw/rtl/cp/VX_cp_pkg.sv index 01edf50a83..7fdd1a7d9c 100644 --- a/hw/rtl/cp/VX_cp_pkg.sv +++ b/hw/rtl/cp/VX_cp_pkg.sv @@ -71,9 +71,43 @@ package VX_cp_pkg; CMD_FENCE = 8'h07, CMD_EVENT_SIGNAL = 8'h08, CMD_EVENT_WAIT = 8'h09, - CMD_CACHE_FLUSH = 8'h0A + CMD_CACHE_FLUSH = 8'h0A, + CMD_LAUNCH_QMD = 8'h0B, + CMD_LAUNCH_INDIRECT = 8'h0D } cp_opcode_e; + // ------------------------------------------------------------------------ + // Launch descriptors (CMD_LAUNCH_QMD / CMD_LAUNCH_INDIRECT): line aligned, + // {dcr_addr, value} pairs on 8-byte slots. + // QMD: slot 0 = {reserved, count}, pairs from slot 1. + // ILD: a 64-byte header line, pairs from the next line; header fields at + // the byte offsets below. + // ------------------------------------------------------------------------ + + localparam int LAUNCH_DESC_ALIGN_LG = 6; + localparam int QMD_PAIRS_SLOT = 1; + + localparam int ILD_OFF_CTL = 0; + localparam int ILD_OFF_SKIP = 4; + localparam int ILD_OFF_RECORD = 8; + localparam int ILD_OFF_PRED = 16; + localparam int ILD_OFF_PRED_REF = 24; + localparam int ILD_OFF_COUNT = 28; + localparam int ILD_OFF_X_BIAS = 32; + localparam int ILD_OFF_X_DIV = 36; + + localparam int ILD_CTL_W = 28; + localparam int ILD_CTL_SEL_LSB = 0; // 3 x 4-bit word select, 0xF = 1 + localparam int ILD_CTL_SHIFT_LSB = 12; // 3 x 4-bit ceil-shift + localparam int ILD_CTL_HAS_RECORD = 24; + localparam int ILD_CTL_HAS_PRED = 25; + localparam int ILD_CTL_PRED_INV = 26; + localparam int ILD_CTL_NO_LAUNCH = 27; + localparam logic [3:0] ILD_SEL_ONE = 4'hF; + + // Q_ERROR bits. + localparam int Q_ERROR_DESC_ALIGN = 0; // a descriptor was not line aligned + // ------------------------------------------------------------------------ // Header flag bits. // ------------------------------------------------------------------------ @@ -174,7 +208,9 @@ package VX_cp_pkg; CMD_FENCE, CMD_EVENT_SIGNAL, CMD_EVENT_WAIT, - CMD_CACHE_FLUSH: return 1'b1; + CMD_CACHE_FLUSH, + CMD_LAUNCH_QMD, + CMD_LAUNCH_INDIRECT: return 1'b1; default: return 1'b0; endcase endfunction @@ -190,6 +226,8 @@ package VX_cp_pkg; CMD_LAUNCH: base = 12; CMD_FENCE: base = 8; CMD_CACHE_FLUSH: base = 12; + CMD_LAUNCH_QMD: base = 12; + CMD_LAUNCH_INDIRECT: base = 12; CMD_DCR_WRITE: base = 20; CMD_DCR_READ: base = 20; CMD_EVENT_SIGNAL: base = 20; diff --git a/hw/unittest/Makefile b/hw/unittest/Makefile index 7e708caadc..ee934ec44d 100644 --- a/hw/unittest/Makefile +++ b/hw/unittest/Makefile @@ -74,6 +74,18 @@ run: $(MAKE) -C mem_req_pending run $(MAKE) -C cache_init_eq run +# Command processor blocks only — executed (not just built) so CI gates the CP. +run-cp: + $(MAKE) -C cp_arbiter run + $(MAKE) -C cp_engine run + $(MAKE) -C cp_launch run + $(MAKE) -C cp_dcr_proxy run + $(MAKE) -C cp_unpack run + $(MAKE) -C cp_axil_regfile run + $(MAKE) -C cp_axi_path run + $(MAKE) -C cp_dma run + $(MAKE) -C cp_core run + # FPU arithmetic units only — executed (not just built) so CI gates correctness. run-fpu: $(MAKE) -C fma_unit run diff --git a/hw/unittest/cp_core/main.cpp b/hw/unittest/cp_core/main.cpp index 1a0e4946f7..1fa730b987 100644 --- a/hw/unittest/cp_core/main.cpp +++ b/hw/unittest/cp_core/main.cpp @@ -29,6 +29,13 @@ // NOP retires without bidding for any resource, so this exercises the // regfile → fetch → unpack → engine → completion path without touching // the launch or DMA paths. +// +// A second ring then runs launch descriptors read over the device master: +// an indirect launch whose grid comes from a device record, a predicated-off +// indirect launch that skips the next two commands, a DCR write and a QMD +// launch after the skip range, and a predicate-only command. The DCR writes +// and start pulses seen at the GPU boundary, and the completion count, must +// match exactly. // ============================================================================ #include "vl_simulator.h" @@ -38,6 +45,8 @@ #include #include #include +#include +#include #ifndef TRACE_START_TIME #define TRACE_START_TIME 0ull @@ -152,12 +161,70 @@ struct AxiSlave { } }; +// ============================================================================ +// Device-memory AXI4 read slave (the d_* master): one outstanding line read. +// ============================================================================ +struct DevSlave { + static constexpr uint64_t MEM_BASE = 0x40000; + static constexpr int MEM_SIZE = 16 * 1024; + uint8_t mem[MEM_SIZE] = {0}; + bool r_inflight = false; + uint64_t r_addr = 0; + uint32_t r_id = 0; + int reads = 0; + bool bad_read = false; + + void wr32(uint64_t addr, uint32_t v) { + std::memcpy(&mem[addr - MEM_BASE], &v, 4); + } + void wr64(uint64_t addr, uint64_t v) { + std::memcpy(&mem[addr - MEM_BASE], &v, 8); + } + template + void comb_drive(T* top) { + top->d_arready = !r_inflight; + top->d_rvalid = r_inflight; + top->d_rid = r_id; + top->d_rlast = 1; + top->d_rresp = 0; + if (r_inflight) { + uint32_t* d = vortex::VDataCastd_rdata)>::get(top->d_rdata); + for (int w = 0; w < 16; ++w) { + std::memcpy(&d[w], &mem[r_addr - MEM_BASE + 4 * w], 4); + } + } + top->d_awready = 0; + top->d_wready = 0; + top->d_bvalid = 0; + top->d_bid = 0; + top->d_bresp = 0; + } + template + void posedge_update(T* top) { + if (top->d_arvalid && top->d_arready) { + const uint64_t a = top->d_araddr; + if ((a & 63) != 0 || a < MEM_BASE || a + 64 > MEM_BASE + MEM_SIZE) { + bad_read = true; + } else { + r_inflight = true; + r_addr = a; + r_id = top->d_arid; + ++reads; + } + } else if (r_inflight && top->d_rvalid && top->d_rready) { + r_inflight = false; + } + } +}; + // ============================================================================ // Synthetic gpu_if model. Pulses dcr_req_ready always; pulses busy for -// a few cycles after start. dcr_rsp is unused in this NOP test. +// a few cycles after start; records every DCR write and start. // ============================================================================ struct GpuModel { int busy_cnt = 0; + int starts = 0; + std::vector> writes; template void comb_drive(T* top) { top->gpu_dcr_req_ready = 1; @@ -167,26 +234,39 @@ struct GpuModel { } template void posedge_update(T* top) { - if (top->gpu_start) busy_cnt = 4; - else if (busy_cnt > 0) busy_cnt--; + if (top->gpu_dcr_req_valid && top->gpu_dcr_req_rw) { + writes.push_back({uint32_t(top->gpu_dcr_req_addr), uint32_t(top->gpu_dcr_req_data)}); + } + if (top->gpu_start) { + busy_cnt = 4; + ++starts; + } else if (busy_cnt > 0) { + busy_cnt--; + } } }; +DevSlave g_dev; + template static void cycle(vl_simulator& sim, AxiSlave& slave, GpuModel& gpu, uint64_t& tick) { auto* top = sim.operator->(); slave.comb_drive(top); gpu.comb_drive(top); + g_dev.comb_drive(top); top->eval(); slave.comb_drive(top); gpu.comb_drive(top); + g_dev.comb_drive(top); top->eval(); slave.posedge_update(top); gpu.posedge_update(top); + g_dev.posedge_update(top); tick = sim.step(tick, 2); slave.comb_drive(top); gpu.comb_drive(top); + g_dev.comb_drive(top); top->eval(); } @@ -250,6 +330,7 @@ static constexpr uint16_t Q_TAIL_LO = 0x20; static constexpr uint16_t Q_TAIL_HI = 0x24; static constexpr uint16_t Q_SEQNUM = 0x28; static constexpr uint16_t Q_HEAD_LO = 0x2C; +static constexpr uint16_t Q_ERROR = 0x2C; int main(int argc, char** argv) { Verilated::commandArgs(argc, argv); @@ -267,6 +348,7 @@ int main(int argc, char** argv) { { uint32_t v = axil_read(sim, slave, gpu, tick, CP_DEV_CAPS); EXPECT((v & 0xff) == 1, "DEV_CAPS NUM_QUEUES"); + EXPECT((v >> 24) == 0x14, "DEV_CAPS must advertise QMD (26) and INDIRECT (28) only"); } // ----- Seed memory: a single NOP+F_PROFILE at ring_base ----- @@ -363,7 +445,128 @@ int main(int argc, char** argv) { EXPECT((ctrl_after & 1) == 0, "Q_CONTROL.reset did not clear enable"); } + // ----- Launch descriptors over the device master ----- + { + constexpr uint64_t ILD_A = DevSlave::MEM_BASE + 0x0000; + constexpr uint64_t ILD_B = DevSlave::MEM_BASE + 0x0400; + constexpr uint64_t ILD_C = DevSlave::MEM_BASE + 0x0800; + constexpr uint64_t QMD = DevSlave::MEM_BASE + 0x0C00; + constexpr uint64_t REC = DevSlave::MEM_BASE + 0x1038; // crosses a line + constexpr uint64_t PRED = DevSlave::MEM_BASE + 0x1104; + g_dev.wr32(REC + 0, 5); + g_dev.wr32(REC + 4, 2); + g_dev.wr32(REC + 8, 3); + g_dev.wr32(PRED, 1); + std::vector> want; + + // A: grid {5, 2, 3} from the record; GRID_DIM pairs carry placeholders. + auto put_hdr = [](uint64_t at, uint32_t ctl, uint16_t skip, uint64_t rec, + uint64_t pred, uint32_t ref, uint32_t count) { + g_dev.wr32(at + 0, ctl); + g_dev.wr32(at + 4, skip); + g_dev.wr64(at + 8, rec); + g_dev.wr64(at + 16, pred); + g_dev.wr32(at + 24, ref); + g_dev.wr32(at + 28, count); + }; + constexpr uint32_t HAS_RECORD = 1u << 24, HAS_PRED = 1u << 25, NO_LAUNCH = 1u << 27; + put_hdr(ILD_A, HAS_RECORD | (0u << 0) | (1u << 4) | (2u << 8), 0, REC, 0, 0, 10); + for (uint32_t i = 0; i < 10; ++i) { + const uint32_t a = 0x010 + i + (i >= 9 ? 9 : 0); // 0x10..0x18, then GRID_X.. + const uint32_t v = 0x100 + i; + g_dev.wr32(ILD_A + 64 + 8 * i, a); + g_dev.wr32(ILD_A + 68 + 8 * i, v); + } + g_dev.wr32(ILD_A + 64 + 8 * 9, 0x019); // GRID_DIM_X + for (uint32_t i = 0; i < 9; ++i) { + want.push_back({0x010 + i, 0x100 + i}); + } + want.push_back({0x019, 5}); + // B: predicate 1 > 1 is false: skip the next two commands. + put_hdr(ILD_B, HAS_PRED, 2, 0, PRED, 1, 3); + // QMD: three pairs. + g_dev.wr32(QMD + 0, 3); + for (uint32_t i = 0; i < 3; ++i) { + g_dev.wr32(QMD + 8 + 8 * i, 0x01A + i); + g_dev.wr32(QMD + 12 + 8 * i, 0x900 + i); + } + // C: predicate-only, 1 > 0 holds: retire without a launch. + put_hdr(ILD_C, HAS_PRED | NO_LAUNCH, 5, 0, PRED, 0, 0); + + auto put_cmd = [&](int slot, uint8_t op, uint64_t a0, uint64_t a1) { + uint8_t cl[64] = {0}; + cl[0] = op; + std::memcpy(cl + 4, &a0, 8); + std::memcpy(cl + 12, &a1, 8); + slave.mem_write_cl(RING_BASE + 64 * slot, cl); + }; + put_cmd(0, 0x0D, ILD_A, 0); // indirect launch + put_cmd(1, 0x0D, ILD_B, 0); // predicated off, skip 2 + put_cmd(2, 0x04, 0x0FF, 0xBAD); // skipped DCR write + put_cmd(3, 0x0B, QMD, 0); // skipped QMD launch + put_cmd(4, 0x04, 0x0FE, 0x77); // runs + put_cmd(5, 0x0B, QMD, 0); // runs + put_cmd(6, 0x0D, ILD_C, 0); // predicate-only + want.push_back({0x0FE, 0x77}); + for (uint32_t i = 0; i < 3; ++i) { + want.push_back({0x01A + i, 0x900 + i}); + } + + for (int i = 0; i < 8; ++i) { + slave.mem[CMPL_ADDR - AxiSlave::MEM_BASE + i] = 0xFF; + } + gpu.writes.clear(); + gpu.starts = 0; + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_RING_BASE_LO, (uint32_t)RING_BASE); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_RING_BASE_HI, 0); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_CMPL_ADDR_LO, (uint32_t)CMPL_ADDR); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_CMPL_ADDR_HI, 0); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_RING_SIZE_LOG2, 12); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_CONTROL, 1u | (2u << 2)); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_TAIL_LO, 7 * 64); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_TAIL_HI, 0); + + bool got = false; + for (int g = 0; g < 5000 && !got; ++g) { + cycle(sim, slave, gpu, tick); + got = (slave.mem_read64(CMPL_ADDR) == 7); + } + EXPECT(got, "launch ring did not retire 7 commands"); + for (int g = 0; g < 50; ++g) { + cycle(sim, slave, gpu, tick); + } + EXPECT(!g_dev.bad_read, "device read not a line inside device memory"); + EXPECT(gpu.starts == 2, "expected 2 starts"); + if (gpu.writes != want) { + for (auto& w : gpu.writes) { + std::fprintf(stderr, " dcr 0x%03x = 0x%x\n", w.first, w.second); + } + } + EXPECT(gpu.writes == want, "DCR writes at the GPU boundary differ"); + // A: header, record line 0, record line 1, 2 body lines; B: header, + // predicate; QMD: 1 line; C: header, predicate. + EXPECT(g_dev.reads == 10, "unexpected device read count"); + EXPECT(axil_read(sim, slave, gpu, tick, Q0_BASE + Q_ERROR) == 0, + "Q_ERROR set by well-formed descriptors"); + + // A descriptor off its line is refused: Q_ERROR bit 0, no read, no start. + put_cmd(7, 0x0D, ILD_A + 4, 0); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_TAIL_LO, 8 * 64); + axil_write(sim, slave, gpu, tick, Q0_BASE + Q_TAIL_HI, 0); + got = false; + for (int g = 0; g < 2000 && !got; ++g) { + cycle(sim, slave, gpu, tick); + got = (slave.mem_read64(CMPL_ADDR) == 8); + } + EXPECT(got, "misaligned descriptor did not retire"); + EXPECT(gpu.starts == 2, "misaligned descriptor started a kernel"); + EXPECT(g_dev.reads == 10, "misaligned descriptor was read"); + EXPECT(axil_read(sim, slave, gpu, tick, Q0_BASE + Q_ERROR) == 1, + "Q_ERROR does not report the misaligned descriptor"); + } + std::printf("PASSED — CP end-to-end: NOP retired, seqnum written to " - "cmpl_addr, Q_CONTROL.reset clears the queue\n"); + "cmpl_addr, Q_CONTROL.reset clears the queue; indirect, " + "skip, QMD and predicate-only launches over the device master\n"); return 0; } diff --git a/hw/unittest/cp_dcr_proxy/VX_cp_dcr_proxy_top.sv b/hw/unittest/cp_dcr_proxy/VX_cp_dcr_proxy_top.sv index 1de85c8b61..79a104c37f 100644 --- a/hw/unittest/cp_dcr_proxy/VX_cp_dcr_proxy_top.sv +++ b/hw/unittest/cp_dcr_proxy/VX_cp_dcr_proxy_top.sv @@ -41,6 +41,7 @@ module VX_cp_dcr_proxy_top .grant (grant), .cmd (cmd_typed), .done (done), + `UNUSED_PIN (idle), .last_rsp_data (last_rsp_data), .dcr_req_valid (dcr_req_valid), .dcr_req_rw (dcr_req_rw), diff --git a/hw/unittest/cp_engine/VX_cp_engine_top.sv b/hw/unittest/cp_engine/VX_cp_engine_top.sv index d041d535f8..582f23c80b 100644 --- a/hw/unittest/cp_engine/VX_cp_engine_top.sv +++ b/hw/unittest/cp_engine/VX_cp_engine_top.sv @@ -57,6 +57,8 @@ module VX_cp_engine_top // can simply tie these to the corresponding bid_*_grant inputs delayed // by one cycle. input wire kmu_done_i, + input wire kmu_skip_i, + input wire [15:0] kmu_skip_n_i, input wire dma_done_i, input wire dcr_done_i, input wire event_done_i, @@ -128,6 +130,8 @@ module VX_cp_engine_top .bid_dcr (bid_dcr_if), .bid_event (bid_event_if), .kmu_done_i (kmu_done_i), + .kmu_skip_i (kmu_skip_i), + .kmu_skip_n_i (kmu_skip_n_i), .dma_done_i (dma_done_i), .dcr_done_i (dcr_done_i), .event_done_i (event_done_i), diff --git a/hw/unittest/cp_engine/main.cpp b/hw/unittest/cp_engine/main.cpp index 770b4a4394..20a4d1897e 100644 --- a/hw/unittest/cp_engine/main.cpp +++ b/hw/unittest/cp_engine/main.cpp @@ -21,6 +21,11 @@ // 0x07 FENCE -> no bid, retires immediately // 0x08 EVENT_SIGNAL -> bid EVENT // 0x09 EVENT_WAIT -> bid EVENT +// 0x0B LAUNCH_QMD -> bid_kmu +// 0x0D LAUNCH_INDIRECT -> bid_kmu +// +// A KMU done with kmu_skip_i set makes the next kmu_skip_n_i commands retire +// from DECODE without bidding; the command after them bids normally. // // Also asserts: // - retire_seqnum monotonically increments by 1 per retired command @@ -74,8 +79,14 @@ enum CmdOp : uint8_t { OP_FENCE = 0x07, OP_EVT_SIG = 0x08, OP_EVT_WAIT = 0x09, + OP_LAUNCH_QMD = 0x0B, + OP_LAUNCH_IND = 0x0D, }; +// Skip report driven with the next KMU done pulse. +static bool g_kmu_skip = false; +static uint16_t g_kmu_skip_n = 0; + static constexpr uint8_t F_PROFILE_BIT = 0; static void pack_cmd(uint32_t out_words[9], @@ -208,12 +219,18 @@ static uint64_t run_one_cmd(vl_simulator& sim, uint64_t& tick, // ----- Cycle 4: WAIT_DONE -> pulse done -> RETIRE ----- // Engine waits for the resource's done pulse before retiring. // Simulate a one-cycle done pulse here. - if (expect_kmu) sim->kmu_done_i = 1; + if (expect_kmu) { + sim->kmu_done_i = 1; + sim->kmu_skip_i = g_kmu_skip ? 1 : 0; + sim->kmu_skip_n_i = g_kmu_skip_n; + } if (expect_dma) sim->dma_done_i = 1; if (expect_dcr) sim->dcr_done_i = 1; if (expect_event) sim->event_done_i = 1; cycle(sim, tick); sim->kmu_done_i = 0; + sim->kmu_skip_i = 0; + sim->kmu_skip_n_i = 0; sim->dma_done_i = 0; sim->dcr_done_i = 0; sim->event_done_i = 0; @@ -258,6 +275,8 @@ int main(int argc, char** argv) { sim->bid_dcr_grant = 0; sim->bid_event_grant = 0; sim->kmu_done_i = 0; + sim->kmu_skip_i = 0; + sim->kmu_skip_n_i = 0; sim->dma_done_i = 0; sim->dcr_done_i = 0; sim->event_done_i = 0; @@ -289,6 +308,27 @@ int main(int argc, char** argv) { seq = run_one_cmd(sim, tick, OP_MEM_COPY, 0, /*kmu=*/false, /*dma=*/true, /*dcr=*/false, /*event=*/false, seq); + // ----- LAUNCH_QMD / LAUNCH_INDIRECT bid KMU ----- + seq = run_one_cmd(sim, tick, OP_LAUNCH_QMD, 0, true, false, false, false, seq); + seq = run_one_cmd(sim, tick, OP_LAUNCH_IND, 0, true, false, false, false, seq); + + // ----- A predicated-off launch skips the next 3 commands of any kind ----- + g_kmu_skip = true; + g_kmu_skip_n = 3; + seq = run_one_cmd(sim, tick, OP_LAUNCH_IND, 0, true, false, false, false, seq); + g_kmu_skip = false; + g_kmu_skip_n = 0; + seq = run_one_cmd(sim, tick, OP_DCR_WRITE, 0, false, false, false, false, seq); + seq = run_one_cmd(sim, tick, OP_LAUNCH_QMD, 0, false, false, false, false, seq); + seq = run_one_cmd(sim, tick, OP_MEM_COPY, 0, false, false, false, false, seq); + seq = run_one_cmd(sim, tick, OP_DCR_WRITE, 0, false, false, true, false, seq); + + // ----- A skip count of zero skips nothing ----- + g_kmu_skip = true; + seq = run_one_cmd(sim, tick, OP_LAUNCH_IND, 0, true, false, false, false, seq); + g_kmu_skip = false; + seq = run_one_cmd(sim, tick, OP_LAUNCH, 0, true, false, false, false, seq); + // ----- FENCE skips (no resource); EVENT_SIGNAL / EVENT_WAIT bid EVENT ----- seq = run_one_cmd(sim, tick, OP_FENCE, 0, false, false, false, false, seq); seq = run_one_cmd(sim, tick, OP_EVT_SIG, 0, false, false, false, true, seq); diff --git a/hw/unittest/cp_launch/Makefile b/hw/unittest/cp_launch/Makefile index 5f04495e20..a3c6719230 100644 --- a/hw/unittest/cp_launch/Makefile +++ b/hw/unittest/cp_launch/Makefile @@ -15,14 +15,14 @@ SRCS := $(SRC_DIR)/main.cpp DBG_TRACE_FLAGS := -# VX_cp_launch is self-contained (plain scalar ports, no package types). -RTL_PKGS := $(RTL_DIR)/VX_gpu_pkg.sv $(RTL_DIR)/VX_trace_pkg.sv +RTL_PKGS := $(RTL_DIR)/VX_gpu_pkg.sv $(RTL_DIR)/VX_trace_pkg.sv \ + $(RTL_DIR)/cp/VX_cp_pkg.sv RTL_INCLUDE := -I$(ROOT_DIR)/sw -I$(ROOT_DIR)/hw -I$(RTL_DIR) -I$(DPI_DIR) \ -I$(RTL_DIR)/libs -I$(VORTEX_HOME)/hw/unittest/$(PROJECT) RTL_INCLUDE += -I$(RTL_DIR)/interfaces -I$(RTL_DIR)/mem -I$(RTL_DIR)/vm -I$(RTL_DIR)/fpu \ -I$(RTL_DIR)/core -I$(RTL_DIR)/cp -TOP := VX_cp_launch_top +TOP := VX_cp_launch_seq_top include ../common.mk diff --git a/hw/unittest/cp_launch/VX_cp_launch_seq_top.sv b/hw/unittest/cp_launch/VX_cp_launch_seq_top.sv new file mode 100644 index 0000000000..0c4a01820d --- /dev/null +++ b/hw/unittest/cp_launch/VX_cp_launch_seq_top.sv @@ -0,0 +1,113 @@ +// Copyright © 2019-2023 +// Licensed under the Apache License, Version 2.0. + +`include "VX_define.vh" + +// VX_cp_launch_seq_top — verilator-friendly wrapper around VX_cp_launch_seq: +// the command arrives packed, and the AXI read master is flattened. +module VX_cp_launch_seq_top + import VX_cp_pkg::*; +#( + parameter int ADDR_W = 64, + parameter int DATA_W = 512, + parameter int ID_W = VX_CP_AXI_TID_WIDTH_C +) ( + input wire clk, + input wire reset, + + input wire grant, + input wire [$bits(cmd_t)-1:0] cmd_packed, + output wire done, + output wire skip, + output wire [15:0] skip_n, + output wire fault, + + output wire dcr_hold, + input wire dcr_proxy_idle, + output wire dcr_req_valid, + output wire [`VX_DCR_ADDR_BITS-1:0] dcr_req_addr, + output wire [`VX_DCR_DATA_BITS-1:0] dcr_req_data, + input wire dcr_req_ready, + + output wire start, + input wire gpu_busy, + + output wire arvalid, + input wire arready, + output wire [ADDR_W-1:0] araddr, + output wire [ID_W-1:0] arid, + output wire [7:0] arlen, + output wire [2:0] arsize, + output wire [1:0] arburst, + input wire rvalid, + output wire rready, + input wire [DATA_W-1:0] rdata, + input wire [ID_W-1:0] rid, + input wire rlast, + input wire [1:0] rresp, + output wire awvalid, + output wire wvalid, + output wire bready +); + VX_mem_axi_if #( + .ADDR_W (ADDR_W), + .DATA_W (DATA_W), + .ID_W (ID_W) + ) axi (); + + VX_cp_launch_seq #( + .ADDR_W (ADDR_W), + .DATA_W (DATA_W), + .ID_W (ID_W) + ) u_dut ( + .clk (clk), + .reset (reset), + .grant (grant), + .cmd (cmd_t'(cmd_packed)), + .done (done), + .skip (skip), + .skip_n (skip_n), + .fault (fault), + .dcr_hold (dcr_hold), + .dcr_proxy_idle (dcr_proxy_idle), + .dcr_req_valid (dcr_req_valid), + .dcr_req_addr (dcr_req_addr), + .dcr_req_data (dcr_req_data), + .dcr_req_ready (dcr_req_ready), + .start (start), + .gpu_busy (gpu_busy), + .axi_m (axi) + ); + + assign arvalid = axi.arvalid; + assign axi.arready = arready; + assign araddr = axi.araddr; + assign arid = axi.arid; + assign arlen = axi.arlen; + assign arsize = axi.arsize; + assign arburst = axi.arburst; + assign axi.rvalid = rvalid; + assign rready = axi.rready; + assign axi.rdata = rdata; + assign axi.rid = rid; + assign axi.rlast = rlast; + assign axi.rresp = rresp; + assign awvalid = axi.awvalid; + assign wvalid = axi.wvalid; + assign bready = axi.bready; + assign axi.awready = 1'b0; + assign axi.wready = 1'b0; + assign axi.bvalid = 1'b0; + assign axi.bid = '0; + assign axi.bresp = '0; + + `UNUSED_VAR (axi.awaddr) + `UNUSED_VAR (axi.awid) + `UNUSED_VAR (axi.awlen) + `UNUSED_VAR (axi.awsize) + `UNUSED_VAR (axi.awburst) + `UNUSED_VAR (axi.wdata) + `UNUSED_VAR (axi.wstrb) + `UNUSED_VAR (axi.wlast) + +endmodule : VX_cp_launch_seq_top diff --git a/hw/unittest/cp_launch/VX_cp_launch_top.sv b/hw/unittest/cp_launch/VX_cp_launch_top.sv deleted file mode 100644 index 97da4c241f..0000000000 --- a/hw/unittest/cp_launch/VX_cp_launch_top.sv +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright © 2019-2023 -// Licensed under the Apache License, Version 2.0. - -`include "VX_define.vh" - -// ============================================================================ -// VX_cp_launch_top — verilator-friendly wrapper around VX_cp_launch. -// -// VX_cp_launch already has only plain scalar ports, so the wrapper just -// passes them through. It exists for consistency with the other unittest -// targets (each DUT has a *_top.sv harness). -// ============================================================================ - -module VX_cp_launch_top ( - input wire clk, - input wire reset, - input wire grant, - output wire start, - input wire gpu_busy, - output wire done -); - - VX_cp_launch u_dut ( - .clk (clk), - .reset (reset), - .grant (grant), - .start (start), - .gpu_busy (gpu_busy), - .done (done) - ); - -endmodule : VX_cp_launch_top diff --git a/hw/unittest/cp_launch/main.cpp b/hw/unittest/cp_launch/main.cpp index 8ce7129e98..275168aa39 100644 --- a/hw/unittest/cp_launch/main.cpp +++ b/hw/unittest/cp_launch/main.cpp @@ -2,30 +2,33 @@ // Licensed under the Apache License, Version 2.0. // ============================================================================ -// Verilator unit test for VX_cp_launch. +// Verilator unit test for VX_cp_launch_seq. // -// FSM under test: -// IDLE grant → PULSE_START -// PULSE_START one-cycle `start` pulse → WAIT_BUSY -// WAIT_BUSY gpu_busy ↑ → WAIT_DRAIN -// WAIT_DRAIN gpu_busy ↓ → done pulse → IDLE -// -// Coverage: -// 1. Reset → IDLE, no spurious start/done. -// 2. Long idle while grant=0 → no transition. -// 3. Full happy-path launch: grant → start pulse → busy rise → busy fall -// → done pulse → back to IDLE. -// 4. Re-arm: a second launch back-to-back after done. -// 5. WAIT_BUSY hangs indefinitely until busy actually rises (no premature -// done). -// 6. start is exactly 1 cycle wide. -// 7. done is exactly 1 cycle wide and only fires on the busy falling edge. +// The sequencer runs against: +// - an AXI read slave over a byte memory, with random AR stalls and read +// latency, that checks every read is one aligned 64-byte line; +// - a DCR sink with random back-pressure and a DCR proxy that is busy for a +// random time after the grant; +// - a GPU whose busy rises and falls a random time after start. +// Each command's DCR writes, start and done/skip outcome are compared with a +// reference model of the launch descriptors. Covered: plain launch; QMD with +// 0/1/7/8/18/64 pairs and a corrupt count; indirect launch with and without a +// predicate (true, false, inverted, every word offset), with a record (grid +// substitution, constant-1 select, shifts, a zero in each dimension, records +// crossing a line, word 14), x bias and divider corners (0, 1, 2, 7, +// 2^32-1), the predicate-only form, misaligned descriptors (refused with +// `fault`), and a randomized sweep. // ============================================================================ #include "vl_simulator.h" -#include "VVX_cp_launch_top.h" +#include "VVX_cp_launch_seq_top.h" +#include #include #include +#include +#include +#include +#include #ifndef TRACE_START_TIME #define TRACE_START_TIME 0ull @@ -40,103 +43,529 @@ double sc_time_stamp() { return timestamp; } bool sim_trace_enabled() { return trace_en; } void sim_trace_enable(bool e) { trace_en = e; } -#define EXPECT(cond, msg) do { \ +#define EXPECT(cond, ...) do { \ if (!(cond)) { \ - std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, msg); \ + std::fprintf(stderr, "FAIL %s:%d [%s]: ", __FILE__, __LINE__, g_case); \ + std::fprintf(stderr, __VA_ARGS__); \ + std::fprintf(stderr, "\n"); \ std::exit(1); \ } \ } while (0) -// Drive inputs, sample outputs for the current cycle, then advance one -// clock edge. Same convention used by cp_arbiter / cp_engine tests. -template -static void cycle(vl_simulator& sim, uint64_t& tick) { - sim->eval(); - tick = sim.step(tick, 2); +namespace { + +constexpr uint8_t OP_LAUNCH = 0x06; +constexpr uint8_t OP_LAUNCH_QMD = 0x0B; +constexpr uint8_t OP_LAUNCH_IND = 0x0D; +constexpr uint32_t DCR_GRID_X = 0x019; +constexpr uint32_t HAS_RECORD = 1u << 24; +constexpr uint32_t HAS_PRED = 1u << 25; +constexpr uint32_t PRED_INV = 1u << 26; +constexpr uint32_t NO_LAUNCH = 1u << 27; +constexpr uint32_t SEL_ONE = 0xF; +constexpr int SETTLE = 3; +constexpr size_t MEM_SIZE = 1u << 20; + +const char* g_case = ""; +std::mt19937 g_rng(1234); + +uint32_t rnd(uint32_t n) { + return std::uniform_int_distribution(0, n - 1)(g_rng); } -// Run one full launch sequence and verify start/done timing. busy_hold is -// how many cycles to keep gpu_busy=1 in WAIT_DRAIN before dropping it. -template -static void launch(vl_simulator& sim, uint64_t& tick, int busy_hold) { - // T0 IDLE with grant=1 → captures, transitions to PULSE_START at edge. - sim->grant = 1; - sim->gpu_busy = 0; - sim->eval(); - EXPECT(sim->start == 0, "start should be 0 in IDLE"); - EXPECT(sim->done == 0, "done should be 0 in IDLE"); - cycle(sim, tick); - - // T1 PULSE_START: start asserted for exactly this cycle. - sim->eval(); - EXPECT(sim->start == 1, "start pulse missing in PULSE_START"); - EXPECT(sim->done == 0, "done should be 0 in PULSE_START"); - cycle(sim, tick); - - // T2 WAIT_BUSY: start back low, still no done. gpu_busy stays low for - // a few cycles to verify we wait properly. - sim->grant = 0; // grant can drop now; FSM state holds - sim->eval(); - EXPECT(sim->start == 0, "start should fall after PULSE_START"); - EXPECT(sim->done == 0, "done in WAIT_BUSY should be 0"); - cycle(sim, tick); - - sim->eval(); - EXPECT(sim->start == 0, "start should stay 0 while waiting for busy"); - EXPECT(sim->done == 0, "done while busy hasn't risen should be 0"); - cycle(sim, tick); - - // Drive busy=1; FSM moves to WAIT_DRAIN at next edge. - sim->gpu_busy = 1; - cycle(sim, tick); - - // WAIT_DRAIN with busy still high — no done yet. - for (int i = 0; i < busy_hold; ++i) { +std::vector g_mem(MEM_SIZE, 0); + +void wr32(uint64_t a, uint32_t v) { std::memcpy(&g_mem[a], &v, 4); } +void wr64(uint64_t a, uint64_t v) { std::memcpy(&g_mem[a], &v, 8); } +uint32_t rd32(uint64_t a) { uint32_t v; std::memcpy(&v, &g_mem[a], 4); return v; } + +struct Pair { uint32_t addr, value; }; + +struct Ild { + uint32_t ctl = 0; + uint16_t skip_n = 0; + uint64_t rec = 0, pred = 0; + uint32_t ref = 0, bias = 0, div = 0; + std::vector pairs; + uint32_t count_override = ~0u; // corrupt count in the header +}; + +uint32_t ctl_sel(uint32_t x, uint32_t y, uint32_t z) { + return x | (y << 4) | (z << 8); +} + +uint32_t ctl_sh(uint32_t x, uint32_t y, uint32_t z) { + return (x << 12) | (y << 16) | (z << 20); +} + +void put_ild(uint64_t at, const Ild& d) { + std::memset(&g_mem[at], 0, 64); + wr32(at + 0, d.ctl); + wr32(at + 4, d.skip_n); + wr64(at + 8, d.rec); + wr64(at + 16, d.pred); + wr32(at + 24, d.ref); + wr32(at + 28, d.count_override != ~0u ? d.count_override : uint32_t(d.pairs.size())); + wr32(at + 32, d.bias); + wr32(at + 36, d.div); + for (size_t i = 0; i < d.pairs.size(); ++i) { + wr32(at + 64 + 8 * i, d.pairs[i].addr); + wr32(at + 68 + 8 * i, d.pairs[i].value); + } +} + +void put_qmd(uint64_t at, const std::vector& pairs, uint32_t count) { + wr32(at, count); + wr32(at + 4, 0xA5A5A5A5u); + for (size_t i = 0; i < pairs.size(); ++i) { + wr32(at + 8 + 8 * i, pairs[i].addr); + wr32(at + 12 + 8 * i, pairs[i].value); + } +} + +struct Outcome { + bool launch = false; + bool skip = false; + uint16_t skip_n = 0; + std::vector writes; + bool fault = false; +}; + +Outcome model_ild(uint64_t at) { + Outcome o; + const uint32_t ctl = rd32(at), skip_n = rd32(at + 4) & 0xFFFF; + uint64_t rec, pred; + std::memcpy(&rec, &g_mem[at + 8], 8); + std::memcpy(&pred, &g_mem[at + 16], 8); + const uint32_t ref = rd32(at + 24), bias = rd32(at + 32), div = rd32(at + 36); + uint32_t count = rd32(at + 28); + if (count > 64) { + count = 64; + } + bool exec = true; + if (ctl & HAS_PRED) { + exec = (rd32(pred) > ref) != ((ctl & PRED_INV) != 0); + } + uint32_t g[3] = {1, 1, 1}; + if (exec && (ctl & HAS_RECORD)) { + for (int d = 0; d < 3; ++d) { + const uint32_t sel = (ctl >> (4 * d)) & 0xF; + uint64_t v = (sel == SEL_ONE) ? 1 : rd32(rec + 4 * sel); + if (d == 0) { + v = (v > bias) ? v - bias : 0; + if (div > 1) { + v /= div; + } + } + const uint32_t sh = (ctl >> (12 + 4 * d)) & 0xF; + g[d] = uint32_t((v + (uint64_t(1) << sh) - 1) >> sh); + if (g[d] == 0) { + exec = false; + } + } + } + if (!exec) { + o.skip = true; + o.skip_n = uint16_t(skip_n); + return o; + } + if (ctl & NO_LAUNCH) { + return o; + } + for (uint32_t i = 0; i < count; ++i) { + uint32_t a = rd32(at + 64 + 8 * i) & 0xFFF, v = rd32(at + 68 + 8 * i); + if ((ctl & HAS_RECORD) && a >= DCR_GRID_X && a <= DCR_GRID_X + 2) { + v = g[a - DCR_GRID_X]; + } + o.writes.push_back({a, v}); + } + o.launch = true; + return o; +} + +Outcome model_qmd(uint64_t at) { + Outcome o; + uint32_t count = rd32(at); + if (count > 64) { + count = 64; + } + for (uint32_t i = 0; i < count; ++i) { + o.writes.push_back({rd32(at + 8 + 8 * i) & 0xFFF, rd32(at + 12 + 8 * i)}); + } + o.launch = true; + return o; +} + +using Sim = vl_simulator; + +void set_cmd(Sim& sim, uint8_t opcode, uint64_t arg0) { + for (int i = 0; i < 9; ++i) { + sim->cmd_packed[i] = 0; + } + sim->cmd_packed[6] = uint32_t(arg0); + sim->cmd_packed[7] = uint32_t(arg0 >> 32); + sim->cmd_packed[8] = opcode; +} + +struct Rsp { uint64_t addr; uint64_t ready_at; }; + +// Drive one command to completion and compare with `want`. +void run(Sim& sim, uint64_t& tick, uint8_t opcode, uint64_t arg0, const Outcome& want, + bool stress) { + std::deque rq; + std::vector writes; + uint64_t now = 0, last_write = 0, proxy_busy_until = stress ? rnd(12) : 0; + int starts = 0, dones = 0, reads = 0; + bool skipped = false, faulted = false; + uint16_t skip_n = 0; + bool busy = false, seen_idle_hold = false; + uint64_t busy_rise = 0, busy_fall = 0, fall_at = ~0ull; + bool fired = false; + + for (; now < 20000; ++now) { + sim->grant = (now == 0); + set_cmd(sim, opcode, arg0); + sim->arready = !stress || rnd(4) != 0; + bool rv = !rq.empty() && rq.front().ready_at <= now; + sim->rvalid = rv; + if (rv) { + const uint64_t a = rq.front().addr; + for (int w = 0; w < 16; ++w) { + sim->rdata[w] = rd32(a + 4 * w); + } + } + sim->rid = 0; + sim->rlast = 1; + sim->rresp = 0; + sim->dcr_req_ready = !stress || rnd(3) != 0; + sim->dcr_proxy_idle = (now >= proxy_busy_until); + if (busy_rise && now == busy_rise) { + busy = true; + } + if (busy && now == busy_fall) { + busy = false; + fall_at = now; + } + sim->gpu_busy = busy; sim->eval(); - EXPECT(sim->done == 0, "done fired prematurely while busy still high"); - cycle(sim, tick); + + EXPECT(!sim->awvalid && !sim->wvalid, "sequencer issued a write"); + if (sim->arvalid && sim->arready) { + const uint64_t a = sim->araddr; + EXPECT((a & 63) == 0, "AR address 0x%llx is not line aligned", (unsigned long long)a); + EXPECT(sim->arlen == 0 && sim->arsize == 6 && sim->arburst == 1, + "AR is not a single 64-byte INCR beat"); + EXPECT(a + 64 <= MEM_SIZE, "AR address 0x%llx out of range", (unsigned long long)a); + rq.push_back({a, now + 1 + (stress ? rnd(8) : 0)}); + ++reads; + } + if (rv && sim->rready) { + rq.pop_front(); + } + if (sim->dcr_hold && sim->dcr_proxy_idle) { + seen_idle_hold = true; + } + if (sim->dcr_req_valid && sim->dcr_req_ready) { + EXPECT(seen_idle_hold, "DCR write before the proxy went idle under hold"); + EXPECT(sim->dcr_hold, "DCR write without the DCR hold"); + writes.push_back({uint32_t(sim->dcr_req_addr), uint32_t(sim->dcr_req_data)}); + last_write = now; + } + if (sim->start) { + ++starts; + EXPECT(writes.size() == want.writes.size(), "start before the last DCR write"); + EXPECT(writes.empty() || now >= last_write + SETTLE, + "start %llu cycles after the last DCR write", + (unsigned long long)(now - last_write)); + busy_rise = now + 1 + (stress ? rnd(5) : 0); + busy_fall = busy_rise + 1 + (stress ? rnd(20) : 3); + } + if (sim->done) { + ++dones; + skipped = sim->skip; + skip_n = sim->skip_n; + faulted = sim->fault; + EXPECT(!want.launch || (fall_at == now), "done is not on the busy falling edge"); + fired = true; + } + tick = sim.step(tick, 2); + if (fired) { + break; + } + } + EXPECT(fired, "command never finished"); + EXPECT(rq.empty(), "read response left behind"); + EXPECT(dones == 1, "%d done pulses", dones); + EXPECT(starts == (want.launch ? 1 : 0), "%d start pulses, expected %d", starts, want.launch ? 1 : 0); + EXPECT(skipped == want.skip, "skip=%d, expected %d", skipped, want.skip); + EXPECT(faulted == want.fault, "fault=%d, expected %d", faulted, want.fault); + if (want.fault) { + EXPECT(reads == 0, "%d reads of a refused descriptor", reads); + } + if (want.skip) { + EXPECT(skip_n == want.skip_n, "skip_n=%u, expected %u", skip_n, want.skip_n); + } + EXPECT(writes.size() == want.writes.size(), "%zu DCR writes, expected %zu", + writes.size(), want.writes.size()); + for (size_t i = 0; i < writes.size(); ++i) { + EXPECT(writes[i].addr == want.writes[i].addr && writes[i].value == want.writes[i].value, + "DCR write %zu = (0x%x, 0x%x), expected (0x%x, 0x%x)", i, + writes[i].addr, writes[i].value, want.writes[i].addr, want.writes[i].value); + } + // A few idle cycles between commands; nothing may happen. + for (int i = 0; i < 4; ++i) { + sim->grant = 0; + sim->rvalid = 0; + sim->gpu_busy = 0; + sim->eval(); + EXPECT(!sim->arvalid && !sim->dcr_req_valid && !sim->start && !sim->done, + "activity while idle"); + tick = sim.step(tick, 2); + } +} + +void run_ild(Sim& sim, uint64_t& tick, uint64_t at, const Ild& d) { + put_ild(at, d); + const Outcome want = model_ild(at); + run(sim, tick, OP_LAUNCH_IND, at, want, false); + run(sim, tick, OP_LAUNCH_IND, at, want, true); +} + +std::vector kmu_pairs(uint32_t n) { + std::vector p; + for (uint32_t i = 0; i < n; ++i) { + p.push_back({0x010 + (i % 20), 0x1000u * (i + 1) + i}); } + return p; +} - // Drop busy; this cycle WAIT_DRAIN's combinational done = (state==DRAIN) && !busy - // fires, and at the edge FSM returns to IDLE. - sim->gpu_busy = 0; - sim->eval(); - EXPECT(sim->done == 1, "done should pulse on busy falling edge"); - cycle(sim, tick); - - // Back in IDLE; done falls. - sim->eval(); - EXPECT(sim->done == 0, "done should not stick after one cycle"); - EXPECT(sim->start == 0, "start should be 0 in post-launch IDLE"); +// The standard QMD body: entry, args, block, grid, and the rest. +std::vector launch_pairs() { + std::vector p = kmu_pairs(18); + p[9] = {DCR_GRID_X + 0, 111}; + p[10] = {DCR_GRID_X + 1, 222}; + p[11] = {DCR_GRID_X + 2, 333}; + return p; } +} // namespace + int main(int argc, char** argv) { Verilated::commandArgs(argc, argv); - vl_simulator sim; + Sim sim; uint64_t tick = 0; - - sim->grant = 0; + sim->grant = 0; + sim->rvalid = 0; + sim->dcr_req_ready = 1; + sim->dcr_proxy_idle = 1; sim->gpu_busy = 0; tick = sim.reset(tick); + int cases = 0; - // ----- Reset & idle ----- - for (int i = 0; i < 5; ++i) { - sim->eval(); - EXPECT(sim->start == 0, "start should be 0 during long idle"); - EXPECT(sim->done == 0, "done should be 0 during long idle"); - cycle(sim, tick); + g_case = "plain launch"; + run(sim, tick, OP_LAUNCH, 0, Outcome{true, false, 0, {}}, false); + run(sim, tick, OP_LAUNCH, 0, Outcome{true, false, 0, {}}, true); + ++cases; + + g_case = "qmd"; + for (uint32_t n : {0u, 1u, 7u, 8u, 18u, 64u}) { + put_qmd(0x2000, kmu_pairs(n), n); + run(sim, tick, OP_LAUNCH_QMD, 0x2000, model_qmd(0x2000), false); + run(sim, tick, OP_LAUNCH_QMD, 0x2000, model_qmd(0x2000), true); + ++cases; + } + g_case = "qmd corrupt count"; + put_qmd(0x2000, kmu_pairs(64), 1000); + run(sim, tick, OP_LAUNCH_QMD, 0x2000, model_qmd(0x2000), true); + ++cases; + + g_case = "indirect unconditional"; + { + Ild d; + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + d.pairs = kmu_pairs(0); + run_ild(sim, tick, 0x3000, d); + d.pairs = kmu_pairs(64); + run_ild(sim, tick, 0x3000, d); + d.count_override = 500; + run_ild(sim, tick, 0x3000, d); + cases += 4; + } + + g_case = "predicate"; + for (uint32_t off = 0; off < 64; off += 4) { + for (int k = 0; k < 4; ++k) { + Ild d; + d.ctl = HAS_PRED | ((k & 2) ? PRED_INV : 0); + d.pred = 0x8000 + off; + wr32(d.pred, 10); + d.ref = (k & 1) ? 10 : 9; + d.skip_n = uint16_t(off + k + 1); + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + ++cases; + } + } + g_case = "predicate unsigned"; + { + Ild d; + d.ctl = HAS_PRED; + d.pred = 0x8004; + wr32(d.pred, 0x80000000u); + d.ref = 5; + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + ++cases; + } + + g_case = "record grid"; + { + const uint64_t rec = 0x9000; + for (int i = 0; i < 16; ++i) { + wr32(rec + 4 * i, 3 + 2 * i); + } + Ild d; + d.ctl = HAS_RECORD | ctl_sel(0, 1, 2); + d.rec = rec; + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + d.ctl = HAS_RECORD | ctl_sel(5, SEL_ONE, 9) | ctl_sh(3, 0, 1); + run_ild(sim, tick, 0x3000, d); + d.ctl = HAS_RECORD | ctl_sel(SEL_ONE, SEL_ONE, SEL_ONE); + run_ild(sim, tick, 0x3000, d); + // Grid pairs absent: nothing to substitute. + d.ctl = HAS_RECORD | ctl_sel(0, 1, 2); + d.pairs = kmu_pairs(9); + run_ild(sim, tick, 0x3000, d); + cases += 4; + } + + g_case = "zero dimension"; + for (int dim = 0; dim < 3; ++dim) { + const uint64_t rec = 0x9100; + wr32(rec + 0, 4); + wr32(rec + 4, 4); + wr32(rec + 8, 4); + wr32(rec + 4 * dim, 0); + Ild d; + d.ctl = HAS_RECORD | ctl_sel(0, 1, 2); + d.rec = rec; + d.skip_n = uint16_t(7 + dim); + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + ++cases; } - // ----- First launch (busy held for 1 cycle) ----- - launch(sim, tick, /*busy_hold=*/1); + g_case = "line-crossing record"; + for (uint32_t off = 0; off < 64; off += 4) { + const uint64_t rec = 0xA000 + off; + for (int i = 0; i < 15; ++i) { + wr32(rec + 4 * i, 1 + i); + } + Ild d; + d.rec = rec; + d.pairs = launch_pairs(); + d.ctl = HAS_RECORD | ctl_sel(0, 1, 14); + run_ild(sim, tick, 0x3000, d); + d.ctl = HAS_RECORD | ctl_sel(14, 7, 2); + run_ild(sim, tick, 0x3000, d); + cases += 2; + } + g_case = "record at a 4 KiB page end"; + { + const uint64_t rec = 0xBFF8; + wr32(rec, 5); + wr32(rec + 4, 6); + wr32(rec + 8, 7); + Ild d; + d.rec = rec; + d.ctl = HAS_RECORD | ctl_sel(0, 1, 2); + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + ++cases; + } - // ----- Back-to-back launch — FSM must re-arm cleanly ----- - launch(sim, tick, /*busy_hold=*/3); + g_case = "x bias and divider"; + { + struct C { uint32_t v, bias, div, sh; }; + const C cs[] = { + {1000, 16, 7, 2}, {1000, 16, 7, 0}, {1000, 0, 0, 0}, {1000, 0, 1, 0}, + {1000, 0, 2, 0}, {7, 0, 7, 0}, {6, 0, 7, 0}, {0, 0, 3, 0}, + {0xFFFFFFFFu, 0, 0xFFFFFFFFu, 0}, {0xFFFFFFFEu, 0, 0xFFFFFFFFu, 0}, + {0xFFFFFFFFu, 0, 2, 15}, {0xFFFFFFFFu, 0, 0, 15}, + {5, 5, 0, 0}, {5, 6, 0, 0}, {5, 4, 0, 0}, {1, 0, 0, 15}, + }; + for (const C& c : cs) { + const uint64_t rec = 0x9200; + wr32(rec, c.v); + Ild d; + d.ctl = HAS_RECORD | ctl_sel(0, SEL_ONE, SEL_ONE) | ctl_sh(c.sh, 0, 0); + d.rec = rec; + d.bias = c.bias; + d.div = c.div; + d.skip_n = 3; + d.pairs = launch_pairs(); + run_ild(sim, tick, 0x3000, d); + ++cases; + } + } - // ----- A third launch with grant pulsed only at IDLE — once captured, - // FSM should not require grant held high ----- - launch(sim, tick, /*busy_hold=*/0); + g_case = "predicate-only"; + for (int k = 0; k < 2; ++k) { + Ild d; + d.ctl = HAS_PRED | NO_LAUNCH; + d.pred = 0x8010; + wr32(d.pred, uint32_t(k)); + d.skip_n = 31; + run_ild(sim, tick, 0x3000, d); + ++cases; + } + + g_case = "misaligned descriptor"; + { + Outcome refused; + refused.fault = true; + put_qmd(0x2000, kmu_pairs(4), 4); + Ild d; + d.pairs = launch_pairs(); + put_ild(0x3000, d); + for (uint64_t off : {4ull, 8ull, 32ull, 60ull}) { + run(sim, tick, OP_LAUNCH_QMD, 0x2000 + off, refused, false); + run(sim, tick, OP_LAUNCH_IND, 0x3000 + off, refused, true); + cases += 2; + } + // A plain launch carries no descriptor; its arg0 is ignored. + run(sim, tick, OP_LAUNCH, 0x1234, Outcome{true, false, 0, {}}, false); + ++cases; + } + + g_case = "random"; + for (int it = 0; it < 400; ++it) { + const uint64_t rec = 0xC000 + 4 * rnd(64); + const uint64_t pred = 0xD000 + 4 * rnd(64); + for (int i = 0; i < 15; ++i) { + const uint32_t r = rnd(4); + wr32(rec + 4 * i, r == 0 ? 0 : (r == 1 ? rnd(8) : rnd(100000))); + } + wr32(pred, rnd(8)); + Ild d; + d.ctl = (rnd(2) ? HAS_RECORD : 0) | (rnd(2) ? HAS_PRED : 0) + | (rnd(2) ? PRED_INV : 0) | (rnd(5) == 0 ? NO_LAUNCH : 0) + | ctl_sel(rnd(16), rnd(16), rnd(16)) | ctl_sh(rnd(16), rnd(16), rnd(16)); + d.rec = rec; + d.pred = pred; + d.ref = rnd(8); + d.bias = rnd(3) ? 0 : rnd(1000); + d.div = rnd(3) ? 0 : rnd(50); + d.skip_n = uint16_t(rnd(65536)); + d.pairs = rnd(3) ? launch_pairs() : kmu_pairs(rnd(65)); + const uint64_t at = 0x4000 + 64 * rnd(64); + put_ild(at, d); + run(sim, tick, OP_LAUNCH_IND, at, model_ild(at), true); + ++cases; + } - std::printf("PASSED\n"); + std::printf("PASSED — %d launch sequencer cases\n", cases); return 0; } diff --git a/sim/common/cmd_processor.cpp b/sim/common/cmd_processor.cpp index dd19406b06..63425a4d76 100644 --- a/sim/common/cmd_processor.cpp +++ b/sim/common/cmd_processor.cpp @@ -3,9 +3,12 @@ #include "cmd_processor.h" +#include + #include // VX_CFG_* device configuration #include // VX_ISA_IMPL_ID +#include #include #include #include @@ -118,7 +121,8 @@ uint32_t CommandProcessor::mmio_read(uint32_t off) const { case 0x000: return cp_ctrl_; case 0x004: return uint32_t(busy() ? 1 : 0); // CP_STATUS bit0 case 0x008: { - // CP_DEV_CAPS: {DMA_LLC_CLIENT:1 @bit28 | MMU_FAULT_REPORT:1 @bit27 | + // CP_DEV_CAPS: {DMA_LLC_CLIENT:1 @bit29 | SUPPORTS_INDIRECT:1 @bit28 | + // MMU_FAULT_REPORT:1 @bit27 | // SUPPORTS_QMD:1 @bit26 | SUPPORTS_DRAW:1 @bit25 | // VM_ENABLED:1 @bit24 | AXI_TID_W:8 | RING_LOG2:8 | NUM_QUEUES:8}. // Defaults: TID=6, RING_LOG2=16, NUM_QUEUES=1. VM_ENABLED reflects @@ -134,8 +138,9 @@ uint32_t CommandProcessor::mmio_read(uint32_t off) const { const uint32_t supports_draw = 1u << 25; const uint32_t supports_qmd = 1u << 26; const uint32_t fault_report = hooks_.mmu_fault_report ? (1u << 27) : 0; - const uint32_t llc_client = hooks_.dma_llc_client ? (1u << 28) : 0; - return llc_client | supports_qmd | supports_draw | vm_enabled | fault_report + const uint32_t supports_indirect = 1u << 28; + const uint32_t llc_client = hooks_.dma_llc_client ? (1u << 29) : 0; + return llc_client | supports_indirect | supports_qmd | supports_draw | vm_enabled | fault_report | (uint32_t(6) << 16) | (uint32_t(16) << 8) | uint32_t(1); } case 0x00C: return gpu_dev_caps_ext(); @@ -358,6 +363,7 @@ int CommandProcessor::decode_cmd_bytes(const uint8_t* buf, int len, case OP_LAUNCH: return 12; case OP_LAUNCH_QMD: return 12; // arg0 = QMD descriptor address case OP_DRAW: return 12; // arg0 = draw descriptor address + case OP_LAUNCH_INDIRECT: return 12; // arg0 = indirect launch descriptor address case OP_FENCE: return 8; case OP_CACHE_FLUSH: return 12; case OP_DCR_WRITE: return 20; @@ -416,24 +422,120 @@ bool CommandProcessor::event_wait_satisfied_() { } // CMD_LAUNCH_QMD: read the KMU descriptor from device memory and replay it -// through the DCR-write hook. The descriptor is a {uint32 count, then count × -// (uint32 dcr_addr, uint32 value)} list the host staged before submit (like a -// kernel-args blob). cp_translate matches the address the host's CMD_MEM_WRITE +// through the DCR-write hook. The descriptor is a {uint32 count, uint32 +// reserved, then count × (uint32 dcr_addr, uint32 value)} list the host staged +// before submit (like a kernel-args blob). cp_translate matches the address the host's CMD_MEM_WRITE // staged it at (VM walk when active, passthrough otherwise). -void CommandProcessor::apply_qmd_(uint64_t qmd_addr) { - if (!hooks_.dram_read || !hooks_.vortex_dcr_write) return; +bool CommandProcessor::apply_qmd_(uint64_t qmd_addr) { + if (qmd_addr % CP_LAUNCH_DESC_ALIGN != 0) { + q0_.error |= CP_Q_ERROR_DESC_ALIGN; + return false; + } + if (!hooks_.dram_read || !hooks_.vortex_dcr_write) { + return true; + } uint64_t addr = qmd_addr; uint32_t count = 0; cp_dev_read(addr, &count, sizeof(count)); - addr += sizeof(count); - constexpr uint32_t MAX_QMD_DCRS = 64; // backstop against a corrupt count - if (count > MAX_QMD_DCRS) count = MAX_QMD_DCRS; + addr += CP_QMD_PAIRS_OFFSET; + if (count > CP_LAUNCH_MAX_PAIRS) { + count = CP_LAUNCH_MAX_PAIRS; // backstop against a corrupt count + } for (uint32_t i = 0; i < count; ++i) { uint32_t pair[2] = {0, 0}; // {dcr_addr, value} cp_dev_read(addr, pair, sizeof(pair)); addr += sizeof(pair); hooks_.vortex_dcr_write(pair[0] & 0xFFF, pair[1]); // VX_DCR_ADDR_BITS=12 } + return true; +} + +uint32_t CommandProcessor::read_dev32_(uint64_t vaddr) const { + uint32_t v = 0; + cp_dev_read(vaddr, &v, sizeof(v)); + return v; +} + +CommandProcessor::IldAction CommandProcessor::apply_ild_(uint64_t ild_addr, + uint32_t* skip_n) { + *skip_n = 0; + if (ild_addr % CP_LAUNCH_DESC_ALIGN != 0) { + q0_.error |= CP_Q_ERROR_DESC_ALIGN; + return IldAction::Retire; + } + if (!hooks_.dram_read || !hooks_.vortex_dcr_write) { + return IldAction::Retire; + } +#ifndef NDEBUG + if (unflushed_launch_) { + std::fprintf(stderr, "[VXCP] Warning: indirect launch reads memory with " + "no cache flush since the previous launch\n"); + } +#endif + cp_ild_header_t hdr; + const uint64_t base = ild_addr; + cp_dev_read(base, &hdr, sizeof(hdr)); + + bool exec = true; + if (hdr.ctl & CP_ILD_HAS_PRED) { + const uint32_t p = read_dev32_(hdr.pred_addr); + exec = (p > hdr.pred_ref) != ((hdr.ctl & CP_ILD_PRED_INV) != 0); +#ifdef VX_DBG_CP_ILD_FAULT + exec = !exec; // known-bad control (see below): the predicate inverted +#endif + } + uint32_t grid[3] = {1, 1, 1}; + const bool has_record = (hdr.ctl & CP_ILD_HAS_RECORD) != 0; + if (exec && has_record) { + for (int d = 0; d < 3; ++d) { + const uint32_t sel = cp_ild_sel(hdr.ctl, d); + uint64_t v = (sel == CP_ILD_SEL_ONE) + ? 1 : read_dev32_(hdr.record_addr + 4 * uint64_t(sel)); + if (d == 0) { + v = (v > hdr.x_bias) ? (v - hdr.x_bias) : 0; + if (hdr.x_div > 1) { + v /= hdr.x_div; + } + } + const uint32_t sh = cp_ild_shift(hdr.ctl, d); + grid[d] = uint32_t((v + (uint64_t(1) << sh) - 1) >> sh); +#ifdef VX_DBG_CP_ILD_FAULT + // Known-bad control for CI negative cases: the record's x is + // ignored -- every record-sized launch runs one workgroup wide, a + // zero-sized one included -- and the predicate above is inverted. + if (d == 0) { + grid[d] = 1; + } +#endif + if (grid[d] == 0) { + exec = false; + } + } + } + if (!exec) { + *skip_n = hdr.skip_n; + return IldAction::Skip; + } + if (hdr.ctl & CP_ILD_NO_LAUNCH) { + return IldAction::Retire; + } + uint32_t count = hdr.qmd_count; + if (count > CP_LAUNCH_MAX_PAIRS) { + count = CP_LAUNCH_MAX_PAIRS; + } + uint64_t addr = base + CP_ILD_HEADER_BYTES; + for (uint32_t i = 0; i < count; ++i) { + uint32_t pair[2] = {0, 0}; // {dcr_addr, value} + cp_dev_read(addr, pair, sizeof(pair)); + addr += sizeof(pair); + const uint32_t dcr = pair[0] & 0xFFF; + uint32_t value = pair[1]; + if (has_record && dcr >= VX_DCR_KMU_GRID_DIM_X && dcr <= VX_DCR_KMU_GRID_DIM_Z) { + value = grid[dcr - VX_DCR_KMU_GRID_DIM_X]; + } + hooks_.vortex_dcr_write(dcr, value); + } + return IldAction::Launch; } // One DCR write to VX_DCR_BASE_CACHE_FLUSH reaches every core and starts its @@ -469,8 +571,9 @@ bool CommandProcessor::exec_inline_cmd_(const Cmd& c) { switch (c.opcode) { case OP_LAUNCH: case OP_LAUNCH_QMD: - if (c.opcode == OP_LAUNCH_QMD) - apply_qmd_(c.arg0); + if (c.opcode == OP_LAUNCH_QMD && !apply_qmd_(c.arg0)) { + return false; + } launch_state_ = LaunchState::PulseStart; return true; case OP_DCR_WRITE: @@ -485,6 +588,7 @@ bool CommandProcessor::exec_inline_cmd_(const Cmd& c) { return false; case OP_CACHE_FLUSH: this->flush_cores_(uint32_t(c.arg0 & 0xFFFFFFFF), c.flags); + unflushed_launch_ = false; return false; default: // NOP / FENCE / unknown step — no-op (draws don't use MEM_*/EVENT_*). @@ -518,8 +622,10 @@ void CommandProcessor::tick_launch() { launch_state_ = LaunchState::WaitDrain; return; case LaunchState::WaitDrain: - if (!hooks_.vortex_busy || !hooks_.vortex_busy()) + if (!hooks_.vortex_busy || !hooks_.vortex_busy()) { launch_state_ = LaunchState::Idle; + unflushed_launch_ = true; + } return; } } @@ -542,7 +648,8 @@ void CommandProcessor::tick_engine() { } decode_cmd(off, cur_cmd_); cur_is_launch_ = (cur_cmd_.opcode == OP_LAUNCH || - cur_cmd_.opcode == OP_LAUNCH_QMD); + cur_cmd_.opcode == OP_LAUNCH_QMD || + cur_cmd_.opcode == OP_LAUNCH_INDIRECT); switch (cur_cmd_.opcode) { case OP_NOP: case OP_FENCE: // No resource bid for these opcodes; retire as NOP. @@ -565,7 +672,10 @@ void CommandProcessor::tick_engine() { return; case EngState::Decode: - if (cur_is_no_resource_) { + if (skip_cnt_ != 0) { + --skip_cnt_; + eng_state_ = EngState::Retire; + } else if (cur_is_no_resource_) { eng_state_ = EngState::Retire; } else { eng_state_ = EngState::Bid; @@ -575,26 +685,42 @@ void CommandProcessor::tick_engine() { case EngState::Bid: // Dispatch to the resource. Single-queue means we always win // the arbiter, so transition immediately to WaitDone. - if (cur_is_launch_) { + if (cur_cmd_.opcode == OP_LAUNCH_INDIRECT) { + uint32_t skip_n = 0; + switch (apply_ild_(cur_cmd_.arg0, &skip_n)) { + case IldAction::Launch: + launch_state_ = LaunchState::PulseStart; + eng_state_ = EngState::WaitDone; + break; + case IldAction::Skip: + skip_cnt_ = skip_n; + eng_state_ = EngState::Retire; + break; + case IldAction::Retire: + eng_state_ = EngState::Retire; + break; + } + } else if (cur_is_launch_) { // QMD launch: the KMU descriptor lives in memory as a // {count, (dcr_addr,value)...} list (NVIDIA QMD model). Apply // it through the DCR-write hook, then pulse start exactly like // a plain CMD_LAUNCH — collapsing ~18 ring DCR writes to one. - if (cur_cmd_.opcode == OP_LAUNCH_QMD) - apply_qmd_(cur_cmd_.arg0); - launch_state_ = LaunchState::PulseStart; - eng_state_ = EngState::WaitDone; + if (cur_cmd_.opcode == OP_LAUNCH_QMD && !apply_qmd_(cur_cmd_.arg0)) { + eng_state_ = EngState::Retire; + } else { + launch_state_ = LaunchState::PulseStart; + eng_state_ = EngState::WaitDone; + } } else if (cur_cmd_.opcode == OP_DRAW) { // Device-orchestrated draw: arg0 → resident draw descriptor // {uint32 num_steps, steps[28 B]...}. Walk the embedded command // bundle (DrawStep), retiring the one OP_DRAW when drained. draw_addr_ = cur_cmd_.arg0; draw_num_steps_ = 0; - if (hooks_.dram_read) + if (hooks_.dram_read) { cp_dev_read(draw_addr_, &draw_num_steps_, sizeof(draw_num_steps_)); - if (draw_num_steps_ > MAX_DRAW_STEPS) - draw_num_steps_ = MAX_DRAW_STEPS; + } draw_step_ = 0; eng_state_ = EngState::DrawStep; } else if (cur_cmd_.opcode == OP_DCR_WRITE) { @@ -617,6 +743,7 @@ void CommandProcessor::tick_engine() { } else if (cur_cmd_.opcode == OP_CACHE_FLUSH) { // arg0 carries num_cores. this->flush_cores_(uint32_t(cur_cmd_.arg0 & 0xFFFFFFFF), cur_cmd_.flags); + unflushed_launch_ = false; eng_state_ = EngState::Retire; } else if (cur_cmd_.opcode == OP_EVENT_SIG) { // CMD_EVENT_SIGNAL: write arg1 (8-byte value) to arg0 @@ -676,7 +803,21 @@ void CommandProcessor::tick_engine() { return; } draw_load_step_(); - if (exec_inline_cmd_(draw_cmd_)) { + if (draw_cmd_.opcode == OP_LAUNCH_INDIRECT) { + uint32_t skip_n = 0; + switch (apply_ild_(draw_cmd_.arg0, &skip_n)) { + case IldAction::Launch: + launch_state_ = LaunchState::PulseStart; + eng_state_ = EngState::DrawLaunchWait; + break; + case IldAction::Skip: + draw_step_ += 1 + skip_n; + break; + case IldAction::Retire: + ++draw_step_; + break; + } + } else if (exec_inline_cmd_(draw_cmd_)) { eng_state_ = EngState::DrawLaunchWait; } else { ++draw_step_; diff --git a/sim/common/cmd_processor.h b/sim/common/cmd_processor.h index a6d52a71c6..820239aa64 100644 --- a/sim/common/cmd_processor.h +++ b/sim/common/cmd_processor.h @@ -58,6 +58,13 @@ // from one host doorbell with no host round-trip — the "true GPU" draw. The // descriptor is an indirect command bundle, so the executed sequence is // byte-identical to streaming the same commands through the ring. +// +// CMD_LAUNCH_INDIRECT (OP_LAUNCH_INDIRECT, opcode 0x0D) — predicated launch. +// arg0 points at an indirect launch descriptor (cp_launch_abi.h): a predicate, +// a grid read from a device-memory record, and a QMD body. When the +// predicate fails or a grid dimension is zero, the command retires and the +// next skip_n commands of its stream (ring, or the enclosing OP_DRAW bundle) +// retire unexecuted, so a device-computed zero never reaches the KMU. // ============================================================================ #ifndef VORTEX_COMMAND_PROCESSOR_H @@ -189,13 +196,16 @@ class CommandProcessor { OP_CACHE_FLUSH = 0x0A, OP_LAUNCH_QMD = 0x0B, // atomic launch: KMU descriptor read from memory OP_DRAW = 0x0C, // device-orchestrated draw: arg0 = draw descriptor addr + OP_LAUNCH_INDIRECT = 0x0D, // predicated launch: arg0 = indirect launch descriptor addr }; + // Outcome of evaluating an indirect launch descriptor. + enum class IldAction { Skip, Retire, Launch }; + // Fixed per-step stride inside a draw descriptor: the 28-byte cmd-record // prefix (opcode/flags/reserved + arg0/arg1/arg2). A uniform stride keeps // the descriptor walk (and the RTL CP mirror) simple. static constexpr int DRAW_STEP_BYTES = 28; - static constexpr uint32_t MAX_DRAW_STEPS = 256; // corrupt-count backstop // CMD_MEM_* header flag (cmd_t.flags bit2 = F_MEM_PHYSICAL): the device // operand is a physical address — the MMU-aware CP DMA skips translation. @@ -243,6 +253,11 @@ class CommandProcessor { Cmd cur_cmd_{}; bool cur_is_launch_ = false; bool cur_is_no_resource_ = false; + // Commands still to retire unexecuted after a predicated-off indirect launch. + uint32_t skip_cnt_ = 0; + // A launch has drained with no CMD_CACHE_FLUSH behind it yet: an indirect + // read now could miss data that kernel left in the caches. + bool unflushed_launch_ = false; // ----- Draw-bundle state (OP_DRAW walk) ----- uint64_t draw_addr_ = 0; // descriptor base (device VA) @@ -280,8 +295,17 @@ class CommandProcessor { // compares to cur_cmd_.arg1 under the wait_op encoded in arg2[1:0]. bool event_wait_satisfied_(); // CMD_LAUNCH_QMD: read the in-memory KMU descriptor at `qmd_addr` and - // replay its {dcr_addr,value} pairs through the DCR-write hook. - void apply_qmd_(uint64_t qmd_addr); + // replay its {dcr_addr,value} pairs through the DCR-write hook. False when + // the descriptor is not line aligned: nothing is replayed, Q_ERROR is set, + // and the launch must not start. + bool apply_qmd_(uint64_t qmd_addr); + // CMD_LAUNCH_INDIRECT: evaluate the descriptor at `ild_addr` (predicate, + // grid select/scale). On IldAction::Launch the QMD pairs have been + // replayed with the computed grid; on IldAction::Skip `*skip_n` is the + // number of following commands to retire unexecuted. A descriptor that is + // not line aligned retires (IldAction::Retire) and sets Q_ERROR. + IldAction apply_ild_(uint64_t ild_addr, uint32_t* skip_n); + uint32_t read_dev32_(uint64_t vaddr) const; // CMD_CACHE_FLUSH across cores [0, num_cores); a device-scope flush // leaves the shared last-level cache unwalked. void flush_cores_(uint32_t num_cores, uint8_t flags); diff --git a/sw/common/cp_launch_abi.h b/sw/common/cp_launch_abi.h new file mode 100644 index 0000000000..e26d18841b --- /dev/null +++ b/sw/common/cp_launch_abi.h @@ -0,0 +1,105 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Launch descriptors the command processor reads from device memory when the +// command executes, so a kernel may also produce them. Both are a header +// followed by 8-byte {u32 dcr_addr, u32 value} pairs that never straddle a +// 64-byte line. +// +// Both descriptors start on a 64-byte line. A command whose descriptor address +// is not line aligned is not executed: it retires and sets CP_Q_ERROR_DESC_ALIGN +// in its queue's Q_ERROR register. +// +// QMD (CMD_LAUNCH_QMD): {u32 count, u32 reserved, count x pair}. +// +// ILD (CMD_LAUNCH_INDIRECT): a 64-byte header line, then qmd_count pairs: +// +// predicate : exec = (*pred_addr > pred_ref) ^ PRED_INV (HAS_PRED) +// grid : v_d = (sel_d == ILD_SEL_ONE) ? 1 : record[sel_d] (HAS_RECORD) +// x only: v_x = sat_sub(v_x, x_bias), then v_x /= x_div (x_div > 1) +// g_d = (v_d + 2^sh_d - 1) >> sh_d; any g_d == 0 clears exec +// not exec : retire, and retire the next skip_n commands without executing +// NO_LAUNCH : retire after the predicate; no DCR write and no start +// otherwise : replay the pairs (GRID_DIM_X/Y/Z replaced by g when +// HAS_RECORD), then start the kernel and drain it + +#ifndef VORTEX_CP_LAUNCH_ABI_H +#define VORTEX_CP_LAUNCH_ABI_H + +#include +#include + +namespace vortex { + +struct cp_ild_header_t { + uint32_t ctl; + uint16_t skip_n; + uint16_t reserved0; + uint64_t record_addr; // 4-byte aligned; the selected words span at most two lines + uint64_t pred_addr; // 4-byte aligned + uint32_t pred_ref; + uint32_t qmd_count; + uint32_t x_bias; + uint32_t x_div; // 0 or 1 bypasses the divide + uint32_t reserved1[6]; +}; +// Byte offsets of the header fields; the hardware decodes the same positions. +constexpr uint32_t CP_ILD_OFF_CTL = 0; +constexpr uint32_t CP_ILD_OFF_SKIP = 4; +constexpr uint32_t CP_ILD_OFF_RECORD = 8; +constexpr uint32_t CP_ILD_OFF_PRED = 16; +constexpr uint32_t CP_ILD_OFF_PRED_REF = 24; +constexpr uint32_t CP_ILD_OFF_COUNT = 28; +constexpr uint32_t CP_ILD_OFF_X_BIAS = 32; +constexpr uint32_t CP_ILD_OFF_X_DIV = 36; + +static_assert(sizeof(cp_ild_header_t) == 64, "ILD header is one cache line"); +static_assert(offsetof(cp_ild_header_t, ctl) == CP_ILD_OFF_CTL, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, skip_n) == CP_ILD_OFF_SKIP, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, record_addr) == CP_ILD_OFF_RECORD, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, pred_addr) == CP_ILD_OFF_PRED, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, pred_ref) == CP_ILD_OFF_PRED_REF, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, qmd_count) == CP_ILD_OFF_COUNT, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, x_bias) == CP_ILD_OFF_X_BIAS, "ILD layout"); +static_assert(offsetof(cp_ild_header_t, x_div) == CP_ILD_OFF_X_DIV, "ILD layout"); + +constexpr uint32_t CP_LAUNCH_DESC_ALIGN = 64; +constexpr uint32_t CP_Q_ERROR_DESC_ALIGN = 1u << 0; + +constexpr uint32_t CP_QMD_PAIRS_OFFSET = 8; +constexpr uint32_t CP_ILD_HEADER_BYTES = 64; +constexpr uint32_t CP_LAUNCH_MAX_PAIRS = 64; + +constexpr uint32_t CP_ILD_SEL_ONE = 0xF; // grid source: constant 1 +constexpr uint32_t CP_ILD_SEL_X_SH = 0; +constexpr uint32_t CP_ILD_SEL_Y_SH = 4; +constexpr uint32_t CP_ILD_SEL_Z_SH = 8; +constexpr uint32_t CP_ILD_SHIFT_X_SH = 12; +constexpr uint32_t CP_ILD_SHIFT_Y_SH = 16; +constexpr uint32_t CP_ILD_SHIFT_Z_SH = 20; +constexpr uint32_t CP_ILD_HAS_RECORD = 1u << 24; +constexpr uint32_t CP_ILD_HAS_PRED = 1u << 25; +constexpr uint32_t CP_ILD_PRED_INV = 1u << 26; +constexpr uint32_t CP_ILD_NO_LAUNCH = 1u << 27; + +inline uint32_t cp_ild_sel(uint32_t ctl, int dim) { + return (ctl >> (CP_ILD_SEL_X_SH + 4 * dim)) & 0xF; +} + +inline uint32_t cp_ild_shift(uint32_t ctl, int dim) { + return (ctl >> (CP_ILD_SHIFT_X_SH + 4 * dim)) & 0xF; +} + +} // namespace vortex + +#endif // VORTEX_CP_LAUNCH_ABI_H diff --git a/sw/runtime/common/device.cpp b/sw/runtime/common/device.cpp index f9f7503db7..c77b35cad1 100644 --- a/sw/runtime/common/device.cpp +++ b/sw/runtime/common/device.cpp @@ -97,6 +97,7 @@ constexpr uint8_t CP_OPCODE_EVT_WAIT = 0x09; constexpr uint8_t CP_OPCODE_CACHE_FLUSH= 0x0A; constexpr uint8_t CP_OPCODE_LAUNCH_QMD = 0x0B; constexpr uint8_t CP_OPCODE_DRAW = 0x0C; +constexpr uint8_t CP_OPCODE_LAUNCH_IND = 0x0D; constexpr std::size_t CP_CL_BYTES = 64; // CMD_EVENT_WAIT comparison operations (encoded in arg2[1:0]). @@ -345,7 +346,7 @@ vx_result_t Device::cp_init() { if (p->cp_reg_read(CP_DEV_CAPS, &dev_caps) != VX_SUCCESS) return VX_ERR_DEVICE_LOST; // An all-ones read is never a valid capability word: bits [31:29] are - // hardwired zero by VX_cp_axil_regfile, so 0xFFFFFFFF means the read + // reserved zero, so 0xFFFFFFFF means the read // did not reach the register (AXI DECERR / no response substitutes // all-ones on the way back). Decoding it would set every capability // bit -- and a spurious VM_ENABLED sends VMManager off to identity-map @@ -371,9 +372,14 @@ vx_result_t Device::cp_init() { // Reading them on a target that does not decode them stalls the DCR // bus waiting for a response that never arrives. mmu_fault_report_ = (dev_caps & (1u << 27)) != 0; - // DMA_LLC_CLIENT (bit 28): the CP DMA is a client of the last-level + // SUPPORTS_INDIRECT (bit 28): the CP decodes CMD_LAUNCH_INDIRECT. There + // is no fallback: reading the record or predicate on the host would + // stall it on device progress, so launches that chain + // vx_launch_indirect_t are refused without it. + cp_supports_indirect_ = (dev_caps & (1u << 28)) != 0; + // DMA_LLC_CLIENT (bit 29): the CP DMA is a client of the last-level // cache, which is then the point of coherence for host transfers. - cp_dma_llc_client_ = (dev_caps & (1u << 28)) != 0; + cp_dma_llc_client_ = (dev_caps & (1u << 29)) != 0; } // Resolve the core count now, while nothing holds cp_mu_. Deferring it to @@ -557,6 +563,7 @@ const char* cp_opcode_name(uint8_t op) { case CP_OPCODE_CACHE_FLUSH: return "CACHE_FLUSH"; case CP_OPCODE_LAUNCH_QMD: return "LAUNCH_QMD"; case CP_OPCODE_DRAW: return "DRAW"; + case CP_OPCODE_LAUNCH_IND: return "LAUNCH_IND"; default: return "?"; } } @@ -576,7 +583,8 @@ void build_cache_flush(uint8_t cl[CP_CL_BYTES], uint64_t num_cores, uint8_t fenc } // True when a CMD_MEM_* transfer reaches device memory outside the IO -// aperture. IO accesses bypass the caches, so they need no flush. +// aperture, or the CP reads an indirect launch's descriptor, predicate and +// grid record. IO accesses bypass the caches, so they need no flush. bool cp_dma_touches_device_mem(const uint8_t* cl) { uint64_t dst = 0, src = 0, size = 0; std::memcpy(&dst, cl + 4, sizeof(dst)); @@ -589,6 +597,7 @@ bool cp_dma_touches_device_mem(const uint8_t* cl) { case CP_OPCODE_MEM_WRITE: return outside_io(dst); case CP_OPCODE_MEM_READ: return outside_io(src); case CP_OPCODE_MEM_COPY: return outside_io(dst) || outside_io(src); + case CP_OPCODE_LAUNCH_IND: return true; default: return false; } } @@ -607,8 +616,12 @@ vx_result_t Device::cp_ring_append_(const void* cl, bool llc_clean) { // to wait for: the cache cannot serve stale data from it or write a // dirty line back over it. const bool dma = cp_dma_touches_device_mem(b) && !(llc_clean && b[0] == CP_OPCODE_MEM_WRITE); + // An indirect launch counts as a launch whether or not its predicate + // lets it run: the commands it may skip are counted at staging from that + // fixed state (see cmd_ring_count). const bool launch = (b[0] == CP_OPCODE_LAUNCH) || (b[0] == CP_OPCODE_LAUNCH_QMD) + || (b[0] == CP_OPCODE_LAUNCH_IND) || (b[0] == CP_OPCODE_DRAW); if ((dma && (l1_dirty_ || llc_dirty_)) || (launch && l1_dirty_)) { uint8_t flush[CP_CL_BYTES]; @@ -697,6 +710,20 @@ vx_result_t Device::cp_batch_end() { // Poll Q_SEQNUM once for the last command in the batch. r = cp_poll_seqnum_(target); if (r != VX_SUCCESS) return r; + // A descriptor the CP refused (it sets Q_ERROR and retires it unexecuted) + // means the batch did not run as submitted. + uint32_t qerr = 0; + { + std::lock_guard g(cp_mu_); + r = p->cp_reg_read(CP_Q_ERROR, &qerr); + } + if (r != VX_SUCCESS) { + return r; + } + if (qerr != 0) { + fprintf(stderr, "vortex: command processor refused a command (Q_ERROR=0x%x)\n", qerr); + return VX_ERR_DEVICE_LOST; + } // Report a page fault raised by any launch in the batch before treating // its results as valid (deferred from each in-batch cp_submit_launch). r = check_mmu_fault(); @@ -903,7 +930,7 @@ vx_result_t Device::cp_submit_launch() { } // CMD_LAUNCH on-wire layout (cmd_size=12): // bytes 0..3 header { opcode=0x06, flags=0, reserved=0 } - // bytes 4..11 arg0 unused by VX_cp_launch + // bytes 4..11 arg0 unused uint8_t cl[CP_CL_BYTES] = {0}; cl[0] = CP_OPCODE_LAUNCH; auto r = cp_submit_cl_(cl); @@ -1004,6 +1031,33 @@ vx_result_t Device::cp_submit_draw(uint64_t desc_addr) { return drain_cout(); } +vx_result_t Device::cp_submit_launch_indirect(uint64_t ild_addr, bool launches) { + // CMD_LAUNCH_INDIRECT on-wire layout (cmd_size=12): + // bytes 0..3 header { opcode=0x0D, flags=0, reserved=0 } + // bytes 4..11 arg0 indirect launch descriptor device address + // The kernel-boundary flush ahead of it, and after it, is posted by + // cp_ring_append_ as for any launch. + auto r = ensure_mmu_satp(); + if (r != VX_SUCCESS) { + return r; + } + uint8_t cl[CP_CL_BYTES] = {0}; + cl[0] = CP_OPCODE_LAUNCH_IND; + std::memcpy(cl + 4, &ild_addr, sizeof(ild_addr)); + r = cp_submit_cl_(cl); + if (r != VX_SUCCESS || !launches) { + return r; + } + r = check_mmu_fault(); + if (r != VX_SUCCESS) { + return r; + } + if (tls_batch_owner == this) { + return VX_SUCCESS; + } + return drain_cout(); +} + vx_result_t Device::cp_submit_dcr_read(uint32_t addr, uint32_t tag, uint32_t* out_value) { if (!out_value) return VX_ERR_INVALID_VALUE; @@ -1396,6 +1450,9 @@ vx_result_t Device::query_caps(uint32_t caps_id, uint64_t* out_value) { case VX_CAPS_CLOCK_RATE: *out_value = VX_CFG_PLATFORM_CLOCK_RATE; break; case VX_CAPS_PEAK_MEM_BW: *out_value = VX_CFG_PLATFORM_MEMORY_PEAK_BW; break; case VX_CAPS_VM_SUPPORT: *out_value = vm_enabled_ ? 1 : 0; break; + case VX_CAPS_CP_INDIRECT: + *out_value = (cp_supports_indirect_ && cp_supports_qmd_) ? 1 : 0; + break; case VX_CAPS_VM_PINNED_SIZE: *out_value = pinned_size_; break; case VX_CAPS_VM_PINNED_FREE: { std::lock_guard g(mu_); diff --git a/sw/runtime/common/queue.cpp b/sw/runtime/common/queue.cpp index cb0ceb4039..74cafb137a 100644 --- a/sw/runtime/common/queue.cpp +++ b/sw/runtime/common/queue.cpp @@ -8,6 +8,8 @@ #include "vortex2_internal.h" #include +#include +#include "common.h" // CACHE_BLOCK_SIZE #include #include @@ -287,6 +289,15 @@ vx_result_t Queue::enqueue_launch(const vx_launch_info_t* info, if (info->ndim > 3) return VX_ERR_INVALID_VALUE; if (info->args_size != 0 && !info->args_host) return VX_ERR_INVALID_VALUE; + // An extended launch is a one-command batch, which validates and stages + // the chained structs. + if (info->next != nullptr) { + vx_command_t c = {}; + c.type = VX_COMMAND_LAUNCH; + c.data.launch = info; + return this->enqueue_commands(&c, 1, nw, w, out); + } + // info->kernel is a vx_kernel_h (vx_module_get_kernel). NULL is the legacy // escape hatch — the caller pre-programmed the PC DCRs itself. Retain the // kernel for the worker's lifetime so the underlying module image @@ -506,6 +517,7 @@ namespace { constexpr uint8_t CP_OP_DCR_WRITE = 0x04; constexpr uint8_t CP_OP_CACHE_FLUSH = 0x0A; constexpr uint8_t CP_OP_LAUNCH_QMD = 0x0B; +constexpr uint8_t CP_OP_LAUNCH_IND = 0x0D; // Fixed per-step stride in a draw descriptor (28-byte cmd-record prefix). // Must equal CommandProcessor::DRAW_STEP_BYTES. constexpr int CP_DRAW_STEP_BYTES = 28; @@ -525,13 +537,124 @@ struct CmdRec { std::array grid = {1, 1, 1}; std::array block = {1, 1, 1}; std::array cluster = {1, 1, 1}; + // Indirect launch: the descriptor header (skip_n and qmd_count are filled + // at staging) and the number of following API commands it guards. + bool indirect = false; + vortex::cp_ild_header_t ild{}; + uint32_t skip_cmds = 0; }; +// Launch descriptors live in scratch slots, which the device allocator aligns to +// its block size; the command processor reads them as whole lines. +static_assert(CACHE_BLOCK_SIZE % vortex::CP_LAUNCH_DESC_ALIGN == 0, + "launch descriptors must be line aligned"); + +// Commands a record expands to after an indirect launch, as its skip counts +// them. On the ring an indirect launch leaves L1 dirty whether or not it runs, +// as does every launch, so each launch after it is preceded by the flush +// cp_ring_append_ inserts. In a draw descriptor a launch is followed by its own +// flush step, which a predicate-only descriptor does not have, and an indirect +// launch is preceded by a full flush when the CP reads beneath the last-level +// cache (`ild_full_flush`). +uint32_t cmd_ring_count(const CmdRec& rec, bool in_draw, bool ild_full_flush) { + if (!rec.is_launch) { + return 1; + } + if (!in_draw || !rec.indirect) { + return 2; + } + return (ild_full_flush ? 1 : 0) + 1 + ((rec.ild.ctl & vortex::CP_ILD_NO_LAUNCH) ? 0 : 1); +} + +// Parse the extension chain of a launch into `r`. Validates every field the +// command processor would otherwise interpret as garbage. +vx_result_t cmd_parse_launch_ext(Device* device, const vx_launch_info_t* info, + CmdRec& r) { + // Every extension struct starts with {struct_size, next, type}. + struct ext_header_t { + size_t struct_size; + const void* next; + vx_struct_type_e type; + }; + for (const void* p = info->next; p != nullptr; ) { + const auto* hdr = static_cast(p); + if (hdr->struct_size < sizeof(ext_header_t)) { + return VX_ERR_INVALID_INFO; + } + switch (hdr->type) { + case VX_STRUCT_TYPE_LAUNCH_INDIRECT: + break; + default: + return VX_ERR_INVALID_INFO; + } + if (hdr->struct_size < sizeof(vx_launch_indirect_t) || r.indirect) { + return VX_ERR_INVALID_INFO; + } + const vx_launch_indirect_t& x = *static_cast(p); + if (!device->cp_supports_indirect() || !device->cp_supports_qmd()) { + return VX_ERR_NOT_SUPPORTED; + } + const bool no_launch = (x.flags & VX_INDIRECT_NO_LAUNCH) != 0; + if ((x.flags & ~(VX_INDIRECT_PRED_INVERT | VX_INDIRECT_NO_LAUNCH)) != 0 || + (x.record_addr & 3) != 0 || (x.pred_addr & 3) != 0) { + return VX_ERR_INVALID_VALUE; + } + if (no_launch && (info->kernel != nullptr || info->ndim != 0 || + info->args_size != 0)) { + return VX_ERR_INVALID_VALUE; + } + uint32_t ctl = 0; + if (x.record_addr != 0) { + if (!no_launch && info->ndim == 0) { + return VX_ERR_INVALID_VALUE; + } + for (uint32_t d = 0; d < 3; ++d) { + // The KMU cannot check a device-sourced grid against a cluster + // shape, so clustered launches keep a host-known grid. + if (!no_launch && d < info->ndim && info->cluster_dim[d] > 1) { + return VX_ERR_INVALID_VALUE; + } + if (x.grid_word[d] > VX_INDIRECT_ONE || x.grid_shift[d] > 15) { + return VX_ERR_INVALID_VALUE; + } + const bool used = no_launch || d < info->ndim; + const uint32_t sel = used ? x.grid_word[d] : vortex::CP_ILD_SEL_ONE; + const uint32_t sh = used ? x.grid_shift[d] : 0; + ctl |= sel << (vortex::CP_ILD_SEL_X_SH + 4 * d); + ctl |= sh << (vortex::CP_ILD_SHIFT_X_SH + 4 * d); + } + ctl |= vortex::CP_ILD_HAS_RECORD; + r.ild.record_addr = x.record_addr; + r.ild.x_bias = x.x_bias; + r.ild.x_div = x.x_div; + } + if (x.pred_addr != 0) { + ctl |= vortex::CP_ILD_HAS_PRED; + if (x.flags & VX_INDIRECT_PRED_INVERT) { + ctl |= vortex::CP_ILD_PRED_INV; + } + r.ild.pred_addr = x.pred_addr; + r.ild.pred_ref = x.pred_ref; + } + if (no_launch) { + ctl |= vortex::CP_ILD_NO_LAUNCH; + } + r.ild.ctl = ctl; + r.indirect = true; + r.skip_cmds = x.skip_count; + p = x.next; + } + return VX_SUCCESS; +} + // Per-launch device-scratch staging: args blob + QMD launch descriptor. struct CmdStaged { uint64_t args_addr = 0; bool args_pooled = false; bool args_active = false; uint64_t qmd_addr = 0; bool qmd_pooled = false; bool qmd_active = false; - // Host copy of the packed QMD ([count, count x (dcr_addr, value)]) for + // qmd_addr holds an indirect launch descriptor rather than a plain QMD. + bool indirect = false; + bool launches = true; + // Host copy of the packed QMD ([count, reserved, count x (dcr_addr, value)]) for // CPs without the CMD_LAUNCH_QMD decoder (see cmd_submit_launch). std::vector qmd_words; }; @@ -539,8 +662,8 @@ struct CmdStaged { // Validate `commands`, copy into `recs`, retaining launched kernels (recorded // in `retained`). On any validation error the retained kernels are released and // the error is returned; on success the caller owns `retained`. -vx_result_t cmd_build_recs(const vx_command_t* commands, uint32_t count, - std::vector& recs, +vx_result_t cmd_build_recs(Device* device, const vx_command_t* commands, + uint32_t count, std::vector& recs, std::vector& retained) { recs.reserve(count); auto fail = [&](vx_result_t e) -> vx_result_t { @@ -548,6 +671,19 @@ vx_result_t cmd_build_recs(const vx_command_t* commands, uint32_t count, retained.clear(); return e; }; + // A CTA runs on one core: its block fits the core's threads and its shared + // memory the core's local memory (the vx_enqueue_launch contract). + uint64_t nt = 0, nw = 0, lmem_cap = 0; + auto rq = device->query_caps(VX_CAPS_NUM_THREADS, &nt); + if (rq == VX_SUCCESS) { + rq = device->query_caps(VX_CAPS_NUM_WARPS, &nw); + } + if (rq == VX_SUCCESS) { + rq = device->query_caps(VX_CAPS_LOCAL_MEM_SIZE, &lmem_cap); + } + if (rq != VX_SUCCESS) { + return rq; + } for (uint32_t i = 0; i < count; ++i) { const vx_command_t& c = commands[i]; CmdRec r; @@ -571,9 +707,15 @@ vx_result_t cmd_build_recs(const vx_command_t* commands, uint32_t count, } r.ndim = info->ndim; r.lmem_size = info->lmem_size; + uint64_t block_size = 1; for (uint32_t d = 0; d < info->ndim; ++d) { r.grid [d] = info->grid_dim [d]; r.block[d] = info->block_dim[d]; + block_size *= info->block_dim[d]; + } + if (info->ndim > 0 && + (block_size > nt * nw || info->lmem_size > lmem_cap)) { + return fail(VX_ERR_INVALID_VALUE); } for (uint32_t d = 0; d < info->ndim; ++d) { uint32_t lg = info->cluster_dim[d]; @@ -581,6 +723,15 @@ vx_result_t cmd_build_recs(const vx_command_t* commands, uint32_t count, if (r.grid[d] % lg != 0) return fail(VX_ERR_INVALID_VALUE); r.cluster[d] = lg; } + if (info->next != nullptr) { + auto re = cmd_parse_launch_ext(device, info, r); + if (re != VX_SUCCESS) { + return fail(re); + } + if (r.skip_cmds > count - 1 - i) { + return fail(VX_ERR_INVALID_VALUE); + } + } } else { return fail(VX_ERR_INVALID_VALUE); } @@ -592,12 +743,14 @@ vx_result_t cmd_build_recs(const vx_command_t* commands, uint32_t count, // Stage each launch's args AND its QMD launch descriptor into device scratch. // Both are CP DMAs that must complete BEFORE the ring batch / OP_DRAW is // submitted (the launch's CMD_LAUNCH_QMD reads the QMD from memory at drain -// time). The QMD is the KMU descriptor as a {count,(dcr_addr,value)...} list +// time). The QMD is the KMU descriptor as a {count,reserved,(dcr_addr,value)...} list // the CP replays — one launch command in place of ~18 CMD_DCR_WRITEs. Returns // the first error; the caller releases any active slots in `staged`. `tpw` is -// threads-per-warp (NUM_THREADS) for the warp_step derivation. +// threads-per-warp (NUM_THREADS) for the warp_step derivation. `in_draw`: the +// launches run as the steps of a draw descriptor rather than on the ring. vx_result_t cmd_stage_qmds(Device* device_, const std::vector& recs, - std::vector& staged, uint32_t tpw) { + std::vector& staged, uint32_t tpw, + bool in_draw) { vx_result_t r = VX_SUCCESS; for (size_t i = 0; i < recs.size() && r == VX_SUCCESS; ++i) { const CmdRec& rec = recs[i]; @@ -632,9 +785,10 @@ vx_result_t cmd_stage_qmds(Device* device_, const std::vector& recs, (tpw / (eff_block[0] * eff_block[1])) % eff_block[2] : 0; - // 3) Pack the QMD: [count, then count × (dcr_addr, value)]. + // 3) Pack the QMD: [count, reserved, then count × (dcr_addr, value)]. std::vector qmd; qmd.push_back(0); // count placeholder + qmd.push_back(0); auto put = [&](uint32_t addr, uint32_t val) { qmd.push_back(addr); qmd.push_back(val); }; @@ -664,13 +818,45 @@ vx_result_t cmd_stage_qmds(Device* device_, const std::vector& recs, put(VX_DCR_KMU_CLUSTER_DIM_Y, rec.cluster[1]); put(VX_DCR_KMU_CLUSTER_DIM_Z, rec.cluster[2]); } - qmd[0] = uint32_t((qmd.size() - 1) / 2); // pair count + qmd[0] = uint32_t((qmd.size() - 2) / 2); // pair count // 4) Stage the QMD into device memory when the CP decodes // CMD_LAUNCH_QMD; otherwise keep only the host copy that - // cmd_submit_launch replays as plain ring commands. + // cmd_submit_launch replays as plain ring commands. An indirect launch + // stages its descriptor: the header line, then the same QMD body. st.qmd_words = std::move(qmd); - if (device_->cp_supports_qmd()) { + if (rec.indirect) { + // The CP starts skipping at the command after this one, which in + // a draw descriptor is its own flush step when it launches. + const bool ild_full_flush = in_draw && !device_->cp_dma_llc_client(); + uint32_t ring_skip = (in_draw && !(rec.ild.ctl & vortex::CP_ILD_NO_LAUNCH)) ? 1 : 0; + for (uint32_t k = 1; k <= rec.skip_cmds; ++k) { + ring_skip += cmd_ring_count(recs[i + k], in_draw, ild_full_flush); + } + if (ring_skip > 0xFFFF) { + r = VX_ERR_INVALID_VALUE; + break; + } + vortex::cp_ild_header_t hdr = rec.ild; + hdr.skip_n = uint16_t(ring_skip); + hdr.qmd_count = st.qmd_words[0]; + const size_t pair_bytes = (st.qmd_words.size() - 2) * sizeof(uint32_t); + std::vector ild(vortex::CP_ILD_HEADER_BYTES + pair_bytes); + std::memcpy(ild.data(), &hdr, sizeof(hdr)); + std::memcpy(ild.data() + vortex::CP_ILD_HEADER_BYTES, + st.qmd_words.data() + 2, pair_bytes); + r = device_->args_slot_acquire(ild.size(), &st.qmd_addr, &st.qmd_pooled); + if (r != VX_SUCCESS) { + break; + } + st.qmd_active = true; + st.indirect = true; + st.launches = (rec.ild.ctl & vortex::CP_ILD_NO_LAUNCH) == 0; + r = device_->dev_write(st.qmd_addr, ild.data(), ild.size()); + if (r != VX_SUCCESS) { + break; + } + } else if (device_->cp_supports_qmd()) { const uint64_t qmd_bytes = st.qmd_words.size() * sizeof(uint32_t); bool clean = false; r = device_->args_slot_acquire(qmd_bytes, &st.qmd_addr, &st.qmd_pooled, &clean); @@ -687,13 +873,19 @@ vx_result_t cmd_stage_qmds(Device* device_, const std::vector& recs, // replay the descriptor pairs as CMD_DCR_WRITEs followed by a plain // CMD_LAUNCH. vx_result_t cmd_submit_launch(Device* device_, const CmdStaged& st) { + if (st.qmd_active && st.qmd_addr % vortex::CP_LAUNCH_DESC_ALIGN != 0) { + return VX_ERR_INTERNAL; + } + if (st.indirect) { + return device_->cp_submit_launch_indirect(st.qmd_addr, st.launches); + } if (device_->cp_supports_qmd()) { return device_->cp_submit_launch_qmd(st.qmd_addr); } const auto& qmd = st.qmd_words; const uint32_t count = qmd.empty() ? 0 : qmd[0]; for (uint32_t k = 0; k < count; ++k) { - auto r = device_->cp_submit_dcr_write(qmd[1 + 2 * k], qmd[2 + 2 * k]); + auto r = device_->cp_submit_dcr_write(qmd[2 + 2 * k], qmd[3 + 2 * k]); if (r != VX_SUCCESS) return r; } return device_->cp_submit_launch(); @@ -708,7 +900,7 @@ vx_result_t Queue::enqueue_commands(const vx_command_t* commands, std::vector recs; std::vector retained; // released if enqueue() fails (work won't run) - auto rb = cmd_build_recs(commands, count, recs, retained); + auto rb = cmd_build_recs(device_, commands, count, recs, retained); if (rb != VX_SUCCESS) return rb; Command cmd; @@ -730,7 +922,7 @@ vx_result_t Queue::enqueue_commands(const vx_command_t* commands, // Step 1 — stage each launch's args + QMD into device scratch. std::vector staged(recs.size()); const uint32_t tpw = (uint32_t)num_threads; (void)num_warps; - vx_result_t r = cmd_stage_qmds(device_, recs, staged, tpw); + vx_result_t r = cmd_stage_qmds(device_, recs, staged, tpw, false); // Step 2 — emit the whole sequence as one ring batch: each launch is a // single CMD_LAUNCH_QMD (the CP replays the staged descriptor); FF/state @@ -738,13 +930,15 @@ vx_result_t Queue::enqueue_commands(const vx_command_t* commands, if (r == VX_SUCCESS) { std::lock_guard g(enqueue_mu_); *s = now_ns(); + // Programmed ahead of the batch so it cannot land inside a range an + // indirect launch skips. + r = device_->ensure_mmu_satp(); device_->cp_batch_begin(); - for (size_t i = 0; i < recs.size(); ++i) { + for (size_t i = 0; i < recs.size() && r == VX_SUCCESS; ++i) { const CmdRec& rec = recs[i]; r = rec.is_launch ? cmd_submit_launch(device_, staged[i]) : device_->cp_submit_dcr_write(rec.dcr_addr, rec.dcr_value); - if (r != VX_SUCCESS) break; } // Always close the batch (commit + poll + drain) even on a mid-batch // error so the partial sequence retires and the lock releases. @@ -779,7 +973,7 @@ vx_result_t Queue::enqueue_draw(const vx_command_t* commands, std::vector recs; std::vector retained; - auto rb = cmd_build_recs(commands, count, recs, retained); + auto rb = cmd_build_recs(device_, commands, count, recs, retained); if (rb != VX_SUCCESS) return rb; Command cmd; @@ -799,18 +993,6 @@ vx_result_t Queue::enqueue_draw(const vx_command_t* commands, return rq; } - // Step 1 — stage each launch's args + QMD into device scratch. - std::vector staged(recs.size()); - const uint32_t tpw = (uint32_t)num_threads; (void)num_warps; - vx_result_t r = cmd_stage_qmds(device_, recs, staged, tpw); - - // Step 2 — build the resident draw descriptor: [u32 num_steps] then - // 28-byte cmd-record steps. A launch becomes a CMD_LAUNCH_QMD step - // followed by a CMD_CACHE_FLUSH step — the same sequence the ring batch - // streams (cp_submit_launch_qmd appends a flush after every launch), so - // OP_DRAW executes a byte-identical program. The whole draw is then a - // single OP_DRAW ring command the CP expands on-device. - // // Only when the CP advertises OP_DRAW decode (CP DEV_CAPS bit 25). On a // CP without it (e.g. an RTL CP whose OP_DRAW mirror is not yet // synth-validated), fall back to streaming the same launches + DCRs as a @@ -819,6 +1001,17 @@ vx_result_t Queue::enqueue_draw(const vx_command_t* commands, // the QMD decoder (and its staged descriptors). const bool use_op_draw = device_->cp_supports_draw() && device_->cp_supports_qmd(); + + // Step 1 — stage each launch's args + QMD into device scratch. + std::vector staged(recs.size()); + const uint32_t tpw = (uint32_t)num_threads; (void)num_warps; + vx_result_t r = cmd_stage_qmds(device_, recs, staged, tpw, use_op_draw); + + // Step 2 — build the resident draw descriptor: [u32 num_steps] then + // 28-byte cmd-record steps. A launch becomes a CMD_LAUNCH_QMD step + // followed by an L1-only CMD_CACHE_FLUSH step, so each stage's results + // reach the last-level cache before the next stage launches. The whole + // draw is then a single OP_DRAW ring command the CP expands on-device. uint64_t desc_addr = 0; bool desc_pooled = false; bool desc_active = false; if (r == VX_SUCCESS && use_op_draw) { std::vector desc(4, 0); // header placeholder @@ -834,7 +1027,16 @@ vx_result_t Queue::enqueue_draw(const vx_command_t* commands, }; for (size_t i = 0; i < recs.size(); ++i) { const CmdRec& rec = recs[i]; - if (rec.is_launch) { + if (rec.is_launch && staged[i].indirect) { + // the CP reads the predicate and grid an earlier kernel wrote + if (!device_->cp_dma_llc_client()) { + put_step(CP_OP_CACHE_FLUSH, (VX_FENCE_ACQ | VX_FENCE_REL | VX_FENCE_SYS) << VX_CP_FLUSH_OP_SHIFT, num_cores, 0); + } + put_step(CP_OP_LAUNCH_IND, 0, staged[i].qmd_addr, 0); + if (staged[i].launches) { + put_step(CP_OP_CACHE_FLUSH, (VX_FENCE_ACQ | VX_FENCE_REL) << VX_CP_FLUSH_OP_SHIFT, num_cores, 0); + } + } else if (rec.is_launch) { put_step(CP_OP_LAUNCH_QMD, 0, staged[i].qmd_addr, 0); put_step(CP_OP_CACHE_FLUSH, (VX_FENCE_ACQ | VX_FENCE_REL) << VX_CP_FLUSH_OP_SHIFT, num_cores, 0); } else { @@ -859,13 +1061,13 @@ vx_result_t Queue::enqueue_draw(const vx_command_t* commands, if (use_op_draw) { r = device_->cp_submit_draw(desc_addr); } else { + r = device_->ensure_mmu_satp(); device_->cp_batch_begin(); - for (size_t i = 0; i < recs.size(); ++i) { + for (size_t i = 0; i < recs.size() && r == VX_SUCCESS; ++i) { const CmdRec& rec = recs[i]; r = rec.is_launch ? cmd_submit_launch(device_, staged[i]) : device_->cp_submit_dcr_write(rec.dcr_addr, rec.dcr_value); - if (r != VX_SUCCESS) break; } auto re = device_->cp_batch_end(); if (r == VX_SUCCESS) r = re; diff --git a/sw/runtime/common/vortex2_internal.h b/sw/runtime/common/vortex2_internal.h index 4598417550..f1d8f50977 100644 --- a/sw/runtime/common/vortex2_internal.h +++ b/sw/runtime/common/vortex2_internal.h @@ -239,7 +239,7 @@ class Device : public RefCounted { vx_result_t cp_submit_launch(); // Post one CMD_LAUNCH_QMD: the CP reads the KMU descriptor (a - // {count,(dcr_addr,value)...} list the caller staged to device memory at + // {count,reserved,(dcr_addr,value)...} list the caller staged to device memory at // `qmd_addr`) and replays it, then pulses start — one ring command in // place of a launch's ~18 CMD_DCR_WRITEs (NVIDIA QMD model). Flushed like // cp_submit_launch. Batch-aware. @@ -251,10 +251,18 @@ class Device : public RefCounted { // trailing COUT-drain discipline as cp_submit_launch_qmd. vx_result_t cp_submit_draw(uint64_t desc_addr); + // Post one CMD_LAUNCH_INDIRECT: arg0 = device address of a staged indirect + // launch descriptor (header + QMD body). cp_ring_append_ flushes ahead of + // it as for a transfer that reads device memory, and treats it as a + // launch whether or not it runs. Batch-aware. + vx_result_t cp_submit_launch_indirect(uint64_t ild_addr, bool launches); + // True iff the CP decodes CMD_DRAW (OP_DRAW). When false, vx_enqueue_draw // streams the draw as a ring batch instead (functionally identical). bool cp_supports_draw() const { return cp_supports_draw_; } bool cp_supports_qmd() const { return cp_supports_qmd_; } + bool cp_supports_indirect() const { return cp_supports_indirect_; } + bool cp_dma_llc_client() const { return cp_dma_llc_client_; } // Program the device MMU's SATP once, ahead of the first launch that // could translate. Called from every launch path. @@ -514,8 +522,10 @@ class Device : public RefCounted { // the OP_DRAW mirror). Discovered at open. bool cp_supports_draw_ = false; bool cp_supports_qmd_ = false; + // CP decodes CMD_LAUNCH_INDIRECT (CP DEV_CAPS bit 28). + bool cp_supports_indirect_ = false; // The CP DMA reaches device memory through the last-level cache (CP - // DEV_CAPS bit 28), so transfers never need that cache flushed. + // DEV_CAPS bit 29), so transfers never need that cache flushed. bool cp_dma_llc_client_ = false; class CpMemIO; std::unique_ptr vm_io_; diff --git a/sw/runtime/include/vortex2.h b/sw/runtime/include/vortex2.h index 28a9ef07e9..49e4051d10 100644 --- a/sw/runtime/include/vortex2.h +++ b/sw/runtime/include/vortex2.h @@ -74,6 +74,7 @@ typedef struct vx_kernel* vx_kernel_h; #define VX_CAPS_VM_SUPPORT 0xF // 1 if the device has an MMU (VM), else 0 #define VX_CAPS_VM_PINNED_SIZE 0x10 // pinned-region total size (bytes); 0 if disabled #define VX_CAPS_VM_PINNED_FREE 0x11 // pinned-region free size (bytes); 0 if disabled +#define VX_CAPS_CP_INDIRECT 0x12 // 1 if launches accept vx_launch_indirect_t, else 0 // ============================================================================ // Device ISA flags (decode a VX_CAPS_ISA_FLAGS query result) @@ -209,6 +210,54 @@ typedef struct { uint32_t cluster_dim[3]; } vx_launch_info_t; +// ----- Extension structs chained on an info struct's `next` ----- +// +// Each starts with {struct_size, next, type}; `type` names the struct. +typedef enum { + VX_STRUCT_TYPE_LAUNCH_INDIRECT = 1 +} vx_struct_type_e; + +// Indirect launch (chained on vx_launch_info_t.next; requires +// VX_CAPS_CP_INDIRECT). The command processor evaluates it on the device when +// the launch reaches the head of the queue, with no host read-back: +// +// 1. pred_addr != 0: execute iff (*(uint32_t*)pred_addr > pred_ref), unsigned, +// inverted by VX_INDIRECT_PRED_INVERT. +// 2. record_addr != 0: grid_dim[d] = ceil(w / 2^grid_shift[d]), with w the +// 32-bit record word grid_word[d] (VX_INDIRECT_ONE: w = 1). For x, w is +// first replaced by max(w - x_bias, 0) / x_div (x_div 0 or 1: no divide). +// For a launch, dimensions at or above info->ndim are 1; the +// predicate-only form applies grid_word to all three. Any zero dimension +// skips the launch; a device-computed zero grid never starts a kernel. +// 3. Not executed: the launch and the next `skip_count` commands of the same +// vx_enqueue_commands / vx_enqueue_draw call are skipped (0 for +// vx_enqueue_launch). +// 4. VX_INDIRECT_NO_LAUNCH: steps 1-3 only (kernel NULL, ndim 0); a predicate +// that guards the commands after it, e.g. conditional rendering. +// +// The record and predicate are read from device memory below the caches. +// Device-produced indirect data must be written by a launch that precedes this +// one in queue order (each launch's results are flushed before the next +// command), or by a host/DMA write. +#define VX_INDIRECT_ONE 0xFu +#define VX_INDIRECT_PRED_INVERT (1u << 0) +#define VX_INDIRECT_NO_LAUNCH (1u << 1) + +typedef struct { + size_t struct_size; + const void* next; + vx_struct_type_e type; // VX_STRUCT_TYPE_LAUNCH_INDIRECT + uint64_t record_addr; // device address of the grid record, 4-byte aligned; 0 = grid from info + uint8_t grid_word [3]; // record word index 0..14, or VX_INDIRECT_ONE + uint8_t grid_shift[3]; // 0..15 + uint32_t x_bias; + uint32_t x_div; + uint64_t pred_addr; // device address, 4-byte aligned; 0 = unconditional + uint32_t pred_ref; + uint32_t flags; // VX_INDIRECT_* + uint32_t skip_count; +} vx_launch_indirect_t; + // 3D-strided DMA descriptor for the rect enqueue ops. Mirrors OpenCL 1.2's // clEnqueue{Read,Write,Copy}BufferRect parameter block. // diff --git a/tests/regression/indirect/Makefile b/tests/regression/indirect/Makefile new file mode 100644 index 0000000000..6bc426d4d2 --- /dev/null +++ b/tests/regression/indirect/Makefile @@ -0,0 +1,16 @@ +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +PROJECT := indirect + +SRC_DIR := $(VORTEX_HOME)/tests/regression/$(PROJECT) + +SRCS := $(SRC_DIR)/main.cpp + +VX_SRCS := $(SRC_DIR)/kernel.cpp + +KERNEL_LIB := vortex2 + +OPTS ?= -n16384 + +include ../common.mk diff --git a/tests/regression/indirect/common.h b/tests/regression/indirect/common.h new file mode 100644 index 0000000000..bf9689787b --- /dev/null +++ b/tests/regression/indirect/common.h @@ -0,0 +1,32 @@ +#ifndef _COMMON_H_ +#define _COMMON_H_ + +#include + +#define PRODUCE_MAX_WORDS 32 + +// produce_k: copies words[] to dst (device-produced indirect arguments). +typedef struct { + uint64_t dst_addr; + uint32_t num_words; + uint32_t words[PRODUCE_MAX_WORDS]; +} produce_arg_t; + +// vecadd_k: c = a + b. scale_k: c = a * k. poison_k: c = POISON. +typedef struct { + uint64_t a_addr; + uint64_t b_addr; + uint64_t c_addr; + uint32_t n; + uint32_t k; +} vec_arg_t; + +// mark_k: hits[linear block] += 1; dims = {gridDim.xyz, launches}. +typedef struct { + uint64_t hits_addr; + uint64_t dims_addr; +} mark_arg_t; + +#define POISON 0xDEADBEEFu + +#endif diff --git a/tests/regression/indirect/kernel.cpp b/tests/regression/indirect/kernel.cpp new file mode 100644 index 0000000000..4674448e32 --- /dev/null +++ b/tests/regression/indirect/kernel.cpp @@ -0,0 +1,62 @@ +#include +#include "common.h" + +__kernel void produce_k(produce_arg_t* __UNIFORM__ arg) { + if (blockIdx.x != 0 || threadIdx.x != 0) { + return; + } + auto dst = reinterpret_cast(arg->dst_addr); + for (uint32_t i = 0; i < arg->num_words; ++i) { + dst[i] = arg->words[i]; + } +} + +static inline uint32_t global_id() { + return blockIdx.x * blockDim.x + threadIdx.x; +} + +__kernel void vecadd_k(vec_arg_t* __UNIFORM__ arg) { + uint32_t i = global_id(); + if (i >= arg->n) { + return; + } + auto a = reinterpret_cast(arg->a_addr); + auto b = reinterpret_cast(arg->b_addr); + auto c = reinterpret_cast(arg->c_addr); + c[i] = a[i] + b[i]; +} + +__kernel void scale_k(vec_arg_t* __UNIFORM__ arg) { + uint32_t i = global_id(); + if (i >= arg->n) { + return; + } + auto a = reinterpret_cast(arg->a_addr); + auto c = reinterpret_cast(arg->c_addr); + c[i] = a[i] * arg->k; +} + +__kernel void poison_k(vec_arg_t* __UNIFORM__ arg) { + uint32_t i = global_id(); + if (i >= arg->n) { + return; + } + auto c = reinterpret_cast(arg->c_addr); + c[i] = POISON; +} + +__kernel void mark_k(mark_arg_t* __UNIFORM__ arg) { + if (threadIdx.x != 0 || threadIdx.y != 0 || threadIdx.z != 0) { + return; + } + auto hits = reinterpret_cast(arg->hits_addr); + uint32_t b = (blockIdx.z * gridDim.y + blockIdx.y) * gridDim.x + blockIdx.x; + hits[b] += 1; + if (b == 0) { + auto dims = reinterpret_cast(arg->dims_addr); + dims[0] = gridDim.x; + dims[1] = gridDim.y; + dims[2] = gridDim.z; + dims[3] += 1; + } +} diff --git a/tests/regression/indirect/main.cpp b/tests/regression/indirect/main.cpp new file mode 100644 index 0000000000..8a60dde182 --- /dev/null +++ b/tests/regression/indirect/main.cpp @@ -0,0 +1,196 @@ +// Device-sourced launch arguments through the command processor. +// +// One ring batch: +// 1. produce_k writes {n, 1, 1, 0} to a record in device memory. +// 2. vecadd_k launches indirectly: grid.x = ceil(record[0] / block), so the +// grid exists only on the device. +// 3. poison_k is predicated on record[3] > 0, which is false: it and the +// poison_k behind it (its skip range) must not run. +// 4. scale_k depends on vecadd_k's output. +// The host never reads the record; it checks the final result only. + +#include +#include "common.h" + +#include +#include +#include +#include +#include + +#define CHECK(expr) do { \ + vx_result_t _r = (expr); \ + if (_r != VX_SUCCESS) { \ + std::printf("Error: '%s' returned %s\n", #expr, \ + vx_result_string(_r)); \ + std::exit(1); \ + } \ + } while (0) + +static const char* kernel_file = "kernel.vxbin"; +static uint32_t size = 16384; + +static void parse_args(int argc, char** argv) { + int c; + while ((c = getopt(argc, argv, "n:k:h")) != -1) { + switch (c) { + case 'n': size = std::atoi(optarg); break; + case 'k': kernel_file = optarg; break; + default: + std::printf("Usage: [-k kernel] [-n size] [-h]\n"); + std::exit(c == 'h' ? 0 : 1); + } + } +} + +int main(int argc, char** argv) { + parse_args(argc, argv); + std::printf("indirect: size=%u\n", size); + + vx_device_h dev = nullptr; + CHECK(vx_device_open(0, &dev)); + uint64_t has_indirect = 0; + CHECK(vx_device_query(dev, VX_CAPS_CP_INDIRECT, &has_indirect)); + if (!has_indirect) { + std::printf("Error: device does not support indirect launch\n"); + return 1; + } + uint64_t nt = 0, nw = 0; + CHECK(vx_device_query(dev, VX_CAPS_NUM_THREADS, &nt)); + CHECK(vx_device_query(dev, VX_CAPS_NUM_WARPS, &nw)); + const uint32_t block = uint32_t(nt * nw); + if ((block & (block - 1)) != 0) { + std::printf("Error: block size %u is not a power of two\n", block); + return 1; + } + uint8_t block_log2 = 0; + while ((1u << block_log2) < block) { + ++block_log2; + } + + vx_queue_h q = nullptr; + CHECK(vx_queue_create(dev, nullptr, &q)); + + const uint64_t bytes = uint64_t(size) * sizeof(uint32_t); + vx_buffer_h a_buf, b_buf, c_buf, d_buf, rec_buf; + CHECK(vx_buffer_create(dev, bytes, VX_MEM_READ, &a_buf)); + CHECK(vx_buffer_create(dev, bytes, VX_MEM_READ, &b_buf)); + CHECK(vx_buffer_create(dev, bytes, VX_MEM_READ_WRITE, &c_buf)); + CHECK(vx_buffer_create(dev, bytes, VX_MEM_WRITE, &d_buf)); + CHECK(vx_buffer_create(dev, 64, VX_MEM_READ_WRITE, &rec_buf)); + uint64_t a_addr, b_addr, c_addr, d_addr, rec_addr; + CHECK(vx_buffer_address(a_buf, &a_addr)); + CHECK(vx_buffer_address(b_buf, &b_addr)); + CHECK(vx_buffer_address(c_buf, &c_addr)); + CHECK(vx_buffer_address(d_buf, &d_addr)); + CHECK(vx_buffer_address(rec_buf, &rec_addr)); + + std::vector h_a(size), h_b(size), h_d(size); + for (uint32_t i = 0; i < size; ++i) { + h_a[i] = i * 7 + 1; + h_b[i] = i ^ 0x55; + } + std::vector zeros(16, 0); + CHECK(vx_enqueue_write(q, a_buf, 0, h_a.data(), bytes, 0, nullptr, nullptr)); + CHECK(vx_enqueue_write(q, b_buf, 0, h_b.data(), bytes, 0, nullptr, nullptr)); + CHECK(vx_enqueue_write(q, rec_buf, 0, zeros.data(), 64, 0, nullptr, nullptr)); + + vx_module_h mod = nullptr; + CHECK(vx_module_load_file(dev, kernel_file, &mod)); + vx_kernel_h k_produce, k_vecadd, k_scale, k_poison; + CHECK(vx_module_get_kernel(mod, "produce_k", &k_produce)); + CHECK(vx_module_get_kernel(mod, "vecadd_k", &k_vecadd)); + CHECK(vx_module_get_kernel(mod, "scale_k", &k_scale)); + CHECK(vx_module_get_kernel(mod, "poison_k", &k_poison)); + + produce_arg_t pa = {}; + pa.dst_addr = rec_addr; + pa.num_words = 4; + pa.words[0] = size; + pa.words[1] = 1; + pa.words[2] = 1; + pa.words[3] = 0; + vec_arg_t va = {a_addr, b_addr, c_addr, size, 0}; + vec_arg_t sa = {c_addr, 0, d_addr, size, 3}; + vec_arg_t xa = {0, 0, c_addr, size, 0}; + + auto make_launch = [&](vx_kernel_h k, const void* args, size_t args_size, + uint32_t grid) { + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.kernel = k; + li.args_host = args; + li.args_size = args_size; + li.ndim = 1; + li.grid_dim[0] = grid; + li.block_dim[0] = block; + return li; + }; + const uint32_t grid = (size + block - 1) / block; + vx_launch_info_t li_produce = make_launch(k_produce, &pa, sizeof(pa), 1); + li_produce.block_dim[0] = 1; + vx_launch_info_t li_vecadd = make_launch(k_vecadd, &va, sizeof(va), 0); + vx_launch_info_t li_poison = make_launch(k_poison, &xa, sizeof(xa), grid); + vx_launch_info_t li_poison2 = make_launch(k_poison, &xa, sizeof(xa), grid); + vx_launch_info_t li_scale = make_launch(k_scale, &sa, sizeof(sa), grid); + + vx_launch_indirect_t ind_vecadd = {}; + ind_vecadd.struct_size = sizeof(ind_vecadd); + ind_vecadd.type = VX_STRUCT_TYPE_LAUNCH_INDIRECT; + ind_vecadd.record_addr = rec_addr; + ind_vecadd.grid_word[0] = 0; + ind_vecadd.grid_shift[0] = block_log2; + li_vecadd.next = &ind_vecadd; + + vx_launch_indirect_t ind_poison = {}; + ind_poison.struct_size = sizeof(ind_poison); + ind_poison.type = VX_STRUCT_TYPE_LAUNCH_INDIRECT; + ind_poison.pred_addr = rec_addr + 12; + ind_poison.pred_ref = 0; + ind_poison.skip_count = 1; + li_poison.next = &ind_poison; + + vx_command_t cmds[5] = {}; + const vx_launch_info_t* order[5] = {&li_produce, &li_vecadd, &li_poison, + &li_poison2, &li_scale}; + for (int i = 0; i < 5; ++i) { + cmds[i].type = VX_COMMAND_LAUNCH; + cmds[i].data.launch = order[i]; + } + CHECK(vx_enqueue_commands(q, cmds, 5, 0, nullptr, nullptr)); + CHECK(vx_enqueue_read(q, h_d.data(), d_buf, 0, bytes, 0, nullptr, nullptr)); + CHECK(vx_queue_finish(q, VX_TIMEOUT_INFINITE)); + + int errors = 0; + for (uint32_t i = 0; i < size; ++i) { + const uint32_t ref = (h_a[i] + h_b[i]) * 3; + if (h_d[i] != ref) { + if (errors < 10) { + std::printf("*** error: [%u] expected=0x%x, actual=0x%x\n", i, ref, h_d[i]); + } + ++errors; + } + } + + vx_device_dump_perf(dev, stdout); + + vx_kernel_release(k_poison); + vx_kernel_release(k_scale); + vx_kernel_release(k_vecadd); + vx_kernel_release(k_produce); + vx_module_release(mod); + vx_buffer_release(rec_buf); + vx_buffer_release(d_buf); + vx_buffer_release(c_buf); + vx_buffer_release(b_buf); + vx_buffer_release(a_buf); + vx_queue_release(q); + vx_device_release(dev); + + if (errors != 0) { + std::printf("FAILED! (%d errors)\n", errors); + return 1; + } + std::printf("PASSED!\n"); + return 0; +} diff --git a/tests/runtime/Makefile b/tests/runtime/Makefile index c902d46fcb..0edb46a594 100644 --- a/tests/runtime/Makefile +++ b/tests/runtime/Makefile @@ -11,6 +11,8 @@ RT_DIR := $(ROOT_DIR)/sw/runtime # it at the `basic` regression kernel image. The runtime() target in # ci/regression.sh builds this before invoking run-simx. VXBIN := $(ROOT_DIR)/tests/regression/basic/kernel.vxbin +# test_indirect launches the kernels of the `indirect` regression image. +INDIRECT_VXBIN := $(ROOT_DIR)/tests/regression/indirect/kernel.vxbin CXXFLAGS += -std=c++17 -Wall -Wextra -Wfatal-errors -Werror CXXFLAGS += -O2 -DNDEBUG @@ -22,7 +24,8 @@ CXXFLAGS += $(XCONFIGS) LDFLAGS += -Wl,-rpath,$(RT_DIR) -L$(RT_DIR) -lvortex -pthread -TESTS := test_basic test_async test_timeline_events test_module_kernel test_rect_fill +TESTS := test_basic test_async test_timeline_events test_module_kernel test_rect_fill \ + test_indirect .PHONY: all run run-simx run-xrt clean @@ -43,6 +46,9 @@ test_module_kernel: $(VORTEX_HOME)/tests/runtime/test_module_kernel.cpp test_rect_fill: $(VORTEX_HOME)/tests/runtime/test_rect_fill.cpp $(CXX) $(CXXFLAGS) $< $(LDFLAGS) -o $@ +test_indirect: $(VORTEX_HOME)/tests/runtime/test_indirect.cpp $(VORTEX_HOME)/tests/regression/indirect/common.h + $(CXX) $(CXXFLAGS) $< $(LDFLAGS) -o $@ + # Bare run — honours whatever VORTEX_DRIVER is in the environment. run: $(TESTS) @for t in $(TESTS); do \ @@ -56,14 +62,14 @@ run-simx: $(TESTS) @for t in $(TESTS); do \ echo "[RUN] $$t (simx)"; \ VORTEX_DRIVER=simx LD_LIBRARY_PATH=$(RT_DIR) \ - VX_TEST_VXBIN=$(VXBIN) ./$$t || exit 1; \ + VX_TEST_VXBIN=$(VXBIN) VX_TEST_INDIRECT_VXBIN=$(INDIRECT_VXBIN) ./$$t || exit 1; \ done run-xrt: $(TESTS) @for t in $(TESTS); do \ echo "[RUN] $$t (xrt)"; \ VORTEX_DRIVER=xrt LD_LIBRARY_PATH=$(RT_DIR) \ - VX_TEST_VXBIN=$(VXBIN) ./$$t || exit 1; \ + VX_TEST_VXBIN=$(VXBIN) VX_TEST_INDIRECT_VXBIN=$(INDIRECT_VXBIN) ./$$t || exit 1; \ done clean: diff --git a/tests/runtime/test_indirect.cpp b/tests/runtime/test_indirect.cpp new file mode 100644 index 0000000000..d42038aa88 --- /dev/null +++ b/tests/runtime/test_indirect.cpp @@ -0,0 +1,792 @@ +// Copyright © 2019-2023 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 + +// ============================================================================ +// test_indirect.cpp +// +// Exercises vx_launch_indirect_t (command-processor indirect launch): +// - VX_CAPS_CP_INDIRECT +// - a grid written by a kernel and consumed by the next launch, 1D and 3D +// - a zero in each grid dimension skips the launch and its skip range +// - predicate true / false / inverted, and a predicate-only command +// - a skip range spanning launches and DCR writes, in a ring batch and in a +// draw bundle +// - a draw bundle of several hundred launches, run to its last command +// - an indirect-count unroll with the count below, at and above the bound +// - byte-count derivation (bias, odd divisor, ceil-shift) +// - a record whose words straddle a cache line +// - vx_enqueue_launch with a chained struct +// - validation failures +// +// Kernels come from tests/regression/indirect/kernel.vxbin (VX_TEST_INDIRECT_VXBIN +// or -k ). +// +// PASS: all sections print [ OK ], exit code 0. +// ============================================================================ + +#include +#include + +#include "../regression/indirect/common.h" + +#include +#include +#include +#include +#include +#include + +#define CHECK_VX(expr) do { \ + vx_result_t _r = (expr); \ + if (_r != VX_SUCCESS) { \ + fprintf(stderr, "FAILED at %s:%d: '%s' returned %s\n", \ + __FILE__, __LINE__, #expr, vx_result_string(_r)); \ + return 1; \ + } \ +} while (0) + +#define EXPECT(cond, ...) do { \ + if (!(cond)) { \ + fprintf(stderr, "FAILED at %s:%d: ", __FILE__, __LINE__); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n"); \ + return 1; \ + } \ +} while (0) + +namespace { + +constexpr uint32_t HITS_WORDS = 256; +constexpr uint32_t DIMS_WORDS = 16; + +vx_device_h g_dev = nullptr; +vx_queue_h g_q = nullptr; +vx_kernel_h g_produce = nullptr; +vx_kernel_h g_mark = nullptr; +uint32_t g_nt = 1; + +// One mark_k target: hits[linear block] and dims {grid.xyz, launches}. +struct Mark { + vx_buffer_h hits = nullptr; + vx_buffer_h dims = nullptr; + mark_arg_t arg = {}; + std::vector h_hits = std::vector(HITS_WORDS); + std::vector h_dims = std::vector(DIMS_WORDS); +}; + +int mark_create(Mark& m) { + CHECK_VX(vx_buffer_create(g_dev, HITS_WORDS * 4, VX_MEM_READ_WRITE, &m.hits)); + CHECK_VX(vx_buffer_create(g_dev, DIMS_WORDS * 4, VX_MEM_READ_WRITE, &m.dims)); + CHECK_VX(vx_buffer_address(m.hits, &m.arg.hits_addr)); + CHECK_VX(vx_buffer_address(m.dims, &m.arg.dims_addr)); + return 0; +} + +int mark_clear(Mark& m) { + std::vector z(HITS_WORDS, 0); + CHECK_VX(vx_enqueue_write(g_q, m.hits, 0, z.data(), HITS_WORDS * 4, 0, nullptr, nullptr)); + CHECK_VX(vx_enqueue_write(g_q, m.dims, 0, z.data(), DIMS_WORDS * 4, 0, nullptr, nullptr)); + CHECK_VX(vx_queue_finish(g_q, VX_TIMEOUT_INFINITE)); + return 0; +} + +int mark_read(Mark& m) { + CHECK_VX(vx_enqueue_read(g_q, m.h_hits.data(), m.hits, 0, HITS_WORDS * 4, 0, nullptr, nullptr)); + CHECK_VX(vx_enqueue_read(g_q, m.h_dims.data(), m.dims, 0, DIMS_WORDS * 4, 0, nullptr, nullptr)); + CHECK_VX(vx_queue_finish(g_q, VX_TIMEOUT_INFINITE)); + return 0; +} + +void mark_release(Mark& m) { + vx_buffer_release(m.hits); + vx_buffer_release(m.dims); +} + +// Expect exactly `launches` launches of a gx*gy*gz grid (0 launches: untouched). +int mark_expect(Mark& m, uint32_t launches, uint32_t gx, uint32_t gy, uint32_t gz, + const char* what) { + if (mark_read(m)) { + return 1; + } + EXPECT(m.h_dims[3] == launches, "%s: %u launches, expected %u", what, m.h_dims[3], launches); + const uint32_t blocks = launches ? gx * gy * gz : 0; + if (launches) { + EXPECT(m.h_dims[0] == gx && m.h_dims[1] == gy && m.h_dims[2] == gz, + "%s: grid %ux%ux%u, expected %ux%ux%u", what, + m.h_dims[0], m.h_dims[1], m.h_dims[2], gx, gy, gz); + } + for (uint32_t b = 0; b < HITS_WORDS; ++b) { + const uint32_t want = (b < blocks) ? launches : 0; + EXPECT(m.h_hits[b] == want, "%s: block %u ran %u times, expected %u", + what, b, m.h_hits[b], want); + } + return 0; +} + +vx_launch_info_t mark_launch(const Mark& m, uint32_t ndim, uint32_t gx, uint32_t gy, + uint32_t gz) { + vx_launch_info_t li = {}; + li.struct_size = sizeof(li); + li.kernel = g_mark; + li.args_host = &m.arg; + li.args_size = sizeof(m.arg); + li.ndim = ndim; + li.grid_dim[0] = gx; + li.grid_dim[1] = gy; + li.grid_dim[2] = gz; + li.block_dim[0] = g_nt; + li.block_dim[1] = 1; + li.block_dim[2] = 1; + return li; +} + +vx_launch_indirect_t indirect() { + vx_launch_indirect_t x = {}; + x.struct_size = sizeof(x); + x.type = VX_STRUCT_TYPE_LAUNCH_INDIRECT; + x.grid_word[0] = 0; + x.grid_word[1] = 1; + x.grid_word[2] = 2; + return x; +} + +vx_command_t launch_cmd(const vx_launch_info_t* li) { + vx_command_t c = {}; + c.type = VX_COMMAND_LAUNCH; + c.data.launch = li; + return c; +} + +vx_command_t dcr_cmd(uint32_t addr, uint32_t value) { + vx_command_t c = {}; + c.type = VX_COMMAND_DCR_WRITE; + c.data.dcr.addr = addr; + c.data.dcr.value = value; + return c; +} + +vx_result_t submit(const std::vector& cmds, bool bundle = false) { + vx_result_t r = bundle + ? vx_enqueue_draw(g_q, cmds.data(), uint32_t(cmds.size()), 0, nullptr, nullptr) + : vx_enqueue_commands(g_q, cmds.data(), uint32_t(cmds.size()), 0, nullptr, nullptr); + if (r != VX_SUCCESS) { + return r; + } + return vx_queue_finish(g_q, VX_TIMEOUT_INFINITE); +} + +// Device scratch for records / predicates, written by the host. +struct Words { + vx_buffer_h buf = nullptr; + uint64_t addr = 0; +}; + +int words_create(Words& w, uint32_t bytes) { + CHECK_VX(vx_buffer_create(g_dev, bytes, VX_MEM_READ_WRITE, &w.buf)); + CHECK_VX(vx_buffer_address(w.buf, &w.addr)); + return 0; +} + +int words_write(Words& w, uint32_t off, const std::vector& v) { + CHECK_VX(vx_enqueue_write(g_q, w.buf, off, v.data(), v.size() * 4, 0, nullptr, nullptr)); + CHECK_VX(vx_queue_finish(g_q, VX_TIMEOUT_INFINITE)); + return 0; +} + +// --------------------------------------------------------------------------- + +int test_caps() { + uint64_t v = 0; + CHECK_VX(vx_device_query(g_dev, VX_CAPS_CP_INDIRECT, &v)); + EXPECT(v == 1, "VX_CAPS_CP_INDIRECT = %llu, expected 1", (unsigned long long)v); + return 0; +} + +// A kernel writes the grid; the next launch in the same batch consumes it. +int test_device_grid() { + Words rec; + if (words_create(rec, 64)) { + return 1; + } + if (words_write(rec, 0, std::vector(16, 0))) { + return 1; + } + Mark m3, m1; + if (mark_create(m3) || mark_create(m1) || mark_clear(m3) || mark_clear(m1)) { + return 1; + } + produce_arg_t pa = {}; + pa.dst_addr = rec.addr; + pa.num_words = 4; + pa.words[0] = 3; + pa.words[1] = 5; + pa.words[2] = 2; + pa.words[3] = 37; + vx_launch_info_t lp = {}; + lp.struct_size = sizeof(lp); + lp.kernel = g_produce; + lp.args_host = &pa; + lp.args_size = sizeof(pa); + lp.ndim = 1; + lp.grid_dim[0] = 1; + lp.block_dim[0] = 1; + + vx_launch_info_t l3 = mark_launch(m3, 3, 0, 0, 0); + vx_launch_indirect_t x3 = indirect(); + x3.record_addr = rec.addr; + l3.next = &x3; + + // 1D, word 3 (37) at shift 2 -> ceil(37 / 4) = 10 blocks. + vx_launch_info_t l1 = mark_launch(m1, 1, 0, 0, 0); + vx_launch_indirect_t x1 = indirect(); + x1.record_addr = rec.addr; + x1.grid_word[0] = 3; + x1.grid_shift[0] = 2; + l1.next = &x1; + + CHECK_VX(submit({launch_cmd(&lp), launch_cmd(&l3), launch_cmd(&l1)})); + if (mark_expect(m3, 1, 3, 5, 2, "device grid 3D") || + mark_expect(m1, 1, 10, 1, 1, "device grid 1D shift")) { + return 1; + } + mark_release(m3); + mark_release(m1); + vx_buffer_release(rec.buf); + return 0; +} + +// A zero dimension skips the launch and its skip range, never a later command. +int test_zero_dims() { + Words rec; + if (words_create(rec, 64)) { + return 1; + } + for (int d = 0; d < 3; ++d) { + std::vector w = {2, 2, 2}; + w[d] = 0; + if (words_write(rec, 0, w)) { + return 1; + } + Mark mz, ms, mr; + if (mark_create(mz) || mark_create(ms) || mark_create(mr) || + mark_clear(mz) || mark_clear(ms) || mark_clear(mr)) { + return 1; + } + vx_launch_info_t lz = mark_launch(mz, 3, 0, 0, 0); + vx_launch_indirect_t xz = indirect(); + xz.record_addr = rec.addr; + xz.skip_count = 1; + lz.next = &xz; + vx_launch_info_t ls = mark_launch(ms, 1, 1, 1, 1); + vx_launch_info_t lr = mark_launch(mr, 1, 2, 1, 1); + CHECK_VX(submit({launch_cmd(&lz), launch_cmd(&ls), launch_cmd(&lr)})); + if (mark_expect(mz, 0, 0, 0, 0, "zero-dim launch") || + mark_expect(ms, 0, 0, 0, 0, "zero-dim skip range") || + mark_expect(mr, 1, 2, 1, 1, "after zero-dim skip range")) { + fprintf(stderr, " (zero in dimension %d)\n", d); + return 1; + } + mark_release(mz); + mark_release(ms); + mark_release(mr); + } + vx_buffer_release(rec.buf); + return 0; +} + +// exec = (*pred > ref) ^ invert, unsigned. +int test_predicate() { + Words pred; + if (words_create(pred, 64) || words_write(pred, 0, {5, 0xFFFFFFFFu})) { + return 1; + } + struct Case { uint32_t off, ref; bool inv, runs; }; + const Case cases[] = { + {0, 4, false, true}, {0, 5, false, false}, + {0, 5, true, true}, {0, 4, true, false}, + {4, 0xFFFFFFFEu, false, true}, {4, 0xFFFFFFFFu, false, false}, + }; + for (const Case& c : cases) { + Mark m; + if (mark_create(m) || mark_clear(m)) { + return 1; + } + vx_launch_info_t l = mark_launch(m, 2, 2, 3, 1); + vx_launch_indirect_t x = indirect(); + x.pred_addr = pred.addr + c.off; + x.pred_ref = c.ref; + x.flags = c.inv ? VX_INDIRECT_PRED_INVERT : 0; + l.next = &x; + CHECK_VX(submit({launch_cmd(&l)})); + if (mark_expect(m, c.runs ? 1 : 0, 2, 3, 1, "predicate")) { + fprintf(stderr, " (pred word at +%u, ref=0x%x, invert=%d)\n", c.off, c.ref, c.inv); + return 1; + } + mark_release(m); + } + vx_buffer_release(pred.buf); + return 0; +} + +// A skip range of launch, DCR write, launch; the command after it runs. +int test_skip_range(bool bundle) { + Words pred; + if (words_create(pred, 64)) { + return 1; + } + for (uint32_t p = 0; p < 2; ++p) { + if (words_write(pred, 0, {p})) { + return 1; + } + Mark ma, mb, mc, md; + if (mark_create(ma) || mark_create(mb) || mark_create(mc) || mark_create(md) || + mark_clear(ma) || mark_clear(mb) || mark_clear(mc) || mark_clear(md)) { + return 1; + } + vx_launch_info_t la = mark_launch(ma, 1, 2, 1, 1); + vx_launch_indirect_t xa = indirect(); + xa.pred_addr = pred.addr; + xa.skip_count = 3; + la.next = &xa; + vx_launch_info_t lb = mark_launch(mb, 1, 3, 1, 1); + vx_launch_info_t lc = mark_launch(mc, 1, 4, 1, 1); + vx_launch_info_t ld = mark_launch(md, 1, 5, 1, 1); + CHECK_VX(submit({launch_cmd(&la), launch_cmd(&lb), + dcr_cmd(VX_DCR_KMU_LMEM_SIZE, 0), + launch_cmd(&lc), launch_cmd(&ld)}, bundle)); + const uint32_t n = p; + if (mark_expect(ma, n, 2, 1, 1, "skip head") || + mark_expect(mb, n, 3, 1, 1, "skip range launch 1") || + mark_expect(mc, n, 4, 1, 1, "skip range launch 2") || + mark_expect(md, 1, 5, 1, 1, "after skip range")) { + fprintf(stderr, " (pred=%u, %s)\n", p, bundle ? "draw bundle" : "ring batch"); + return 1; + } + mark_release(ma); + mark_release(mb); + mark_release(mc); + mark_release(md); + } + vx_buffer_release(pred.buf); + return 0; +} + +// A skipped launch whose range ends on a predicate-only guard. The guard is +// skipped too, so it cannot skip what follows it. A range that is short by the +// skipped launch's own trailing flush lands on the guard instead, which then +// skips the last launch. +int test_skip_into_guard(bool bundle) { + Words pred; + if (words_create(pred, 64) || words_write(pred, 0, {0})) { + return 1; + } + Mark ml, mm; + if (mark_create(ml) || mark_create(mm) || mark_clear(ml) || mark_clear(mm)) { + return 1; + } + vx_launch_info_t ll = mark_launch(ml, 1, 2, 1, 1); + vx_launch_indirect_t xl = indirect(); + xl.pred_addr = pred.addr; + xl.skip_count = 1; + ll.next = &xl; + vx_launch_info_t lg = {}; + lg.struct_size = sizeof(lg); + vx_launch_indirect_t xg = indirect(); + xg.pred_addr = pred.addr; + xg.flags = VX_INDIRECT_NO_LAUNCH; + xg.skip_count = 1; + lg.next = &xg; + vx_launch_info_t lm = mark_launch(mm, 1, 3, 1, 1); + CHECK_VX(submit({launch_cmd(&ll), launch_cmd(&lg), launch_cmd(&lm)}, bundle)); + if (mark_expect(ml, 0, 2, 1, 1, "skipped launch") || + mark_expect(mm, 1, 3, 1, 1, "launch after the skipped guard")) { + fprintf(stderr, " (%s)\n", bundle ? "draw bundle" : "ring batch"); + return 1; + } + mark_release(ml); + mark_release(mm); + vx_buffer_release(pred.buf); + return 0; +} + +// A predicate-only command guards the two launches behind it. +int test_no_launch(bool bundle) { + Words pred; + if (words_create(pred, 64)) { + return 1; + } + for (uint32_t p = 0; p < 2; ++p) { + if (words_write(pred, 0, {p})) { + return 1; + } + Mark ma, mb, mc; + if (mark_create(ma) || mark_create(mb) || mark_create(mc) || + mark_clear(ma) || mark_clear(mb) || mark_clear(mc)) { + return 1; + } + vx_launch_info_t lg = {}; + lg.struct_size = sizeof(lg); + vx_launch_indirect_t xg = indirect(); + xg.pred_addr = pred.addr; + xg.flags = VX_INDIRECT_NO_LAUNCH; + xg.skip_count = 2; + lg.next = &xg; + vx_launch_info_t la = mark_launch(ma, 1, 2, 1, 1); + vx_launch_info_t lb = mark_launch(mb, 1, 3, 1, 1); + vx_launch_info_t lc = mark_launch(mc, 1, 1, 1, 1); + CHECK_VX(submit({launch_cmd(&lg), launch_cmd(&la), launch_cmd(&lb), + launch_cmd(&lc)}, bundle)); + if (mark_expect(ma, p, 2, 1, 1, "guarded launch 1") || + mark_expect(mb, p, 3, 1, 1, "guarded launch 2") || + mark_expect(mc, 1, 1, 1, 1, "after guard")) { + fprintf(stderr, " (pred=%u, %s)\n", p, bundle ? "draw bundle" : "ring batch"); + return 1; + } + mark_release(ma); + mark_release(mb); + mark_release(mc); + } + vx_buffer_release(pred.buf); + return 0; +} + +// A draw bundle runs every command it holds, however many: the same commands +// as a ring batch, which the command processor streams to the end. Each launch +// is two of the bundle's steps, a launch and a flush. +int test_long_bundle() { + constexpr uint32_t N = 300; + Mark ma, mb; + if (mark_create(ma) || mark_create(mb) || mark_clear(ma) || mark_clear(mb)) { + return 1; + } + vx_launch_info_t la = mark_launch(ma, 1, 1, 1, 1); + vx_launch_info_t lb = mark_launch(mb, 1, 2, 1, 1); + std::vector cmds(N, launch_cmd(&la)); + cmds.push_back(launch_cmd(&lb)); + CHECK_VX(submit(cmds, true)); + if (mark_expect(ma, N, 1, 1, 1, "every launch of a long bundle") || + mark_expect(mb, 1, 2, 1, 1, "the bundle's last launch")) { + return 1; + } + mark_release(ma); + mark_release(mb); + return 0; +} + +// Indirect count with a recording bound: launch d runs iff count > d. +int test_count_unroll() { + constexpr uint32_t MAX = 4; + Words cnt; + if (words_create(cnt, 64)) { + return 1; + } + const uint32_t counts[] = {2, MAX, MAX + 2, 0}; + for (uint32_t count : counts) { + if (words_write(cnt, 0, {count})) { + return 1; + } + Mark m[MAX]; + vx_launch_info_t l[MAX]; + vx_launch_indirect_t x[MAX]; + std::vector cmds; + for (uint32_t d = 0; d < MAX; ++d) { + if (mark_create(m[d]) || mark_clear(m[d])) { + return 1; + } + l[d] = mark_launch(m[d], 1, d + 1, 1, 1); + x[d] = indirect(); + x[d].pred_addr = cnt.addr; + x[d].pred_ref = d; + l[d].next = &x[d]; + cmds.push_back(launch_cmd(&l[d])); + } + CHECK_VX(submit(cmds)); + for (uint32_t d = 0; d < MAX; ++d) { + if (mark_expect(m[d], (count > d) ? 1 : 0, d + 1, 1, 1, "count unroll")) { + fprintf(stderr, " (count=%u, draw %u)\n", count, d); + return 1; + } + mark_release(m[d]); + } + } + vx_buffer_release(cnt.buf); + return 0; +} + +// x = ceil(((bytes - bias) / div) / 2^shift); a bias above the count skips. +int test_byte_count() { + Words rec; + if (words_create(rec, 64)) { + return 1; + } + struct Case { uint32_t bytes, bias, div, shift, gx; }; + const Case cases[] = { + {1000, 16, 7, 2, 35}, // 984 / 7 = 140, ceil(140 / 4) = 35 + {1000, 16, 7, 3, 18}, // ceil(140 / 8) = 18 + {13, 3, 1, 1, 5}, // divisor 1 bypasses: ceil(10 / 2) = 5 + {100, 0, 0, 0, 100}, + {20, 0, 7, 0, 2}, // 20 / 7 = 2, floor + {6, 0, 7, 0, 0}, // 6 / 7 = 0: skipped + {9, 10, 3, 0, 0}, // bias above the count: skipped + }; + for (const Case& c : cases) { + if (words_write(rec, 0, {c.bytes})) { + return 1; + } + Mark m; + if (mark_create(m) || mark_clear(m)) { + return 1; + } + vx_launch_info_t l = mark_launch(m, 1, 0, 0, 0); + vx_launch_indirect_t x = indirect(); + x.record_addr = rec.addr; + x.x_bias = c.bias; + x.x_div = c.div; + x.grid_shift[0] = uint8_t(c.shift); + l.next = &x; + CHECK_VX(submit({launch_cmd(&l)})); + if (mark_expect(m, c.gx ? 1 : 0, c.gx, 1, 1, "byte count")) { + fprintf(stderr, " (bytes=%u bias=%u div=%u shift=%u)\n", c.bytes, c.bias, c.div, c.shift); + return 1; + } + mark_release(m); + } + vx_buffer_release(rec.buf); + return 0; +} + +// Record words on both sides of a 64-byte line, and the highest word index. +int test_line_crossing() { + Words rec; + if (words_create(rec, 256)) { + return 1; + } + std::vector w(64, 0); + // record at +56: words 0,1 on line 0; word 2 on line 1; word 14 at +112. + w[56 / 4 + 0] = 4; + w[56 / 4 + 1] = 3; + w[56 / 4 + 2] = 2; + w[56 / 4 + 14] = 7; + if (words_write(rec, 0, w)) { + return 1; + } + Mark m, m14; + if (mark_create(m) || mark_create(m14) || mark_clear(m) || mark_clear(m14)) { + return 1; + } + vx_launch_info_t l = mark_launch(m, 3, 0, 0, 0); + vx_launch_indirect_t x = indirect(); + x.record_addr = rec.addr + 56; + l.next = &x; + vx_launch_info_t l14 = mark_launch(m14, 2, 0, 0, 0); + vx_launch_indirect_t x14 = indirect(); + x14.record_addr = rec.addr + 56; + x14.grid_word[0] = 14; + x14.grid_word[1] = 2; + l14.next = &x14; + CHECK_VX(submit({launch_cmd(&l), launch_cmd(&l14)})); + if (mark_expect(m, 1, 4, 3, 2, "line-crossing record") || + mark_expect(m14, 1, 7, 2, 1, "record word 14")) { + return 1; + } + mark_release(m); + mark_release(m14); + vx_buffer_release(rec.buf); + return 0; +} + +int test_enqueue_launch() { + Words rec; + if (words_create(rec, 64) || words_write(rec, 0, {6, 2, 1})) { + return 1; + } + Mark m; + if (mark_create(m) || mark_clear(m)) { + return 1; + } + vx_launch_info_t l = mark_launch(m, 2, 0, 0, 0); + vx_launch_indirect_t x = indirect(); + x.record_addr = rec.addr; + l.next = &x; + CHECK_VX(vx_enqueue_launch(g_q, &l, 0, nullptr, nullptr)); + CHECK_VX(vx_queue_finish(g_q, VX_TIMEOUT_INFINITE)); + if (mark_expect(m, 1, 6, 2, 1, "vx_enqueue_launch")) { + return 1; + } + mark_release(m); + vx_buffer_release(rec.buf); + return 0; +} + +int test_validation() { + Mark m; + if (mark_create(m)) { + return 1; + } + vx_launch_info_t l = mark_launch(m, 1, 1, 1, 1); + vx_launch_info_t l2 = mark_launch(m, 1, 1, 1, 1); + struct Bad { + const char* what; + void (*mutate)(vx_launch_indirect_t&, vx_launch_info_t&); + vx_result_t want; + }; + const Bad bad[] = { + {"skip past the end", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.skip_count = 2; }, + VX_ERR_INVALID_VALUE}, + {"grid word 16", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.record_addr = 64; x.grid_word[0] = 16; }, + VX_ERR_INVALID_VALUE}, + {"grid shift 16", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.record_addr = 64; x.grid_shift[0] = 16; }, + VX_ERR_INVALID_VALUE}, + {"misaligned record", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.record_addr = 66; }, + VX_ERR_INVALID_VALUE}, + {"misaligned predicate", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.pred_addr = 65; }, + VX_ERR_INVALID_VALUE}, + {"unknown flag", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.flags = 1u << 7; }, + VX_ERR_INVALID_VALUE}, + {"predicate-only with a kernel", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.flags = VX_INDIRECT_NO_LAUNCH; }, + VX_ERR_INVALID_VALUE}, + {"record grid without ndim", + [](vx_launch_indirect_t& x, vx_launch_info_t& li) { x.record_addr = 64; li.ndim = 0; }, + VX_ERR_INVALID_VALUE}, + {"record grid with a cluster", + [](vx_launch_indirect_t& x, vx_launch_info_t& li) { + x.record_addr = 64; li.grid_dim[0] = 2; li.cluster_dim[0] = 2; }, + VX_ERR_INVALID_VALUE}, + {"wrong struct type", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.type = vx_struct_type_e(99); }, + VX_ERR_INVALID_INFO}, + {"short struct", + [](vx_launch_indirect_t& x, vx_launch_info_t&) { x.struct_size = 8; }, + VX_ERR_INVALID_INFO}, + }; + for (const Bad& b : bad) { + vx_launch_info_t li = l; + vx_launch_indirect_t x = indirect(); + b.mutate(x, li); + li.next = &x; + vx_result_t r = vx_enqueue_commands(g_q, std::vector{ + launch_cmd(&li), launch_cmd(&l2)}.data(), 2, 0, nullptr, nullptr); + EXPECT(r == b.want, "%s: returned %s, expected %s", b.what, + vx_result_string(r), vx_result_string(b.want)); + } + // A block larger than a core, or more shared memory than a core has, is + // refused on every launch path, extended or not. + for (int k = 0; k < 2; ++k) { + vx_launch_info_t li = l; + if (k == 0) { + li.block_dim[0] = 1u << 20; + } else { + li.lmem_size = 1u << 30; + } + vx_launch_indirect_t x = indirect(); + li.next = &x; + const char* what = k ? "oversized lmem" : "oversized block"; + vx_result_t r = vx_enqueue_launch(g_q, &li, 0, nullptr, nullptr); + EXPECT(r == VX_ERR_INVALID_VALUE, "%s on extended vx_enqueue_launch: returned %s", + what, vx_result_string(r)); + li.next = nullptr; + vx_command_t c = launch_cmd(&li); + r = vx_enqueue_commands(g_q, &c, 1, 0, nullptr, nullptr); + EXPECT(r == VX_ERR_INVALID_VALUE, "%s on vx_enqueue_commands: returned %s", + what, vx_result_string(r)); + r = vx_enqueue_draw(g_q, &c, 1, 0, nullptr, nullptr); + EXPECT(r == VX_ERR_INVALID_VALUE, "%s on vx_enqueue_draw: returned %s", + what, vx_result_string(r)); + } + // A skip range on vx_enqueue_launch has nothing to skip. + vx_launch_info_t li = l; + vx_launch_indirect_t x = indirect(); + x.skip_count = 1; + li.next = &x; + vx_result_t r = vx_enqueue_launch(g_q, &li, 0, nullptr, nullptr); + EXPECT(r == VX_ERR_INVALID_VALUE, "skip on vx_enqueue_launch: returned %s", + vx_result_string(r)); + CHECK_VX(vx_queue_finish(g_q, VX_TIMEOUT_INFINITE)); + mark_release(m); + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + std::string vxbin; + for (int i = 1; i < argc; ++i) { + if (std::string(argv[i]) == "-k" && i + 1 < argc) { + vxbin = argv[++i]; + } + } + if (vxbin.empty()) { + if (const char* env = std::getenv("VX_TEST_INDIRECT_VXBIN")) { + vxbin = env; + } + } + if (vxbin.empty()) { + fprintf(stderr, "FAILED: no kernel image (set VX_TEST_INDIRECT_VXBIN or -k)\n"); + return 1; + } + + CHECK_VX(vx_device_open(0, &g_dev)); + CHECK_VX(vx_queue_create(g_dev, nullptr, &g_q)); + uint64_t nt = 0; + CHECK_VX(vx_device_query(g_dev, VX_CAPS_NUM_THREADS, &nt)); + g_nt = uint32_t(nt); + vx_module_h mod = nullptr; + CHECK_VX(vx_module_load_file(g_dev, vxbin.c_str(), &mod)); + CHECK_VX(vx_module_get_kernel(mod, "produce_k", &g_produce)); + CHECK_VX(vx_module_get_kernel(mod, "mark_k", &g_mark)); + + struct Test { const char* name; int (*fn)(); }; + const Test tests[] = { + {"caps", test_caps}, + {"device-written grid", test_device_grid}, + {"zero dimensions", test_zero_dims}, + {"predicate", test_predicate}, + {"skip range (ring)", [] { return test_skip_range(false); }}, + {"skip range (bundle)", [] { return test_skip_range(true); }}, + {"skip into a guard (ring)", [] { return test_skip_into_guard(false); }}, + {"skip into a guard (bundle)", [] { return test_skip_into_guard(true); }}, + {"predicate-only (ring)", [] { return test_no_launch(false); }}, + {"predicate-only (bundle)", [] { return test_no_launch(true); }}, + {"long draw bundle", test_long_bundle}, + {"count unroll", test_count_unroll}, + {"byte count", test_byte_count}, + {"line-crossing record", test_line_crossing}, + {"vx_enqueue_launch", test_enqueue_launch}, + {"validation", test_validation}, + }; + int failures = 0; + for (const Test& t : tests) { + printf("[ RUN ] %s\n", t.name); + fflush(stdout); + if (t.fn() != 0) { + printf("[ FAIL ] %s\n", t.name); + ++failures; + } else { + printf("[ OK ] %s\n", t.name); + } + fflush(stdout); + } + + vx_kernel_release(g_mark); + vx_kernel_release(g_produce); + vx_module_release(mod); + vx_queue_release(g_q); + vx_device_release(g_dev); + if (failures) { + printf("FAILED! (%d sections)\n", failures); + return 1; + } + printf("PASSED!\n"); + return 0; +} diff --git a/tests/unittest/cp_model/Makefile b/tests/unittest/cp_model/Makefile new file mode 100644 index 0000000000..9fe2b20eca --- /dev/null +++ b/tests/unittest/cp_model/Makefile @@ -0,0 +1,12 @@ +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +PROJECT := cp_model + +SRC_DIR := $(VORTEX_HOME)/tests/unittest/$(PROJECT) + +CXXFLAGS += -I$(VORTEX_HOME)/sim/common +CXXFLAGS += $(shell python3 $(ROOT_DIR)/ci/gen_config.py --config=$(VORTEX_HOME)/VX_config.toml --cflags='$(CONFIGS) -DVX_CFG_XLEN=$(XLEN)') +SRCS := $(SRC_DIR)/main.cpp $(VORTEX_HOME)/sim/common/cmd_processor.cpp + +include ../common.mk diff --git a/tests/unittest/cp_model/main.cpp b/tests/unittest/cp_model/main.cpp new file mode 100644 index 0000000000..f0bd629960 --- /dev/null +++ b/tests/unittest/cp_model/main.cpp @@ -0,0 +1,244 @@ +// Copyright © 2019-2023 +// Licensed under the Apache License, Version 2.0. + +// Unit test for the C++ command processor's launch descriptors: a QMD and an +// ILD replay their pairs and start the kernel; a descriptor off its 64-byte +// line is refused (no DCR write, no start) with Q_ERROR bit 0 set; a skipped +// indirect launch retires the commands of its range unexecuted. A backend +// whose busy holds from its start (SimX, rtlsim) may finish a kernel before +// the CP's next tick: the launch, ring or draw step, still retires. So may a +// device the CP sees only through busy polls that each let it run on (FireSim, +// foldsim, gem5): a kernel shorter than the gap between two polls retires, +// and a longer one only once busy has fallen. + +#include "cmd_processor.h" +#include +#include + +#include +#include +#include +#include +#include +#include + +#define EXPECT(cond, ...) do { \ + if (!(cond)) { \ + std::fprintf(stderr, "FAIL %s:%d: ", __FILE__, __LINE__); \ + std::fprintf(stderr, __VA_ARGS__); \ + std::fprintf(stderr, "\n"); \ + std::exit(1); \ + } \ +} while (0) + +namespace { + +constexpr uint64_t RING = 0x10000; +constexpr uint64_t CMPL = 0x20000; +constexpr uint64_t DESC = 0x30000; +constexpr uint64_t PRED = 0x40000; + +std::vector g_mem(1u << 20, 0); +std::vector> g_writes; +int g_starts = 0; +int g_busy = 0; +// The kernel each start runs is over before the CP ticks again: SimX's +// processor_.run() on its async thread, done while the host thread that ticks +// the CP was off the CPU. Busy is true from the start until then. +bool g_instant = false; + +// A device on its own clock, seen only through busy polls: each poll first +// lets it run `g_step` cycles -- FireSim's lockstep target stepped a batch +// before its busy is sampled, foldsim's running on while the host polls over +// PCIe or is off the CPU -- and a kernel runs `g_len` cycles from its start. +// Busy is high from the start (the target takes it on its first cycle; the +// foldsim shell counts a start not yet answered as busy) until the kernel +// ends, so a kernel shorter than a poll's step is never seen busy, and an +// empty one (g_len 0) never is. +bool g_polled = false; +uint64_t g_now = 0, g_end = 0, g_step = 16, g_len = 0; +// The backend's Hooks::busy_from_start declaration. +bool g_from_start = false; + +void wr32(uint64_t a, uint32_t v) { std::memcpy(&g_mem[a], &v, 4); } +void wr64(uint64_t a, uint64_t v) { std::memcpy(&g_mem[a], &v, 8); } + +vortex::CommandProcessor::Hooks hooks() { + vortex::CommandProcessor::Hooks h; + h.dram_read = [](uint64_t a, void* d, std::size_t n) { std::memcpy(d, &g_mem[a], n); }; + h.dram_write = [](uint64_t a, const void* s, std::size_t n) { std::memcpy(&g_mem[a], s, n); }; + h.vortex_dcr_write = [](uint32_t a, uint32_t v) { g_writes.push_back({a, v}); }; + h.vortex_dcr_read = [](uint32_t, uint32_t) -> uint32_t { return 0; }; + h.vortex_start = [] { + ++g_starts; + g_busy = g_instant ? 0 : 3; + g_end = g_now + g_len; + }; + h.vortex_busy = [] { + if (g_polled) { + g_now += g_step; + return g_now < g_end; + } + return g_busy > 0 && g_busy-- > 0; + }; + h.busy_from_start = g_instant || g_from_start; + return h; +} + +// One command per ring line, as the runtime submits them. +void put_cmd(int slot, uint8_t op, uint64_t a0) { + uint8_t* cl = &g_mem[RING + 64 * slot]; + std::memset(cl, 0, 64); + cl[0] = op; + std::memcpy(cl + 4, &a0, 8); +} + +void put_qmd(uint64_t at, uint32_t n) { + wr32(at, n); + wr32(at + 4, 0); + for (uint32_t i = 0; i < n; ++i) { + wr32(at + 8 + 8 * i, 0x010 + i); + wr32(at + 12 + 8 * i, 0x100 + i); + } +} + +void put_ild(uint64_t at, uint32_t ctl, uint16_t skip, uint32_t n) { + std::memset(&g_mem[at], 0, 64); + wr32(at + vortex::CP_ILD_OFF_CTL, ctl); + wr32(at + vortex::CP_ILD_OFF_SKIP, skip); + wr64(at + vortex::CP_ILD_OFF_PRED, PRED); + wr32(at + vortex::CP_ILD_OFF_COUNT, n); + for (uint32_t i = 0; i < n; ++i) { + wr32(at + 64 + 8 * i, 0x010 + i); + wr32(at + 68 + 8 * i, 0x200 + i); + } +} + +// Run `n` ring commands from the start of the ring on a fresh CP. +uint32_t run(int n) { + g_writes.clear(); + g_starts = 0; + vortex::CommandProcessor cp(hooks()); + cp.mmio_write(0x100, uint32_t(RING)); + cp.mmio_write(0x104, 0); + cp.mmio_write(0x110, uint32_t(CMPL)); + cp.mmio_write(0x114, 0); + cp.mmio_write(0x118, 16); + cp.mmio_write(0x11C, 1); + cp.mmio_write(0x000, 1); + cp.mmio_write(0x120, uint32_t(64 * n)); + cp.mmio_write(0x124, 0); + for (int i = 0; i < 10000 && cp.busy(); ++i) { + cp.tick(); + } + EXPECT(!cp.busy(), "the CP did not drain"); + EXPECT(cp.mmio_read(0x128) == uint32_t(n), "retired %u commands, expected %d", + cp.mmio_read(0x128), n); + return cp.mmio_read(0x12C); +} + +} // namespace + +int main() { + constexpr uint8_t OP_DCR_WRITE = 0x04, OP_LAUNCH_QMD = 0x0B, OP_DRAW = 0x0C, + OP_LAUNCH_IND = 0x0D; + + put_qmd(DESC, 5); + put_cmd(0, OP_LAUNCH_QMD, DESC); + EXPECT(run(1) == 0, "aligned QMD set Q_ERROR"); + EXPECT(g_writes.size() == 5 && g_starts == 1, "aligned QMD: %zu writes, %d starts", + g_writes.size(), g_starts); + + for (uint64_t off : {4ull, 8ull, 60ull}) { + put_cmd(0, OP_LAUNCH_QMD, DESC + off); + EXPECT(run(1) == vortex::CP_Q_ERROR_DESC_ALIGN, "QMD at +%llu not refused", + (unsigned long long)off); + EXPECT(g_writes.empty() && g_starts == 0, "refused QMD ran"); + + put_ild(DESC + 0x100, 0, 0, 3); + put_cmd(0, OP_LAUNCH_IND, DESC + 0x100 + off); + EXPECT(run(1) == vortex::CP_Q_ERROR_DESC_ALIGN, "ILD at +%llu not refused", + (unsigned long long)off); + EXPECT(g_writes.empty() && g_starts == 0, "refused ILD ran"); + } + + // Predicated off (0 > 0 fails), skip the next two commands; the third runs. + wr32(PRED, 0); + put_ild(DESC + 0x200, vortex::CP_ILD_HAS_PRED, 2, 3); + put_cmd(0, OP_LAUNCH_IND, DESC + 0x200); + put_cmd(1, OP_DCR_WRITE, 0); + put_cmd(2, OP_LAUNCH_QMD, DESC); + put_cmd(3, OP_LAUNCH_QMD, DESC); + EXPECT(run(4) == 0, "skip set Q_ERROR"); + EXPECT(g_writes.size() == 5 && g_starts == 1, "skip range: %zu writes, %d starts", + g_writes.size(), g_starts); + + // Predicate true: the ILD replays its pairs and starts. + wr32(PRED, 1); + put_cmd(0, OP_LAUNCH_IND, DESC + 0x200); + EXPECT(run(1) == 0, "aligned ILD set Q_ERROR"); + EXPECT(g_writes.size() == 3 && g_writes[0].second == 0x200 && g_starts == 1, + "aligned ILD: %zu writes, %d starts", g_writes.size(), g_starts); + + // A kernel over before the CP's next tick: a ring launch, then a draw + // whose two launch steps end so, around an inline DCR write. Each start + // happens once and the commands retire. + g_instant = true; + put_cmd(0, OP_LAUNCH_QMD, DESC); + put_cmd(1, OP_LAUNCH_IND, DESC + 0x200); + EXPECT(run(2) == 0, "instant launches set Q_ERROR"); + EXPECT(g_starts == 2, "instant launches: %d starts", g_starts); + + constexpr uint64_t DRAW = 0x50000; + constexpr uint32_t STEP = 28; // DRAW_STEP_BYTES + auto put_step = [&](uint32_t i, uint8_t op, uint64_t a0, uint64_t a1) { + uint8_t* s = &g_mem[DRAW + 4 + STEP * i]; + std::memset(s, 0, STEP); + s[0] = op; + std::memcpy(s + 4, &a0, 8); + std::memcpy(s + 12, &a1, 8); + }; + wr32(DRAW, 3); + put_step(0, OP_LAUNCH_QMD, DESC, 0); + put_step(1, OP_DCR_WRITE, 0x7, 0x77); + put_step(2, OP_LAUNCH_IND, DESC + 0x200, 0); + put_cmd(0, OP_DRAW, DRAW); + EXPECT(run(1) == 0, "instant draw set Q_ERROR"); + EXPECT(g_starts == 2 && g_writes.size() == 5 + 1 + 3, + "instant draw: %d starts, %zu writes", g_starts, g_writes.size()); + g_instant = false; + + // A polled device: kernels that start and end between two polls (empty, + // and shorter than the step), one that ends exactly at the first poll, + // and one that spans many. Each launch starts once, and none retires + // before its kernel has ended. + g_polled = true; + g_from_start = true; + for (uint64_t len : {0ull, 5ull, 15ull, 16ull, 1000ull}) { + g_len = len; + g_now = 0; + put_cmd(0, OP_LAUNCH_QMD, DESC); + put_cmd(1, OP_LAUNCH_IND, DESC + 0x200); + EXPECT(run(2) == 0, "polled launches (%llu cycles) set Q_ERROR", + (unsigned long long)len); + EXPECT(g_starts == 2, "polled launches (%llu cycles): %d starts", + (unsigned long long)len, g_starts); + EXPECT(g_now >= g_end, "polled launch (%llu cycles) retired at %llu, " + "before its kernel ended at %llu", (unsigned long long)len, + (unsigned long long)g_now, (unsigned long long)g_end); + + put_cmd(0, OP_DRAW, DRAW); + EXPECT(run(1) == 0, "polled draw (%llu cycles) set Q_ERROR", + (unsigned long long)len); + EXPECT(g_starts == 2 && g_writes.size() == 5 + 1 + 3, + "polled draw (%llu cycles): %d starts, %zu writes", + (unsigned long long)len, g_starts, g_writes.size()); + EXPECT(g_now >= g_end, "polled draw step (%llu cycles) retired early", + (unsigned long long)len); + } + g_polled = false; + g_from_start = false; + + std::printf("PASSED\n"); + return 0; +} diff --git a/tests/vulkan/dispatchindirect/Makefile b/tests/vulkan/dispatchindirect/Makefile new file mode 100644 index 0000000000..8295032b74 --- /dev/null +++ b/tests/vulkan/dispatchindirect/Makefile @@ -0,0 +1,30 @@ +# Copyright © 2026 Vortex GPGPU +# SPDX-License-Identifier: MIT +# +# vkCmdDispatchIndirect with workgroup counts written by a shader in the same +# command buffer, with zero counts, an offset record, a large grid and +# host-written counts, and dispatches under conditional rendering. +# +# make -- build the host binary + SPIR-V +# make run-simx -- run each case and check every workgroup and the grid +# +# STRICT is 1: the device must run every dispatch itself. Set before common.mk. + +ROOT_DIR := $(realpath ../../..) +include $(ROOT_DIR)/config.mk + +PROJECT := dispatchindirect + +SRC_DIR := $(VORTEX_HOME)/tests/vulkan/$(PROJECT) + +STRICT := 1 +# Every count and predicate is read by the command processor, and every +# dispatch runs on the device. +EXPECT_NO_HOSTREAD := 1 +EXPECT_ATTRIB := launches=25/25_draws=0/0 + +SRCS := $(SRC_DIR)/main.c + +SHADERS := $(SRC_DIR)/args.comp $(SRC_DIR)/mark.comp + +include ../common.mk diff --git a/tests/vulkan/dispatchindirect/args.comp b/tests/vulkan/dispatchindirect/args.comp new file mode 100644 index 0000000000..bc6abde123 --- /dev/null +++ b/tests/vulkan/dispatchindirect/args.comp @@ -0,0 +1,29 @@ +/* Copyright © 2026 Vortex GPGPU + * SPDX-License-Identifier: MIT + * + * Writes a dispatch's workgroup counts and a predicate word on the device, so + * the dispatch that consumes them can only learn them from memory. + */ +#version 450 + +layout(local_size_x = 1) in; + +layout(std430, binding = 0) buffer Args { + uint w[]; +}; + +layout(push_constant) uniform PC { + uint off; + uint x; + uint y; + uint z; + uint pred; +} pc; + +void main() +{ + w[pc.off + 0u] = pc.x; + w[pc.off + 1u] = pc.y; + w[pc.off + 2u] = pc.z; + w[pc.off + 3u] = pc.pred; +} diff --git a/tests/vulkan/dispatchindirect/main.c b/tests/vulkan/dispatchindirect/main.c new file mode 100644 index 0000000000..41ed71ac89 --- /dev/null +++ b/tests/vulkan/dispatchindirect/main.c @@ -0,0 +1,420 @@ +/* + * Copyright © 2026 Vortex GPGPU + * SPDX-License-Identifier: MIT + * + * vkCmdDispatchIndirect, and dispatches under VK_EXT_conditional_rendering. + * + * In the GPU cases a shader writes the workgroup counts (and the predicate + * word) into the buffer the dispatch then reads, inside one command buffer, so + * the counts exist only in device memory when the dispatch is recorded. The + * marking shader counts every workgroup it runs as and records the grid, so a + * dispatch that ran the wrong grid, ran a workgroup twice, skipped one, or ran + * at all when it should not have, each fails differently. + * + * gpu 3x2x2 / offset counts written by a shader, at offset 0 / 32 + * gpu zero x / y / z a zero count dispatches nothing + * gpu large 2048 workgroups + * host 5x1x1 counts written through a mapping + * cond gpu 0 / 1 [inverted] a direct dispatch under a predicate the + * shader wrote, normal and inverted + * cond indirect gpu 0 / 1 an indirect dispatch under a predicate + * + * Run against lavapipe with GALLIUM_DRIVER=vortexpipe. + */ + +#include +#include +#include +#include +#include + +#define HITS 4096u +#define META 16u +#define ARGS 64u + +#define CHECK(x) do { \ + VkResult _r = (x); \ + if (_r != VK_SUCCESS) { \ + fprintf(stderr, "FAILED: %s -> VkResult %d\n", #x, (int)_r); \ + return 1; \ + } \ +} while (0) + +enum cond_mode { COND_NONE, COND_NORMAL, COND_INVERTED }; + +struct dcase { + const char *name; + bool gpu_args; /* counts written by args.comp, else by the host */ + bool indirect; /* vkCmdDispatchIndirect, else vkCmdDispatch */ + uint32_t off; /* word offset of the record */ + uint32_t x, y, z; + enum cond_mode cond; + uint32_t pred; +}; + +static const struct dcase cases[] = { + { "gpu 3x2x2", true, true, 0u, 3u, 2u, 2u, COND_NONE, 0u }, + { "gpu offset 4x1x3", true, true, 8u, 4u, 1u, 3u, COND_NONE, 0u }, + { "gpu zero x", true, true, 0u, 0u, 4u, 4u, COND_NONE, 0u }, + { "gpu zero y", true, true, 0u, 4u, 0u, 4u, COND_NONE, 0u }, + { "gpu zero z", true, true, 0u, 4u, 4u, 0u, COND_NONE, 0u }, + { "gpu large 1024x2x1", true, true, 0u, 1024u, 2u, 1u, COND_NONE, 0u }, + { "host 5x1x1", false, true, 0u, 5u, 1u, 1u, COND_NONE, 0u }, + { "cond gpu 0", true, false, 0u, 2u, 2u, 1u, COND_NORMAL, 0u }, + { "cond gpu 1", true, false, 0u, 2u, 2u, 1u, COND_NORMAL, 1u }, + { "cond gpu 0 inverted", true, false, 0u, 2u, 2u, 1u, COND_INVERTED, 0u }, + { "cond gpu 7 inverted", true, false, 0u, 2u, 2u, 1u, COND_INVERTED, 7u }, + { "cond indirect gpu 0", true, true, 0u, 3u, 1u, 2u, COND_NORMAL, 0u }, + { "cond indirect gpu 1", true, true, 0u, 3u, 1u, 2u, COND_NORMAL, 1u }, +}; +#define NCASES (sizeof cases / sizeof cases[0]) + +struct pc { + uint32_t off, x, y, z, pred; +}; + +static uint32_t * +read_spirv(const char *path, size_t *out_size) +{ + FILE *f = fopen(path, "rb"); + if (!f) { fprintf(stderr, "FAILED: cannot open %s\n", path); return NULL; } + fseek(f, 0, SEEK_END); + long sz = ftell(f); + fseek(f, 0, SEEK_SET); + uint32_t *buf = malloc((size_t)sz); + if (buf && fread(buf, 1, (size_t)sz, f) != (size_t)sz) { free(buf); buf = NULL; } + fclose(f); + if (buf) { *out_size = (size_t)sz; } + return buf; +} + +struct gpu { + VkDevice dev; + VkPhysicalDevice pd; + VkQueue queue; + uint32_t qf; + PFN_vkCmdBeginConditionalRenderingEXT begin_cond; + PFN_vkCmdEndConditionalRenderingEXT end_cond; +}; + +static int +make_buffer(struct gpu *g, VkDeviceSize bytes, VkBufferUsageFlags usage, + VkBuffer *buf, VkDeviceMemory *mem, uint32_t **map) +{ + VkBufferCreateInfo bci = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .size = bytes, .usage = usage, .sharingMode = VK_SHARING_MODE_EXCLUSIVE, + }; + CHECK(vkCreateBuffer(g->dev, &bci, NULL, buf)); + VkMemoryRequirements mr; + vkGetBufferMemoryRequirements(g->dev, *buf, &mr); + VkPhysicalDeviceMemoryProperties mp; + vkGetPhysicalDeviceMemoryProperties(g->pd, &mp); + const VkMemoryPropertyFlags want = + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT; + uint32_t mt = UINT32_MAX; + for (uint32_t i = 0; i < mp.memoryTypeCount; i++) { + if ((mr.memoryTypeBits & (1u << i)) && + (mp.memoryTypes[i].propertyFlags & want) == want) { mt = i; break; } + } + if (mt == UINT32_MAX) { fprintf(stderr, "FAILED: no host-visible memory\n"); return 1; } + VkMemoryAllocateInfo mai = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = mr.size, .memoryTypeIndex = mt, + }; + CHECK(vkAllocateMemory(g->dev, &mai, NULL, mem)); + CHECK(vkBindBufferMemory(g->dev, *buf, *mem, 0)); + CHECK(vkMapMemory(g->dev, *mem, 0, bytes, 0, (void **)map)); + return 0; +} + +static int +make_pipeline(struct gpu *g, const char *path, VkPipelineLayout pl, VkPipeline *pipe) +{ + size_t sz = 0; + uint32_t *spv = read_spirv(path, &sz); + if (!spv) { return 1; } + VkShaderModuleCreateInfo smci = { + .sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, + .codeSize = sz, .pCode = spv, + }; + VkShaderModule sm; + CHECK(vkCreateShaderModule(g->dev, &smci, NULL, &sm)); + free(spv); + VkComputePipelineCreateInfo cpci = { + .sType = VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, + .stage = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, + .stage = VK_SHADER_STAGE_COMPUTE_BIT, .module = sm, .pName = "main", + }, + .layout = pl, + }; + CHECK(vkCreateComputePipelines(g->dev, VK_NULL_HANDLE, 1, &cpci, NULL, pipe)); + vkDestroyShaderModule(g->dev, sm, NULL); + return 0; +} + +int +main(int argc, char **argv) +{ + const char *args_path = (argc > 1) ? argv[1] : "args.comp.spv"; + const char *mark_path = (argc > 2) ? argv[2] : "mark.comp.spv"; + + VkApplicationInfo app = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .pApplicationName = "vortexpipe-dispatchindirect", + .apiVersion = VK_API_VERSION_1_1, + }; + VkInstanceCreateInfo ici = { + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &app, + }; + VkInstance inst; + CHECK(vkCreateInstance(&ici, NULL, &inst)); + + struct gpu g = { 0 }; + uint32_t npd = 1; + CHECK(vkEnumeratePhysicalDevices(inst, &npd, &g.pd)); + if (npd == 0) { fprintf(stderr, "FAILED: no physical device\n"); return 1; } + VkPhysicalDeviceProperties props; + vkGetPhysicalDeviceProperties(g.pd, &props); + printf("device: %s\n", props.deviceName); + + uint32_t nqf = 0; + vkGetPhysicalDeviceQueueFamilyProperties(g.pd, &nqf, NULL); + VkQueueFamilyProperties *qfp = calloc(nqf, sizeof(*qfp)); + vkGetPhysicalDeviceQueueFamilyProperties(g.pd, &nqf, qfp); + g.qf = UINT32_MAX; + for (uint32_t i = 0; i < nqf; i++) { + if (qfp[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { g.qf = i; break; } + } + free(qfp); + if (g.qf == UINT32_MAX) { fprintf(stderr, "FAILED: no compute queue\n"); return 1; } + + float prio = 1.0f; + VkDeviceQueueCreateInfo qci = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueFamilyIndex = g.qf, .queueCount = 1, .pQueuePriorities = &prio, + }; + VkPhysicalDeviceConditionalRenderingFeaturesEXT crf = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_CONDITIONAL_RENDERING_FEATURES_EXT, + .conditionalRendering = VK_TRUE, + }; + const char *exts[] = { VK_EXT_CONDITIONAL_RENDERING_EXTENSION_NAME }; + VkDeviceCreateInfo dci = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = &crf, + .queueCreateInfoCount = 1, .pQueueCreateInfos = &qci, + .enabledExtensionCount = 1, .ppEnabledExtensionNames = exts, + }; + CHECK(vkCreateDevice(g.pd, &dci, NULL, &g.dev)); + vkGetDeviceQueue(g.dev, g.qf, 0, &g.queue); + g.begin_cond = (PFN_vkCmdBeginConditionalRenderingEXT) + vkGetDeviceProcAddr(g.dev, "vkCmdBeginConditionalRenderingEXT"); + g.end_cond = (PFN_vkCmdEndConditionalRenderingEXT) + vkGetDeviceProcAddr(g.dev, "vkCmdEndConditionalRenderingEXT"); + if (!g.begin_cond || !g.end_cond) { + fprintf(stderr, "FAILED: no conditional rendering entry points\n"); + return 1; + } + + VkBuffer argb, hitb, metab; + VkDeviceMemory argm, hitm, metam; + uint32_t *argp, *hitp, *metap; + if (make_buffer(&g, ARGS * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | + VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT, + &argb, &argm, &argp) || + make_buffer(&g, HITS * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &hitb, &hitm, &hitp) || + make_buffer(&g, META * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &metab, &metam, &metap)) { + return 1; + } + + VkDescriptorSetLayoutBinding b[3]; + for (uint32_t i = 0; i < 3; i++) { + b[i] = (VkDescriptorSetLayoutBinding) { + .binding = i, .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, + .descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, + }; + } + VkDescriptorSetLayoutCreateInfo dslci = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, + .bindingCount = 3, .pBindings = b, + }; + VkDescriptorSetLayout dsl; + CHECK(vkCreateDescriptorSetLayout(g.dev, &dslci, NULL, &dsl)); + VkPushConstantRange pcr = { + .stageFlags = VK_SHADER_STAGE_COMPUTE_BIT, .offset = 0, .size = sizeof(struct pc), + }; + VkPipelineLayoutCreateInfo plci = { + .sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, + .setLayoutCount = 1, .pSetLayouts = &dsl, + .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr, + }; + VkPipelineLayout pl; + CHECK(vkCreatePipelineLayout(g.dev, &plci, NULL, &pl)); + VkPipeline args_pipe, mark_pipe; + if (make_pipeline(&g, args_path, pl, &args_pipe) || + make_pipeline(&g, mark_path, pl, &mark_pipe)) { + return 1; + } + + VkDescriptorPoolSize dps = { + .type = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, .descriptorCount = 3, + }; + VkDescriptorPoolCreateInfo dpci = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, + .maxSets = 1, .poolSizeCount = 1, .pPoolSizes = &dps, + }; + VkDescriptorPool dp; + CHECK(vkCreateDescriptorPool(g.dev, &dpci, NULL, &dp)); + VkDescriptorSetAllocateInfo dsai = { + .sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, + .descriptorPool = dp, .descriptorSetCount = 1, .pSetLayouts = &dsl, + }; + VkDescriptorSet ds; + CHECK(vkAllocateDescriptorSets(g.dev, &dsai, &ds)); + VkDescriptorBufferInfo dbi[3] = { + { .buffer = argb, .offset = 0, .range = ARGS * 4 }, + { .buffer = hitb, .offset = 0, .range = HITS * 4 }, + { .buffer = metab, .offset = 0, .range = META * 4 }, + }; + VkWriteDescriptorSet wds[3]; + for (uint32_t i = 0; i < 3; i++) { + wds[i] = (VkWriteDescriptorSet) { + .sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, + .dstSet = ds, .dstBinding = i, .descriptorCount = 1, + .descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, .pBufferInfo = &dbi[i], + }; + } + vkUpdateDescriptorSets(g.dev, 3, wds, 0, NULL); + + VkCommandPoolCreateInfo cmpci = { + .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + .flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT, + .queueFamilyIndex = g.qf, + }; + VkCommandPool cp; + CHECK(vkCreateCommandPool(g.dev, &cmpci, NULL, &cp)); + VkCommandBufferAllocateInfo cbai = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = cp, .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 1, + }; + VkCommandBuffer cb; + CHECK(vkAllocateCommandBuffers(g.dev, &cbai, &cb)); + + unsigned failed = 0; + for (unsigned c = 0; c < NCASES; c++) { + const struct dcase *k = &cases[c]; + /* The record starts out holding counts that would pass a dispatch that + * ignored the device-written ones. */ + for (uint32_t i = 0; i < ARGS; i++) { argp[i] = 1u; } + memset(hitp, 0, HITS * 4); + memset(metap, 0, META * 4); + if (!k->gpu_args) { + argp[k->off + 0] = k->x; + argp[k->off + 1] = k->y; + argp[k->off + 2] = k->z; + argp[k->off + 3] = k->pred; + } + + VkCommandBufferBeginInfo cbbi = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, + }; + CHECK(vkBeginCommandBuffer(cb, &cbbi)); + vkCmdBindDescriptorSets(cb, VK_PIPELINE_BIND_POINT_COMPUTE, pl, 0, 1, &ds, 0, NULL); + if (k->gpu_args) { + const struct pc pc = { k->off, k->x, k->y, k->z, k->pred }; + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, args_pipe); + vkCmdPushConstants(cb, pl, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof pc, &pc); + vkCmdDispatch(cb, 1, 1, 1); + VkMemoryBarrier mb = { + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER, + .srcAccessMask = VK_ACCESS_SHADER_WRITE_BIT, + .dstAccessMask = VK_ACCESS_INDIRECT_COMMAND_READ_BIT | + VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT, + }; + vkCmdPipelineBarrier(cb, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, + VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | + VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, + 0, 1, &mb, 0, NULL, 0, NULL); + } + vkCmdBindPipeline(cb, VK_PIPELINE_BIND_POINT_COMPUTE, mark_pipe); + if (k->cond != COND_NONE) { + VkConditionalRenderingBeginInfoEXT crbi = { + .sType = VK_STRUCTURE_TYPE_CONDITIONAL_RENDERING_BEGIN_INFO_EXT, + .buffer = argb, .offset = (k->off + 3u) * 4u, + .flags = k->cond == COND_INVERTED ? VK_CONDITIONAL_RENDERING_INVERTED_BIT_EXT : 0, + }; + g.begin_cond(cb, &crbi); + } + if (k->indirect) { + vkCmdDispatchIndirect(cb, argb, k->off * 4u); + } else { + vkCmdDispatch(cb, k->x, k->y, k->z); + } + if (k->cond != COND_NONE) { + g.end_cond(cb); + } + CHECK(vkEndCommandBuffer(cb)); + VkSubmitInfo si = { + .sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, + .commandBufferCount = 1, .pCommandBuffers = &cb, + }; + CHECK(vkQueueSubmit(g.queue, 1, &si, VK_NULL_HANDLE)); + CHECK(vkQueueWaitIdle(g.queue)); + CHECK(vkResetCommandBuffer(cb, 0)); + + bool runs = k->x && k->y && k->z; + if (k->cond != COND_NONE) { + runs = runs && ((k->pred != 0) != (k->cond == COND_INVERTED)); + } + const uint32_t blocks = runs ? k->x * k->y * k->z : 0; + unsigned bad = 0; + for (uint32_t i = 0; i < HITS; i++) { + const uint32_t want = i < blocks ? 1u : 0u; + if (hitp[i] != want) { + if (bad < 4) { + fprintf(stderr, " %s: workgroup %u ran %u times, want %u\n", + k->name, i, hitp[i], want); + } + bad++; + } + } + if (metap[3] != (runs ? 1u : 0u) || + (runs && (metap[0] != k->x || metap[1] != k->y || metap[2] != k->z))) { + fprintf(stderr, " %s: grid %ux%ux%u over %u launches, want %ux%ux%u over %u\n", + k->name, metap[0], metap[1], metap[2], metap[3], + k->x, k->y, k->z, runs ? 1u : 0u); + bad++; + } + printf("%-24s %s\n", k->name, bad ? "FAIL" : "ok"); + if (bad) { + failed++; + } + } + + vkDestroyCommandPool(g.dev, cp, NULL); + vkDestroyDescriptorPool(g.dev, dp, NULL); + vkDestroyPipeline(g.dev, args_pipe, NULL); + vkDestroyPipeline(g.dev, mark_pipe, NULL); + vkDestroyPipelineLayout(g.dev, pl, NULL); + vkDestroyDescriptorSetLayout(g.dev, dsl, NULL); + vkDestroyBuffer(g.dev, argb, NULL); + vkDestroyBuffer(g.dev, hitb, NULL); + vkDestroyBuffer(g.dev, metab, NULL); + vkFreeMemory(g.dev, argm, NULL); + vkFreeMemory(g.dev, hitm, NULL); + vkFreeMemory(g.dev, metam, NULL); + vkDestroyDevice(g.dev, NULL); + vkDestroyInstance(inst, NULL); + + if (failed) { + printf("FAILED (dispatchindirect: %u of %u cases)\n", failed, (unsigned)NCASES); + return 1; + } + printf("PASSED (dispatchindirect: %u cases)\n", (unsigned)NCASES); + return 0; +} diff --git a/tests/vulkan/dispatchindirect/mark.comp b/tests/vulkan/dispatchindirect/mark.comp new file mode 100644 index 0000000000..8d46e53505 --- /dev/null +++ b/tests/vulkan/dispatchindirect/mark.comp @@ -0,0 +1,34 @@ +/* Copyright © 2026 Vortex GPGPU + * SPDX-License-Identifier: MIT + * + * Counts each workgroup it runs as and records the grid it was dispatched + * with, so a missing, extra or misplaced workgroup and a wrong grid are each + * visible. + */ +#version 450 + +layout(local_size_x = 4) in; + +layout(std430, binding = 1) buffer Hits { + uint hits[]; +}; + +layout(std430, binding = 2) buffer Meta { + uint meta[]; +}; + +void main() +{ + if (gl_LocalInvocationIndex != 0u) { + return; + } + uint wid = (gl_WorkGroupID.z * gl_NumWorkGroups.y + gl_WorkGroupID.y) + * gl_NumWorkGroups.x + gl_WorkGroupID.x; + hits[wid] += 1u; + if (wid == 0u) { + meta[0] = gl_NumWorkGroups.x; + meta[1] = gl_NumWorkGroups.y; + meta[2] = gl_NumWorkGroups.z; + meta[3] += 1u; + } +}