Skip to content

28 kuda

misazhu edited this page Dec 3, 2026 · 2 revisions

28 KUDA: a CUDA-Compatible Compute Layer

Language: English | 中文

Goal: understand projects/kuda — a CUDA driver API compatibility layer for EwokOS: what its API surface promises (and deliberately does not), how the machine-independent core is split from per-machine BSP backends, how the built-in CPU simulator keeps every app runnable without a GPU, and how the shipping Adreno 690 backend turns GLSL compute shaders into a CUDA-shaped operator set that runs LLM inference on real silicon.

Read 27 GPU Support first for the daemon/IPC/compiler shape this chapter builds on; 09 IPC and 05 Memory & MMU explain the transport and the zero-copy buffers. Terminology is collected in the glossary.

KUDA lets CUDA driver-API code compile and run on EwokOS unchanged at the source level: same CUresult/CUcontext/CUmodule/CUstream types, same error codes, same _v2 naming convention — only the prefix changes from cu*/CU_* to ku*/KU_* (a mechanical rename). There is no PTX JIT and no NVIDIA binary compatibility promise beyond what each BSP accepts; the contract is source compatibility for a well-defined subset, plus honest KUDA_ERROR_NOT_SUPPORTED everywhere else.

Every code reference below points at a real file:

Piece File
Public API header (M0 subset) projects/kuda/libs/kuda/include/kuda.h
Core state & backend contract projects/kuda/libs/kuda/src/internal.h
Init / device / context / handle liveness projects/kuda/libs/kuda/src/api.c
Module loading & function query projects/kuda/libs/kuda/src/module.c
Launch validation & parameter packing projects/kuda/libs/kuda/src/launch.c
Memory / streams / occupancy wrappers mem.c, stream.c, occupancy.c
Built-in CPU simulation backend projects/kuda/libs/kuda/src/backend_sim.c
Sim module descriptor format projects/kuda/libs/kuda/include/kuda_sim.h
Weak BSP fallbacks projects/kuda/libs/kuda/src/bsp_default.c
Adreno 690 KUDA BSP hardwares/qcom/8gen3/system/libs/kuda/src/backend.c, image.c
ops.q8b image format hardwares/qcom/8gen3/system/libs/kuda/include/q8b_kuda_image.h
Host-side operator image generator hardwares/qcom/8gen3/system/libs/kuda/tools/generate.c + shaders/*.comp
Board test / benchmark app hardwares/qcom/8gen3/system/libs/kuda/test/vec_add.c
GA10B cubin/QMD reuse hardwares/nvidia/orin.nano/system/libs/ga10b/ga10b_compute.c
Board test flow & measured results q8b-kuda-test-flow.md, q8b-kuda-gemv-optimization.md, q8b-rebuild-llm-report-20261201.md

28.1 The API surface: what M0 promises

kuda.h declares KUDA_VERSION 12000 and mirrors NVIDIA's driver API for the M0 subset:

Area Functions
Init / device kuInit, kuDriverGetVersion, kuDeviceGetCount/Get/GetName/TotalMem_v2/GetAttribute/ComputeCapability
Context kuCtxCreate_v2, kuCtxDestroy_v2, kuCtxSetCurrent/GetCurrent/Synchronize/GetDevice
Modules kuModuleLoad (file), kuModuleLoadData (image), kuModuleUnload, kuModuleGetFunction
Function attributes kuFuncGetAttribute, kuFuncSetAttribute (dynamic shared-memory opt-in)
Memory kuMemAlloc_v2/Free_v2/GetInfo_v2, kuMemcpyHtoD/DtoH/DtoD_v2, kuMemsetD8/D32_v2
Launch kuLaunchKernel (both kernelParams and extra forms)
Streams / events create/destroy/synchronize/query, kuStreamWaitEvent, kuEventRecord/ElapsedTime
Occupancy kuOccupancyMaxActiveBlocksPerMultiprocessor[WithFlags], kuOccupancyMaxPotentialBlockSize[WithFlags]
Errors kuGetErrorString, kuGetErrorName

Plain-name aliases (#define kuMemAlloc kuMemAlloc_v2, ...) match NVIDIA's header, so existing driver-API sources need only the prefix rename.

Deliberately not implemented (documented in the header): PTX JIT (compile offline with nvcc -cubin), arrays/textures, graphics interop, unified/managed memory, IPC handles, CUDA graphs.

Documented deviations from NVIDIA: the current context is process-wide, not per-thread; the library is not thread-safe; destroying a context releases its modules, streams, events and device memory (CUDA leaves that to the caller).

28.2 The core/BSP split and the link contract

 libkuda.a  (projects/kuda — machine independent)
   api.c / module.c / mem.c / launch.c / stream.c / occupancy.c
   owns: handle validation, object lifetime, parameter packing
   includes: backend_sim.c (CPU fallback, always present)
        │  struct kuda_backend vtable (internal.h)
        ▼
 libkudabsp.a  (hardwares/<vendor>/<hw>/system/libs/kuda — per machine)
   binary image parsing, device model, hardware submission, operator set
   today: hardwares/qcom/8gen3 (Adreno 690)

The core talks to a backend only through struct kuda_backend — a vtable covering probe, device queries, context create/destroy/sync, module load/unload, alloc/free/memcpy/memset, launch, and the full stream/event set. Everything that touches a device or an image format lives in the BSP.

Four symbols cross the boundary: kuda_backend_bsp (the hardware backend selector; NULL routes kuInit to the simulator), kuda_sim_module_ops, kuda_sim_device_attr and kuda_sim_arch_ok (the BSP supplies the sim device model so the simulator reports the same limits as the machine's GPU path). bsp_default.c provides weak fallbacks so a core-only link stays alive. To pull the strong definitions out of the BSP archive, the machine Makefile links it before libkuda.a inside --start-group and forces the references — this is the real link line from hardwares/qcom/8gen3/system/libs/kuda/Makefile:

$(LD) -Ttext=100 $< -u kuda_backend_bsp -u kuda_sim_module_ops \
        --start-group $(BSP_LIB) $(KUDA_LIB) --end-group \
        -L$(BUILD_DIR)/lib -lg2dclient -lopenlibm $(EWOK_LIBC) -o $@

Ownership is intrusive-list based: a context owns its modules, streams and events; a module owns the function handles it handed out. Destroying the owner destroys what it owns, so no handle outlives its object.

28.3 Core walkthrough

api.c — init and liveness. kuInit asks kuda_backend_bsp() for a backend and calls its probe(); if the BSP reports zero devices (driver node absent, gate not set), the core falls back to kuda_backend_sim(). Handle validation never dereferences the handle: kuda_ctx_live / kuda_mod_live / kuda_func_live / kuda_stream_live / kuda_event_live walk the live lists, so a stale handle to a destroyed object is rejected without touching freed memory. kuCtxCreate_v2 makes the new context current; kuCtxDestroy_v2 cascades events → streams → modules, then calls the backend's ctx_destroy (which releases every device allocation the context still owns).

module.c — one loader, two image kinds. kuModuleLoadData peeks the first four bytes: magic KUDA_SIM_MODULE_MAGIC ("ESIM") means a sim descriptor table (C kernel twins); anything else goes to the BSP's module_load_image, which validates the format, takes ownership of a copy (mod->image_copy), and fills the format-neutral kernel table (struct kuda_kernel_info: name, per-parameter offset/size window, param_base — 0x160 for cubin cbank0 — static shared bytes, frame size, register count, cbank0 size). kuModuleGetFunction returns one handle per kernel (repeated lookups return the same object). kuFuncGetAttribute answers from that table (PTX_VERSION is 0 — binary-only; BINARY_VERSION is the module's arch tag); kuFuncSetAttribute implements the dynamic-shared-memory opt-in, checked against the device's MAX_SHARED_MEMORY_PER_BLOCK_OPTIN minus the kernel's static shared size.

launch.c — validate, pack, dispatch. kuLaunchKernel first checks grid/block dimensions and total threads against the device attributes; then pack_params builds a zero-padded parameter window from the kernelParams array using each parameter's BSP-declared offset/size (a 64×uint64_t stack buffer covers the common case; larger windows go to the heap). The extra form (KU_LAUNCH_PARAM_BUFFER_POINTER / _SIZE) is accepted too. Static + dynamic shared memory above the opt-in limit returns KUDA_ERROR_LAUNCH_OUT_OF_RESOURCES before anything is submitted. The packed window plus grid/block/smem/stream go to the backend as struct kuda_launch_cfg.

mem.c / stream.c / occupancy.c are thin, validating wrappers over the vtable; occupancy math uses the device attributes and the kernel's register/shared footprint.

28.4 The CPU simulation backend

backend_sim.c is the always-present fallback — the same "CPU is the reference" contract as the rest of the graphics stack:

  • Device memory is host memory: each allocation is a malloc with a 16-byte tracking header; sim_range validates every memcpy/memset/launch argument against the live allocation list (double frees are rejected). The simulated device reports 8 GB total.
  • Kernels are C twins of the GPU operators, registered through kuda_sim.h descriptor tables. The harness loops grid × block and calls the twin once per thread with the same packed parameter window the GPU path would build — so parameter packing is exercised identically. Twins must be per-thread independent (no __syncthreads/__shared__); kernels that need block-wide cooperation set KUDA_SIM_KERNEL_WHOLE_LAUNCH and compute the whole launch in one call.
  • Real cubins can bind to twins: the BSP's image parser fills the kernel table even on the sim path, and sim_abi_matches refuses the launch unless the cubin's parameter layout matches the twin's param_size[] table — a cheap ABI cross-check between the GPU and CPU versions of an operator.
  • Streams are no-ops, events are real: everything executes synchronously, but events timestamp with CLOCK_MONOTONIC, so kuEventElapsedTime still measures something meaningful.
  • The sim device model comes from the BSP (kuda_sim_device_attr), so a sim run on the 8gen3 reports Adreno-shaped limits, not generic ones.

The optional operator tree (projects/kuda/libs/kuda/ops, single-source .cu kernels compiled by nvcc for the GPU and as C twins with -DKUDA_SIM for the simulator) is exactly that — optional: when absent, the weak kuda_sim_module_ops fallback applies and the hardware image path still works.

28.5 The Adreno 690 BSP: CUDA-shaped operators on GLSL compute

The shipping hardware backend lives in hardwares/qcom/8gen3/system/libs/kuda and rides the same g2dd / g2dclient compute path as OpenCL (27.4).

Probe & device model. q8b_probe requires ADRENO_ENABLE in the environment and g2d_get_version() == 690. The device model reports: 1024 threads/block, warp size 64, 8 SMs, 32 KB shared memory per block, compute capability 6.0, 8 GB total — a deliberate CUDA-shaped facade over the a6xx compute engine.

Operator images: ops.q8b. Instead of cubins, this BSP consumes a purpose-built image (magic 0x3844514B, "KUDQ"): a header, one record per kernel (name, local_size, shared/frame/register/cbank0 sizes, the parameter window, pointer ordinals, scalar→uniform-dword mapping, rows_per_group), and the serialized ir3 program blobs. The image is generated on the host: tools/generate.c + tools/Makefile.host compile shaders/*.comp (GLSL compute) through the shared mesa front end and the freedreno/ir3 back end, then pack the records. image.c validates aggressively at load (local-size product ≤ 256, 8-byte-aligned blobs, blob size ≥ adreno_prog_blob_t, parameter count/size caps) and uploads each blob through g2d_cl_program.

Memory. Allocations come from 64 MB physically-contiguous shm pools (1 MB minimum allocation, 256-byte alignment); a 256-byte uniform shm carries scalar arguments. CUdeviceptr is the host virtual address of the pool slice — the GPU reads the same physical pages (zero copy, CB0 identity-mapped).

Launch: deferred, batched, chained. A launch is queued, not submitted: q8b_launch converts the CUDA grid into workgroups (honoring the record's local_size and rows_per_group override), binds pointer arguments as shm subranges and scalars as uniform dwords, then calls g2d_cl_dispatch_deferred. Small launches (≤ 128 workgroups) collect into a batch of up to G2D_CL_BATCH_MAX (8) and flush together through g2d_cl_dispatch_batch — one doorbell, one fence. The flush happens before the CPU touches device memory (memcpy/free/ctx_sync all call q8b_finish first), because a queued launch may still be running. Two environment knobs make A/B testing trivial: KUDA_Q8B_SYNC=1 runs every launch to completion; KUDA_Q8B_BATCH=0 gives every launch its own driver round trip.

The submission layer was further tuned with chained IBs (launches of one decode step build into a single Indirect Buffer while the previous submission is still executing) and ring queueing (a second staging IB rings the doorbell before waiting on the previous fence). Board A/B numbers are in q8b-kuda-gemv-optimization.md.

The operator set is an LLM decode stack. shaders/ contains vec_add, vec_mul, gemv, rmsnorm, add_rmsnorm, silu, silu_mul, rope_* (rotary position embedding variants), argmax_f32, attention_decode_gqa(_sc) (grouped-query attention), and quantized GEMV kernels q4k_gemv(3) / q6k_gemv(3) / q4k_row / q6k_row for llama.cpp K-quant weights. Measured on the Radxa Dragon Q8B (Adreno 690), from the board reports linked above:

Workload Result
vec_add streaming bandwidth (reference) 46.69 GB/s
Llama-3.2-1B Q4_K_M decode ~50.7 tok/s (16-token and 96-token rounds agree)
Qwen3-4B Q4_K_M decode ~15.6–15.9 tok/s
chain / ring A/B 49.12 vs 48.45 tok/s; 49.60 vs 49.07 tok/s

The reports are explicit that these are measured numbers for the current implementation, not hardware peak claims — the quantized GEMV kernels run at 42–45 GB/s against the 46.69 GB/s streaming reference, and the remaining per-step gap is itemized there.

28.6 GA10B: shared cubin/QMD machinery

On Orin Nano the KUDA story is currently the M1 compute path rather than a KUDA BSP: ga10b_compute.c parses real nvcc sm_87 cubins and builds QMD v3.0 launches with the host-tested cubin parser and QMD builder from projects/kuda (its header comment names libs/kuda/src/cubin.c, qmd.c), sharing the cbank0 parameter-window convention (param_base 0x160) that the KUDA core also uses. vectorAdd is board-verified (27.5). A GA10B libkudabsp.a would plug into the same vtable without touching the core; until then, KUDA apps on Orin run on the CPU simulator, and on any machine without a BSP at all.

28.7 Trying it

Build (8gen3, from the repository root):

# core + BSP + default ops.q8b image
make -C hardwares/qcom/8gen3/system/libs kuda HW=8gen3 ARCH=aarch64
# board test app (built after gui libs install libg2dclient)
make -C hardwares/qcom/8gen3/system/libs kuda HW=8gen3 ARCH=aarch64 test
# regenerate the operator image after editing shaders/*.comp (host toolchain)
make -C hardwares/qcom/8gen3/system/libs/kuda -f tools/Makefile.host image

Run on the board (the .rd profile in q8b-kuda-test-flow.md starts g2dd with ADRENO_ENABLE=1):

kuda_vec_add /lib/kuda/ops.q8b            # correctness: CPU twin vs GPU
kuda_vec_add /lib/kuda/ops.q8b --bench    # per-shape ms/iter and GB/s
KUDA_BENCH_FILTER=scan ...                # single-weight shaders only
KUDA_BENCH_FILTER=k3_ ...                 # fused kernels (GB/s output)
KUDA_Q8B_SYNC=1 ...                       # synchronous launches (debug/A-B)

The test app loads the image through kuModuleLoad, looks up kernels with kuModuleGetFunction, and checks GPU results against a CPU reference — the same discipline as vktest/cltest. Without ADRENO_ENABLE (or on a machine without the BSP), kuInit transparently lands on the simulator and the same source still runs.


Back to 27 GPU Support Across the Mainstream Platforms for the graphics side of the same stack; unfamiliar abbreviations are in the glossary.

EwokOS OS Tutorial / EwokOS 操作系统教学

English Home · 中文首页

Part 1: Getting Started / 第 1 部分:起步

Part 2: The Kernel / 第 2 部分:内核

Part 3: Userland / 第 3 部分:用户态

Part 4: The Full System / 第 4 部分:完整系统

Part 5: The ewokos Series (Libraries) / 第 5 部分:ewokos 系列(库生态)

Part 6: GPU & Compute / 第 6 部分:GPU 与计算

Appendix / 附录

Clone this wiki locally