diff --git a/test/vk/icd-spirv.c b/test/vk/icd-spirv.c new file mode 100644 index 0000000..36c09d4 --- /dev/null +++ b/test/vk/icd-spirv.c @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +#include "spirv.h" + +#include +#include +#include + +static int check(const char *path, const uint32_t *want, int nwant) +{ + FILE *f = fopen(path, "rb"); + if (!f) { + perror(path); + return 1; + } + fseek(f, 0, SEEK_END); + long n = ftell(f); + rewind(f); + uint32_t *w = malloc((size_t)n); + if (!w || fread(w, 1, (size_t)n, f) != (size_t)n) { + fprintf(stderr, "%s: cannot read\n", path); + fclose(f); + free(w); + return 1; + } + fclose(f); + uint32_t got[16]; + int ngot = kw_spirv_writable(w, (size_t)n / 4, got, 16); + free(w); + if (ngot != nwant) { + fprintf(stderr, "%s: got %d writable bindings, want %d\n", path, ngot, nwant); + return 1; + } + for (int i = 0; i < nwant; i++) { + int found = 0; + for (int k = 0; k < ngot; k++) + found |= got[k] == want[i]; + if (!found) { + fprintf(stderr, "%s: missing writable binding %u.%u\n", path, + want[i] >> 16, want[i] & 0xffff); + return 1; + } + } + return 0; +} + +int main(void) +{ + static const uint32_t declared[] = {1}; + static const uint32_t compute[] = {1, 2, 3}; + static const uint32_t malformed[] = {0x07230203, 0x00010000, 0, 2, 0, 0}; + int fail = 0; + fail += check("vk/naga/test/shaders/buffer.comp.spv", declared, 1); + fail += check("vk/naga/test/shaders/buffer.comp.opt.spv", declared, 1); + fail += check("vk/naga/test/shaders/unwritten.comp.spv", compute, 3); + fail += check("vk/naga/test/shaders/unwritten.comp.opt.spv", compute, 3); + fail += check("vk/naga/test/shaders/unwritten.vert.spv", NULL, 0); + fail += check("vk/naga/test/shaders/unwritten.vert.opt.spv", NULL, 0); + uint32_t out; + if (kw_spirv_writable(malformed, sizeof malformed / sizeof malformed[0], &out, 1) != -1) { + fputs("malformed SPIR-V did not take the conservative fallback\n", stderr); + fail++; + } + if (!fail) + puts("kwvk SPIR-V writable analysis: ok"); + return !!fail; +} diff --git a/test/vk/icd-spirv.sh b/test/vk/icd-spirv.sh new file mode 100755 index 0000000..fd661c0 --- /dev/null +++ b/test/vk/icd-spirv.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: GPL-2.0-or-later +# Copyright (C) 2026 Pooya Parsa +set -euo pipefail +cd "$(dirname "$0")/../.." +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +cc -O2 -Wall -Wextra -Werror -I vk/icd -o "$work/test-spirv" test/vk/icd-spirv.c vk/icd/spirv.c +"$work/test-spirv" diff --git a/vk/PROTOCOL.md b/vk/PROTOCOL.md index 2b37aeb..a48abc5 100644 --- a/vk/PROTOCOL.md +++ b/vk/PROTOCOL.md @@ -593,9 +593,10 @@ sides can (Amendments, "External present"). carry at most 16 MiB each (a multi-MiB upload is several frames). - ICD (round 4): GPU-written buffers are now marked at each draw or dispatch, only for the storage buffers the bound pipeline's shaders may - write (the ICD scans each module's SPIR-V for storage-buffer variables - not decorated NonWritable; a module it cannot read marks everything, as - before). Mapped memory is page-aligned. + write. The ICD scans each module's SPIR-V: a variable decorated + NonWritable, or whose derived pointers provably reach only loads, + OpArrayLength and access chains, is read-only; a module it cannot read + marks everything, as before. Mapped memory is page-aligned. - Host (ICD agent, round 4): compute stages get their read-only storage buffers as `read_write` (WGSL rewritten after translation, layout type "storage"): ggml-vulkan binds one buffer at different offsets read-only @@ -1056,4 +1057,6 @@ sides can (Amendments, "External present"). range of its buffer (VK_WHOLE_SIZE: to the buffer's end): read by a draw or dispatch for the submit flush, and, for a storage texel buffer the bound pipeline may write (the ICD's scan: an imageBuffer variable - not decorated NonWritable), GPU-written there for readback. + not decorated NonWritable), GPU-written there for readback. The same + scan recognizes plain storage buffers that the module never writes, + so they are not read back after a fence wait. diff --git a/vk/icd/build.sh b/vk/icd/build.sh index b5c77bb..1fe47d9 100755 --- a/vk/icd/build.sh +++ b/vk/icd/build.sh @@ -50,7 +50,7 @@ flags=(-O2 -g0 -Wall -Wextra -Wno-unused-parameter -fPIC -fvisibility=hidden -I strip=() [ "$mode" = guest ] && strip=(-s) "${cc[@]}" "${flags[@]}" "${strip[@]}" -shared -Wl,-soname,libvulkan_kw.so -o "$out/libvulkan_kw.so" \ - "$src/icd.c" "$src/link.c" "$src/wsi.c" -lpthread -ldl -lm + "$src/icd.c" "$src/link.c" "$src/spirv.c" "$src/wsi.c" -lpthread -ldl -lm cat >"$out/kw_icd.json" < #include @@ -1444,111 +1445,16 @@ static API VkResult CALL kw_vkCreateSampler(VkDevice dh, const VkSamplerCreateIn } DESTROY_FN(Sampler, VkSampler) -/* (set << 16 | binding) of the storage buffers and storage texel buffers - * (imageBuffer) a SPIR-V module may write: not NonWritable (on the variable - * or on every member of its block). Only those are marked GPU-written at a - * draw or dispatch. -1 when unsure. */ -static int spirv_writable(const uint32_t *w, size_t nw, uint32_t *out, int cap) -{ - if (nw < 5 || w[0] != 0x07230203) - return -1; - uint32_t bound = w[3]; - if (bound > (1u << 22)) - return -1; - uint8_t *nonwr = calloc(bound, 1); /* var or struct: NonWritable seen */ - uint16_t *mnw = calloc(bound, 2); /* struct: members decorated NonWritable */ - uint16_t *mcount = calloc(bound, 2); /* struct: member count */ - uint8_t *bufblock = calloc(bound, 1); - uint8_t *imgbuf = calloc(bound, 1); /* OpTypeImage Dim Buffer, not known sampled */ - uint32_t *set = calloc(bound, 4), *bind = calloc(bound, 4), *ptr = calloc(bound, 4), *inner = calloc(bound, 4); - uint8_t *hasset = calloc(bound, 1), *hasbind = calloc(bound, 1); - uint32_t *vars = calloc(bound, 4), *varsc = calloc(bound, 4), *ptrsc = calloc(bound, 4); - int n = 0, nvars = 0, bad = !nonwr || !mnw || !mcount || !bufblock || !set || !bind || !ptr || !inner || !hasset || !hasbind || !vars || !varsc || !ptrsc || !imgbuf; - for (size_t i = 5; !bad && i < nw;) { - uint32_t op = w[i] & 0xffff, len = w[i] >> 16; - if (!len || i + len > nw) { - bad = 1; - break; - } - const uint32_t *a = w + i + 1; -#define ID(x) ((x) < bound) - if (op == 71 && len >= 3 && ID(a[0])) { /* OpDecorate */ - if (a[1] == 24) - nonwr[a[0]] = 1; - else if (a[1] == 3) - bufblock[a[0]] = 1; - else if (a[1] == 34 && len >= 4) - set[a[0]] = a[2], hasset[a[0]] = 1; - else if (a[1] == 33 && len >= 4) - bind[a[0]] = a[2], hasbind[a[0]] = 1; - } else if (op == 72 && len >= 4 && ID(a[0]) && a[2] == 24) { /* OpMemberDecorate NonWritable */ - mnw[a[0]]++; - } else if (op == 25 && len >= 9 && ID(a[0])) { /* OpTypeImage: Dim Buffer, Sampled 0 or 2 */ - imgbuf[a[0]] = a[2] == 5 && a[6] != 1; - } else if (op == 30 && len >= 2 && ID(a[0])) { /* OpTypeStruct */ - mcount[a[0]] = (uint16_t)(len - 2); - } else if ((op == 28 || op == 29) && len >= 3 && ID(a[0]) && ID(a[1])) { /* OpTypeArray/RuntimeArray */ - inner[a[0]] = a[1]; - } else if (op == 32 && len >= 4 && ID(a[0]) && ID(a[2])) { /* OpTypePointer */ - ptr[a[0]] = a[2]; - ptrsc[a[0]] = a[1]; - } else if (op == 59 && len >= 4 && ID(a[0]) && ID(a[1])) { /* OpVariable */ - vars[nvars] = a[1]; - varsc[nvars++] = a[0]; - } - i += len; - } - for (int k = 0; !bad && k < nvars; k++) { - uint32_t v = vars[k], pt = varsc[k], sc = ptrsc[pt], ty = ptr[pt]; - if (inner[ty]) - ty = inner[ty]; - if (sc != 12 && !(sc == 2 && bufblock[ty]) && !(sc == 0 && imgbuf[ty])) - continue; /* not a storage buffer or storage texel buffer */ - if (nonwr[v] || (mcount[ty] && mnw[ty] >= mcount[ty])) - continue; /* read-only */ - if (!hasset[v] || !hasbind[v] || n >= cap) { - bad = 1; - break; - } - out[n++] = set[v] << 16 | (bind[v] & 0xffff); - } -#undef ID - free(nonwr), free(mnw), free(mcount), free(bufblock), free(imgbuf), free(set), free(bind), free(ptr), free(inner); - free(hasset), free(hasbind), free(vars), free(varsc), free(ptrsc); - return bad ? -1 : n; -} - -/* does the module decorate anything BuiltIn BaseVertex (4424), BaseInstance - * (4425) or DrawIndex (4426)? WGSL has none: the translator reads 0 */ -static int spirv_base(const uint32_t *w, size_t nw) -{ - if (nw < 5 || w[0] != 0x07230203) - return 0; - for (size_t i = 5; i < nw;) { - uint32_t op = w[i] & 0xffff, len = w[i] >> 16; - if (!len || i + len > nw) - return 0; - if (op == 71 && len >= 4 && w[i + 2] == 11 && w[i + 3] >= 4424 && w[i + 3] <= 4426) - return 1; - if (op == 72 && len >= 5 && w[i + 3] == 11 && w[i + 4] >= 4424 && w[i + 4] <= 4426) - return 1; - if (op == 54) /* OpFunction: past the annotations */ - return 0; - i += len; - } - return 0; -} - static API VkResult CALL kw_vkCreateShaderModule(VkDevice dh, const VkShaderModuleCreateInfo *ci, const VkAllocationCallbacks *a, VkShaderModule *out) { (void)a; struct kw_device *d = DEV(dh); uint32_t tmp[64]; - int nw = spirv_writable(ci->pCode, ci->codeSize / 4, tmp, 64); + int nw = kw_spirv_writable(ci->pCode, ci->codeSize / 4, tmp, 64); struct kw_shader *o = calloc(1, sizeof *o + (nw > 0 ? nw : 0) * sizeof(uint32_t)); o->id = link_id(d->link); o->nw = nw; - o->base = spirv_base(ci->pCode, ci->codeSize / 4); + o->base = kw_spirv_base(ci->pCode, ci->codeSize / 4); if (nw > 0) memcpy(o->w, tmp, nw * sizeof(uint32_t)); struct jb j = {0}; diff --git a/vk/icd/spirv.c b/vk/icd/spirv.c new file mode 100644 index 0000000..e01e0de --- /dev/null +++ b/vk/icd/spirv.c @@ -0,0 +1,269 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +// Conservative SPIR-V reflection used by the guest ICD to decide which +// storage-buffer bindings submitted GPU work may write. +#include "spirv.h" + +#include +#include + +enum { + OP_CAPABILITY = 17, + OP_TYPE_IMAGE = 25, + OP_TYPE_ARRAY = 28, + OP_TYPE_RUNTIME_ARRAY = 29, + OP_TYPE_STRUCT = 30, + OP_TYPE_POINTER = 32, + OP_FUNCTION = 54, + OP_VARIABLE = 59, + OP_LOAD = 61, + OP_ACCESS_CHAIN = 65, + OP_IN_BOUNDS_ACCESS_CHAIN = 66, + OP_PTR_ACCESS_CHAIN = 67, + OP_ARRAY_LENGTH = 68, + OP_IN_BOUNDS_PTR_ACCESS_CHAIN = 70, + OP_DECORATE = 71, + OP_MEMBER_DECORATE = 72, + OP_COPY_OBJECT = 83, + OP_ATOMIC_LOAD = 227, + DEC_BLOCK = 2, + DEC_BUFFER_BLOCK = 3, + DEC_BUILTIN = 11, + DEC_NON_WRITABLE = 24, + DEC_NON_READABLE = 25, + DEC_BINDING = 33, + DEC_DESCRIPTOR_SET = 34, + SC_UNIFORM = 2, + SC_UNIFORM_CONSTANT = 0, + SC_STORAGE_BUFFER = 12, + CAP_VARIABLE_POINTERS_STORAGE_BUFFER = 4441, + CAP_VARIABLE_POINTERS = 4442, + DIM_BUFFER = 5, +}; + +struct scan { + uint8_t *nonwr, *nonread, *bufblock, *imgbuf, *hasset, *hasbind, *storage, *written; + uint16_t *mnw, *mcount; + uint32_t *set, *bind, *ptr, *inner, *ptrsc, *root, *vars, *varptr; +}; + +static void scan_free(struct scan *s) +{ + free(s->nonwr); + free(s->nonread); + free(s->bufblock); + free(s->imgbuf); + free(s->hasset); + free(s->hasbind); + free(s->storage); + free(s->written); + free(s->mnw); + free(s->mcount); + free(s->set); + free(s->bind); + free(s->ptr); + free(s->inner); + free(s->ptrsc); + free(s->root); + free(s->vars); + free(s->varptr); +} + +static int scan_alloc(struct scan *s, uint32_t bound) +{ +#define NEW(field, type) s->field = calloc(bound, sizeof(type)) + NEW(nonwr, uint8_t); + NEW(nonread, uint8_t); + NEW(bufblock, uint8_t); + NEW(imgbuf, uint8_t); + NEW(hasset, uint8_t); + NEW(hasbind, uint8_t); + NEW(storage, uint8_t); + NEW(written, uint8_t); + NEW(mnw, uint16_t); + NEW(mcount, uint16_t); + NEW(set, uint32_t); + NEW(bind, uint32_t); + NEW(ptr, uint32_t); + NEW(inner, uint32_t); + NEW(ptrsc, uint32_t); + NEW(root, uint32_t); + NEW(vars, uint32_t); + NEW(varptr, uint32_t); +#undef NEW + return s->nonwr && s->nonread && s->bufblock && s->imgbuf && s->hasset && s->hasbind && + s->storage && s->written && s->mnw && s->mcount && s->set && s->bind && s->ptr && + s->inner && s->ptrsc && s->root && s->vars && s->varptr; +} + +static uint32_t unwrap_type(const struct scan *s, uint32_t type, uint32_t bound, int *bad) +{ + for (uint32_t n = 0; type < bound && s->inner[type]; n++) { + if (n >= bound) { + *bad = 1; + return 0; + } + type = s->inner[type]; + } + return type; +} + +/* + * Return the set/binding pairs of storage buffers and storage texel buffers + * the module may write. Plain storage buffers that the module provably only + * loads are omitted even when the source did not declare them readonly. + * Anything malformed or not understood returns -1, making the caller mark + * every storage descriptor writable. + */ +int kw_spirv_writable(const uint32_t *w, size_t nw, uint32_t *out, int cap) +{ + if (nw < 5 || w[0] != 0x07230203 || cap < 0) + return -1; + uint32_t bound = w[3]; + if (!bound || bound > (1u << 22)) + return -1; + struct scan s = {0}; + if (!scan_alloc(&s, bound)) { + scan_free(&s); + return -1; + } + int bad = 0, variable_ptrs = 0; + uint32_t nvars = 0; +#define ID(x) ((x) < bound) + for (size_t i = 5; !bad && i < nw;) { + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + if (!len || i + len > nw) { + bad = 1; + break; + } + const uint32_t *a = w + i + 1; + if (op == OP_CAPABILITY && len >= 2 && + (a[0] == CAP_VARIABLE_POINTERS || a[0] == CAP_VARIABLE_POINTERS_STORAGE_BUFFER)) { + variable_ptrs = 1; + } else if (op == OP_DECORATE && len >= 3 && ID(a[0])) { + if (a[1] == DEC_NON_WRITABLE) + s.nonwr[a[0]] = 1; + else if (a[1] == DEC_NON_READABLE) + s.nonread[a[0]] = 1; + else if (a[1] == DEC_BUFFER_BLOCK) + s.bufblock[a[0]] = 1; + else if (a[1] == DEC_DESCRIPTOR_SET && len >= 4) + s.set[a[0]] = a[2], s.hasset[a[0]] = 1; + else if (a[1] == DEC_BINDING && len >= 4) + s.bind[a[0]] = a[2], s.hasbind[a[0]] = 1; + } else if (op == OP_MEMBER_DECORATE && len >= 4 && ID(a[0]) && a[2] == DEC_NON_WRITABLE) { + s.mnw[a[0]]++; + } else if (op == OP_TYPE_IMAGE && len >= 9 && ID(a[0])) { + /* Dim Buffer, Sampled 0 or 2: a storage texel buffer. */ + s.imgbuf[a[0]] = a[2] == DIM_BUFFER && a[6] != 1; + } else if (op == OP_TYPE_STRUCT && len >= 2 && ID(a[0])) { + s.mcount[a[0]] = (uint16_t)(len - 2); + } else if ((op == OP_TYPE_ARRAY || op == OP_TYPE_RUNTIME_ARRAY) && len >= 3 && ID(a[0]) && ID(a[1])) { + s.inner[a[0]] = a[1]; + } else if (op == OP_TYPE_POINTER && len >= 4 && ID(a[0]) && ID(a[2])) { + s.ptr[a[0]] = a[2]; + s.ptrsc[a[0]] = a[1]; + } else if (op == OP_VARIABLE && len >= 4 && ID(a[0]) && ID(a[1])) { + uint32_t ty = unwrap_type(&s, s.ptr[a[0]], bound, &bad); + uint32_t sc = s.ptrsc[a[0]]; + if (sc == SC_STORAGE_BUFFER || (sc == SC_UNIFORM && ID(ty) && s.bufblock[ty]) || + (sc == SC_UNIFORM_CONSTANT && ID(ty) && s.imgbuf[ty])) { + s.vars[nvars++] = a[1]; + s.varptr[a[1]] = a[0]; + s.root[a[1]] = a[1]; + s.storage[a[1]] = sc != SC_UNIFORM_CONSTANT; + } + } + i += len; + } + + /* Follow pointers derived from each storage variable. Unknown uses, + * calls, stores and all atomics except AtomicLoad make it writable. */ + int in_function = 0; + for (size_t i = 5; !bad && !variable_ptrs && i < nw;) { + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + if (!len || i + len > nw) { + bad = 1; + break; + } + const uint32_t *a = w + i + 1; + if (op == OP_FUNCTION) + in_function = 1; + if (in_function && + (op == OP_ACCESS_CHAIN || op == OP_IN_BOUNDS_ACCESS_CHAIN || op == OP_PTR_ACCESS_CHAIN || + op == OP_IN_BOUNDS_PTR_ACCESS_CHAIN || op == OP_COPY_OBJECT) && + len >= 4 && ID(a[1]) && ID(a[2]) && s.root[a[2]]) { + s.root[a[1]] = s.root[a[2]]; + } else if (in_function && op != OP_LOAD && op != OP_ATOMIC_LOAD && op != OP_ARRAY_LENGTH) { + for (uint32_t k = 0; k + 1 < len; k++) + if (ID(a[k]) && s.root[a[k]]) + s.written[s.root[a[k]]] = 1; + } + i += len; + } + + /* A write through any variable at a set/binding makes every view of the + * same binding writable. Variable pointers disable inference entirely. */ + for (uint32_t i = 0; i < nvars; i++) { + uint32_t v = s.vars[i]; + if (!s.storage[v] || (!variable_ptrs && !s.written[v])) + continue; + for (uint32_t k = 0; k < nvars; k++) { + uint32_t x = s.vars[k]; + if (s.storage[x] && s.hasset[v] && s.hasset[x] && s.hasbind[v] && s.hasbind[x] && + s.set[v] == s.set[x] && s.bind[v] == s.bind[x]) + s.written[x] = 1; + } + } + + int n = 0; + for (uint32_t k = 0; !bad && k < nvars; k++) { + uint32_t v = s.vars[k], pt = s.varptr[v], ty = ID(pt) ? s.ptr[pt] : 0; + ty = unwrap_type(&s, ty, bound, &bad); + if (bad) + break; + int declared_ro = s.nonwr[v] || (ID(ty) && s.mcount[ty] && s.mnw[ty] >= s.mcount[ty]); + int inferred_ro = s.storage[v] && !variable_ptrs && !s.nonread[v] && !s.written[v]; + if (declared_ro || inferred_ro) + continue; + if (!s.hasset[v] || !s.hasbind[v]) { + bad = 1; + break; + } + uint32_t slot = s.set[v] << 16 | (s.bind[v] & 0xffff); + int duplicate = 0; + for (int i = 0; i < n; i++) + duplicate |= out[i] == slot; + if (!duplicate) { + if (n >= cap) { + bad = 1; + break; + } + out[n++] = slot; + } + } +#undef ID + scan_free(&s); + return bad ? -1 : n; +} + +int kw_spirv_base(const uint32_t *w, size_t nw) +{ + if (nw < 5 || w[0] != 0x07230203) + return 0; + for (size_t i = 5; i < nw;) { + uint32_t op = w[i] & 0xffff, len = w[i] >> 16; + if (!len || i + len > nw) + return 0; + if (op == OP_DECORATE && len >= 4 && w[i + 2] == DEC_BUILTIN && + w[i + 3] >= 4424 && w[i + 3] <= 4426) + return 1; + if (op == OP_MEMBER_DECORATE && len >= 5 && w[i + 3] == DEC_BUILTIN && + w[i + 4] >= 4424 && w[i + 4] <= 4426) + return 1; + if (op == OP_FUNCTION) + return 0; + i += len; + } + return 0; +} diff --git a/vk/icd/spirv.h b/vk/icd/spirv.h new file mode 100644 index 0000000..9eb60cf --- /dev/null +++ b/vk/icd/spirv.h @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Pooya Parsa +#ifndef KWVK_SPIRV_H +#define KWVK_SPIRV_H + +#include +#include + +int kw_spirv_writable(const uint32_t *words, size_t nwords, uint32_t *out, int cap); +int kw_spirv_base(const uint32_t *words, size_t nwords); + +#endif