CA in WindowServer logged "nil buffer from memory": newBufferWithBytesNoCopy: answered nil for every pointer outside the device region, which is all of an app's own memory. Metal makes one over any range the process maps readable, at any alignment and length (measured on an M3 Max at 16 KiB and, under Rosetta, 4 KiB pages: malloc'd, vm_allocate'd, read-only and file-mapped memory), and answers nil only for a length of 0 or a range not wholly mapped. Such a buffer now lies over a region block of its own, and its contents stay the app's pointer. The block syncs with the memory as the IOSurface copies do: the CPU's bytes go in at the commit of each command buffer that uses it, and the GPU's come back when one that may write it completes, before its completion is reported. Only the bytes each side moved since the two last agreed move, byte by byte, so CPU and GPU writes beside each other both stand. The encoders note each use as a read or a write, and they look up a buffer only while a shadow lives. A null pointer gets zeroed contents of the buffer's own, and its deallocator gets null, as Metal's does.
1520 lines
59 KiB
C++
1520 lines
59 KiB
C++
/*
|
|
* serializer_tests: the reims-graphics guest serialiser's self-contained check,
|
|
* run on the Mac (guest/bundle/Makefile `test`). It builds a plain-buffer region,
|
|
* a ring writer over it, and a serialiser, posts every message the slice covers,
|
|
* and reads each back with a minimal host-side consumer (the mirror of
|
|
* crates/reims-graphics/src/ring.rs), asserting the type, size and fields on the
|
|
* wire. No Metal, no device: this validates the serialiser's bytes alone.
|
|
*
|
|
* Exits 0 and prints a one-line summary when every check passes; aborts on the
|
|
* first failure.
|
|
*/
|
|
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cassert>
|
|
#include <cstdint>
|
|
#include <cstdio>
|
|
#include <cstring>
|
|
#include <vector>
|
|
|
|
#include "RgfxBinaryArchiveFile.hpp"
|
|
#include "RgfxCaps.hpp"
|
|
#include "RgfxEncoder.hpp"
|
|
#include "RgfxHeapRanges.hpp"
|
|
#include "RgfxLibraryKey.hpp"
|
|
#include "RgfxMemoryShadow.hpp"
|
|
#include "RgfxObjectModel.hpp"
|
|
#include <chrono>
|
|
#include <thread>
|
|
|
|
#include "RgfxReplyReader.hpp"
|
|
#include "RgfxRingWriter.hpp"
|
|
#include "RgfxSerializer.hpp"
|
|
#include "reims_graphics_wire.h"
|
|
#include "rgfx_test_ring.hpp" // CHECK, g_checks, TestRing, expectMessage
|
|
|
|
namespace {
|
|
|
|
void test_id_space()
|
|
{
|
|
RgfxIdSpace ids;
|
|
CHECK(ids.allocObjId() == 1);
|
|
CHECK(ids.allocObjId() == 2);
|
|
CHECK(ids.allocResourceId() == 1);
|
|
CHECK(ids.allocResourceId() == 2);
|
|
|
|
uint64_t a = ids.allocAddress(100, 256);
|
|
uint64_t b = ids.allocAddress(1, 4096);
|
|
CHECK(a >= RgfxIdSpace::kDefaultAddressBase);
|
|
CHECK((a % RgfxIdSpace::kAddressGranule) == 0);
|
|
CHECK((b % RgfxIdSpace::kAddressGranule) == 0);
|
|
CHECK(b >= a + RgfxIdSpace::addressSpan(100)); // a's span, its guard page included
|
|
}
|
|
|
|
// GPU addresses hold Metal's span of a pin: each starts a 32 KiB granule, holds the pages its
|
|
// bytes touch and one guard page, rounded up to a granule, and no two live spans meet, so the
|
|
// host pins every one. A span given back is picked again once the picks have gone round the
|
|
// context's range, joined with the free spans beside it.
|
|
void test_address_picks()
|
|
{
|
|
const uint64_t page = RgfxIdSpace::kAddressPage, granule = RgfxIdSpace::kAddressGranule;
|
|
CHECK(RgfxIdSpace::addressSpan(0) == 2 * page);
|
|
CHECK(RgfxIdSpace::addressSpan(1) == 2 * page);
|
|
CHECK(RgfxIdSpace::addressSpan(page) == 2 * page);
|
|
CHECK(RgfxIdSpace::addressSpan(page + 1) == 4 * page);
|
|
CHECK(RgfxIdSpace::addressSpan(3 * page) == 4 * page);
|
|
CHECK(RgfxIdSpace::addressSpan(64 * page) == 66 * page);
|
|
CHECK(RgfxIdSpace::addressSpan(65 * page) == 66 * page);
|
|
|
|
// A context's range, as the kext hands it (slot 3), its picks granule-aligned and their
|
|
// spans apart, whatever their sizes: one of a heap's 1 MiB, then a buffer's 16 KiB.
|
|
RgfxIdSpace ids;
|
|
const uint64_t base = RGFX_CONTEXT_VA_BASE + 3 * RGFX_CONTEXT_VA_SPAN;
|
|
ids.setBases(uint64_t{4} << RGFX_CONTEXT_OBJ_ID_SHIFT, base);
|
|
uint64_t prev = 0, prevSize = 0;
|
|
const uint64_t sizes[] = {1u << 20, 0x4000, 256, 1, 0x4001, 4u << 20, 0x8000};
|
|
for (uint64_t size : sizes) {
|
|
uint64_t at = ids.allocAddress(size, 256);
|
|
CHECK(at >= base && at % granule == 0);
|
|
if (prev != 0)
|
|
CHECK(at >= prev + RgfxIdSpace::addressSpan(prevSize));
|
|
prev = at;
|
|
prevSize = size;
|
|
}
|
|
// A larger alignment is honoured.
|
|
CHECK(ids.allocAddress(1, 0x10'0000) % 0x10'0000 == 0);
|
|
|
|
// Next fit: a span given back is not picked again at once.
|
|
uint64_t a = ids.allocAddress(1, 1);
|
|
ids.freeAddress(a);
|
|
uint64_t b = ids.allocAddress(1, 1);
|
|
CHECK(b > a);
|
|
ids.freeAddress(0); // no pick: ignored
|
|
ids.freeAddress(a); // given back already: ignored
|
|
ids.freeAddress(b + 256); // no pick starts there: ignored
|
|
|
|
// Round the range: 1 GiB picks till none is left, then two side by side given back, which
|
|
// a pick of both their spans takes, at the first's address.
|
|
RgfxIdSpace full;
|
|
full.setBases(uint64_t{5} << RGFX_CONTEXT_OBJ_ID_SHIFT, base);
|
|
const uint64_t gib = uint64_t{1} << 30;
|
|
std::vector<uint64_t> picks;
|
|
for (;;) {
|
|
uint64_t at = full.allocAddress(gib, 1);
|
|
if (at == 0)
|
|
break;
|
|
picks.push_back(at);
|
|
}
|
|
CHECK(picks.size() == RGFX_CONTEXT_VA_SPAN / RgfxIdSpace::addressSpan(gib));
|
|
CHECK(picks.back() + RgfxIdSpace::addressSpan(gib) <= base + RGFX_CONTEXT_VA_SPAN);
|
|
full.freeAddress(picks[10]);
|
|
full.freeAddress(picks[11]);
|
|
uint64_t both = full.allocAddress(2 * RgfxIdSpace::addressSpan(gib) - 2 * page, 1);
|
|
CHECK(both == picks[10]);
|
|
CHECK(full.allocAddress(gib, 1) == 0); // no other 1 GiB span is free
|
|
full.freeAddress(picks[3]);
|
|
CHECK(full.allocAddress(gib, 1) == picks[3]);
|
|
|
|
// Picks from several threads at once never share a span.
|
|
RgfxIdSpace shared;
|
|
std::vector<uint64_t> got[4];
|
|
std::vector<std::thread> threads;
|
|
for (auto &g : got)
|
|
threads.emplace_back([&shared, &g] {
|
|
for (int i = 0; i < 500; i++) {
|
|
uint64_t at = shared.allocAddress(0x1000, 1);
|
|
g.push_back(at);
|
|
if (i % 3 == 0)
|
|
shared.freeAddress(at);
|
|
}
|
|
});
|
|
for (auto &t : threads)
|
|
t.join();
|
|
std::vector<uint64_t> all;
|
|
for (auto &g : got)
|
|
all.insert(all.end(), g.begin(), g.end());
|
|
std::sort(all.begin(), all.end());
|
|
CHECK(std::adjacent_find(all.begin(), all.end()) == all.end());
|
|
}
|
|
|
|
// A chunk source standing in for the kext: it hands each first id of `firsts` in turn, then
|
|
// answers none left, and counts its calls (the user-client calls a create would make).
|
|
struct FakeChunks {
|
|
std::vector<uint64_t> firsts;
|
|
size_t next = 0;
|
|
int calls = 0;
|
|
};
|
|
|
|
bool fakeChunk(void *context, uint64_t *first_id)
|
|
{
|
|
FakeChunks *f = static_cast<FakeChunks *>(context);
|
|
f->calls++;
|
|
if (f->next == f->firsts.size())
|
|
return false;
|
|
*first_id = f->firsts[f->next++];
|
|
return true;
|
|
}
|
|
|
|
void test_resource_id_chunks()
|
|
{
|
|
const uint64_t chunk = RGFX_RESOURCE_ID_CHUNK;
|
|
|
|
// With no source, the ids are the whole pool's, in order, to its last whole chunk below
|
|
// the limit; then none, until one is given back.
|
|
{
|
|
RgfxIdSpace ids;
|
|
const uint64_t last = RGFX_RESOURCE_ID_CHUNKS * chunk;
|
|
CHECK(last < RGFX_RESOURCE_ID_LIMIT);
|
|
for (uint64_t id = 1; id <= last; id++)
|
|
CHECK(ids.allocResourceId() == id);
|
|
CHECK(ids.allocResourceId() == 0);
|
|
ids.freeResourceId(100);
|
|
CHECK(ids.allocResourceId() == 100);
|
|
CHECK(ids.allocResourceId() == 0);
|
|
}
|
|
|
|
// From the kext's chunks: 7 (ids 449 to 512), then 3 (ids 193 to 256), then none.
|
|
FakeChunks f;
|
|
f.firsts = {1 + 7 * chunk, 1 + 3 * chunk};
|
|
RgfxIdSpace ids;
|
|
ids.setResourceIdSource(&fakeChunk, &f);
|
|
|
|
// Take: the first id takes a chunk; its other 63 take no other.
|
|
CHECK(ids.allocResourceId() == 449);
|
|
CHECK(f.calls == 1);
|
|
for (uint64_t id = 450; id <= 512; id++)
|
|
CHECK(ids.allocResourceId() == id);
|
|
CHECK(f.calls == 1);
|
|
|
|
// Free and reuse: the lowest id given back comes first, and no chunk is taken.
|
|
ids.freeResourceId(460);
|
|
ids.freeResourceId(455);
|
|
CHECK(ids.allocResourceId() == 455);
|
|
CHECK(ids.allocResourceId() == 460);
|
|
CHECK(f.calls == 1);
|
|
|
|
// Refill: with the chunk full, the next id is a new chunk's first.
|
|
CHECK(ids.allocResourceId() == 193);
|
|
CHECK(f.calls == 2);
|
|
// The chunks are tried in the order taken, so an id given back to the first comes before
|
|
// the second's next.
|
|
ids.freeResourceId(500);
|
|
CHECK(ids.allocResourceId() == 500);
|
|
CHECK(ids.allocResourceId() == 194);
|
|
|
|
// 0, an id of a chunk the process does not hold, and ids past the pool are ignored.
|
|
ids.freeResourceId(0);
|
|
ids.freeResourceId(1);
|
|
ids.freeResourceId(RGFX_RESOURCE_ID_LIMIT - 1);
|
|
ids.freeResourceId(RGFX_RESOURCE_ID_LIMIT);
|
|
ids.freeResourceId(~0ull);
|
|
|
|
// Exhaustion: once both chunks are full and the source has none, no id, each time asked.
|
|
for (uint64_t id = 195; id <= 256; id++)
|
|
CHECK(ids.allocResourceId() == id);
|
|
CHECK(ids.allocResourceId() == 0);
|
|
CHECK(f.calls == 3);
|
|
CHECK(ids.allocResourceId() == 0);
|
|
CHECK(f.calls == 4);
|
|
// An id given back is taken again with no call.
|
|
ids.freeResourceId(200);
|
|
CHECK(ids.allocResourceId() == 200);
|
|
CHECK(f.calls == 4);
|
|
|
|
// A chunk that is not one of the pool's (not a chunk's first id, past the pool, 0), or
|
|
// one held already, gives no id.
|
|
FakeChunks bad;
|
|
bad.firsts = {2, 1 + RGFX_RESOURCE_ID_CHUNKS * chunk, 0, 1 + 5 * chunk, 1 + 5 * chunk};
|
|
RgfxIdSpace badIds;
|
|
badIds.setResourceIdSource(&fakeChunk, &bad);
|
|
CHECK(badIds.allocResourceId() == 0);
|
|
CHECK(badIds.allocResourceId() == 0);
|
|
CHECK(badIds.allocResourceId() == 0);
|
|
CHECK(badIds.allocResourceId() == 1 + 5 * chunk);
|
|
for (uint64_t i = 1; i < chunk; i++)
|
|
CHECK(badIds.allocResourceId() == 1 + 5 * chunk + i);
|
|
CHECK(badIds.allocResourceId() == 0);
|
|
|
|
// A texture create with no id left posts nothing and answers no object; one given back
|
|
// lets the next create go out with it.
|
|
TestRing ring(0x8000);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
|
|
nullptr);
|
|
FakeChunks one;
|
|
one.firsts = {1 + 9 * chunk};
|
|
RgfxIdSpace serIds;
|
|
serIds.setResourceIdSource(&fakeChunk, &one);
|
|
RgfxSerializer ser(writer, serIds);
|
|
RgfxTextureDescriptor desc = {};
|
|
desc.pixel_format = 80;
|
|
desc.texture_type = 2;
|
|
desc.width = desc.height = desc.depth = 1;
|
|
desc.mipmap_level_count = desc.array_length = desc.sample_count = 1;
|
|
for (uint64_t i = 0; i < chunk; i++) {
|
|
RgfxCreated t = ser.createTexture(desc);
|
|
CHECK(t.posted && t.resource_id == 1 + 9 * chunk + i);
|
|
auto tm = expectMessage<RgfxTextureCreate>(ring, RGFX_CMD_TEXTURE_CREATE);
|
|
CHECK(tm.resource_id == t.resource_id);
|
|
}
|
|
RgfxCreated none = ser.createTexture(desc);
|
|
CHECK(!none.posted && none.obj_id == 0 && none.resource_id == 0 && none.gpu_address == 0);
|
|
RgfxCreated noneFromBuffer = ser.createTextureFromBuffer(1, 0, 4, desc);
|
|
CHECK(!noneFromBuffer.posted && noneFromBuffer.resource_id == 0);
|
|
RgfxCreated noneFromSurface = ser.createTextureFromIOSurface(1, 0, 4, 0x55, 0, desc);
|
|
CHECK(!noneFromSurface.posted && noneFromSurface.resource_id == 0);
|
|
RgfxTextureView noView = {};
|
|
noView.parent_obj_id = 1;
|
|
RgfxCreated noneView = ser.createTextureView(noView);
|
|
CHECK(!noneView.posted && noneView.resource_id == 0 && noneView.obj_id == 0);
|
|
RgfxMsgHeader h = {};
|
|
std::vector<uint8_t> bytes;
|
|
CHECK(!ring.next(&h, &bytes));
|
|
ser.releaseResourceId(1 + 9 * chunk + 3);
|
|
RgfxCreated again = ser.createTexture(desc);
|
|
CHECK(again.posted && again.resource_id == 1 + 9 * chunk + 3);
|
|
auto am = expectMessage<RgfxTextureCreate>(ring, RGFX_CMD_TEXTURE_CREATE);
|
|
CHECK(am.resource_id == again.resource_id && am.obj_id == again.obj_id);
|
|
}
|
|
|
|
void test_caps()
|
|
{
|
|
RgfxCaps caps;
|
|
// A bad version is refused and leaves the caps invalid.
|
|
RgfxDeviceInfo bad = {};
|
|
bad.version = RGFX_DEVICE_INFO_VERSION + 1;
|
|
CHECK(!caps.load(bad));
|
|
CHECK(!caps.valid());
|
|
|
|
RgfxDeviceInfo info = {};
|
|
info.version = RGFX_DEVICE_INFO_VERSION;
|
|
info.registry_id = 0xabcd;
|
|
info.gpu_core_count = 16;
|
|
info.max_threads_per_threadgroup[0] = 1024;
|
|
info.max_threads_per_threadgroup[1] = 512;
|
|
info.max_threads_per_threadgroup[2] = 64;
|
|
info.max_vertex_amplification_count = 2;
|
|
// The families and feature sets are looked up by value, not by position.
|
|
info.family_count = 3;
|
|
info.family_values[0] = 1005; // Apple5
|
|
info.family_answers[0] = 1;
|
|
info.family_values[1] = 1006; // Apple6, a present no
|
|
info.family_values[2] = -1009;
|
|
info.family_answers[2] = 1;
|
|
info.family_values[3] = 1007; // past family_count: not read
|
|
info.family_answers[3] = 1;
|
|
info.feature_set_count = 2;
|
|
info.feature_set_values[0] = 10005; // macOS_GPUFamily2_v1
|
|
info.feature_set_answers[0] = 1;
|
|
info.feature_set_values[1] = 10002; // macOS_ReadWriteTextureTier2, a present no
|
|
info.sizes[kRgfxSizeRecommendedMaxWorkingSetSize] = 1ull << 34; // first by position
|
|
info.sizes[kRgfxSizeLargestRasterizationRateMapLayerCount] = 2; // last by position
|
|
info.identity_flags[kRgfxIdentityIsLowPower] = 1; // first by position
|
|
info.identity_flags[kRgfxIdentitySupportsPlacementSparse] = 1; // last by position
|
|
info.counter_sampling[0] = 1; // at stage boundaries
|
|
info.format_count = 1;
|
|
info.formats[0].format = 80; // BGRA8Unorm
|
|
info.formats[0].texture_buffer_alignment = 16;
|
|
info.formats[0].sparse_tiles[0][0] = 64; // 1 sample, 16 KiB pages
|
|
info.formats[0].sparse_tiles[0][1] = 64;
|
|
info.formats[0].sparse_tiles[0][2] = 1;
|
|
info.formats[0].sparse_tiles[8][0] = 128; // 4 samples, 256 KiB pages
|
|
info.formats[0].sparse_tiles[8][1] = 128;
|
|
info.formats[0].sparse_tiles[8][2] = 1;
|
|
info.formats[1].format = 70; // past format_count: not read
|
|
info.formats[1].texture_buffer_alignment = 16;
|
|
const char *arch = "test_arch";
|
|
info.architecture_name_len = static_cast<uint32_t>(std::strlen(arch));
|
|
std::memcpy(info.architecture_name, arch, info.architecture_name_len);
|
|
info.sample_counts[0] = 1; // count 1
|
|
info.sample_counts[2] = 1; // count 4
|
|
info.primitive_types[3] = 1;
|
|
info.write_rounding_modes[1] = 1; // mode 2
|
|
info.limits[kRgfxLimitDeviceLinearTextureAlignmentBytes] = 64;
|
|
info.limits[kRgfxLimitMaxViewportCount] = 16; // last by position
|
|
info.flags[kRgfxFlagAreRasterOrderGroupsSupported] = 1; // first by position
|
|
info.flags[kRgfxFlagSupportsTileShaders] = 1; // last by position
|
|
// Longer than the 32 bytes the first layout held.
|
|
const char *nm = "NVIDIA GeForce RTX 5080 Laptop GPU";
|
|
info.name_len = static_cast<uint32_t>(std::strlen(nm));
|
|
std::memcpy(info.name, nm, info.name_len);
|
|
|
|
CHECK(caps.load(info));
|
|
CHECK(caps.valid());
|
|
CHECK(caps.registryId() == 0xabcd);
|
|
CHECK(caps.gpuCoreCount() == 16);
|
|
CHECK(caps.maxThreadsPerThreadgroup(0) == 1024);
|
|
CHECK(caps.maxThreadsPerThreadgroup(2) == 64);
|
|
CHECK(caps.maxVertexAmplificationCount() == 2);
|
|
CHECK(caps.supportsFamily(1005));
|
|
CHECK(caps.supportsFamily(-1009));
|
|
CHECK(!caps.supportsFamily(1006));
|
|
CHECK(!caps.supportsFamily(1007)); // listed past the count
|
|
CHECK(!caps.supportsFamily(42)); // names no family
|
|
CHECK(caps.supportsFeatureSet(10005));
|
|
CHECK(!caps.supportsFeatureSet(10002));
|
|
CHECK(!caps.supportsFeatureSet(0)); // not listed
|
|
CHECK(caps.size(kRgfxSizeRecommendedMaxWorkingSetSize) == 1ull << 34);
|
|
CHECK(caps.size(kRgfxSizeLargestRasterizationRateMapLayerCount) == 2);
|
|
CHECK(caps.size(kRgfxSizeMaxBufferLength) == 0); // a gap reads 0
|
|
CHECK(caps.identityFlag(kRgfxIdentityIsLowPower));
|
|
CHECK(caps.identityFlag(kRgfxIdentitySupportsPlacementSparse));
|
|
CHECK(!caps.identityFlag(kRgfxIdentityHasUnifiedMemory));
|
|
CHECK(caps.supportsCounterSampling(0));
|
|
CHECK(!caps.supportsCounterSampling(1));
|
|
CHECK(!caps.supportsCounterSampling(5));
|
|
CHECK(std::strcmp(caps.architectureName(), "test_arch") == 0);
|
|
CHECK(caps.textureBufferAlignment(80) == 16);
|
|
CHECK(caps.textureBufferAlignment(70) == 0); // listed past the count
|
|
CHECK(caps.textureBufferAlignment(130) == 0); // not listed
|
|
uint64_t tile[3];
|
|
CHECK(caps.sparseTile(80, 1, 101, tile) && tile[0] == 64 && tile[1] == 64 && tile[2] == 1);
|
|
CHECK(caps.sparseTile(80, 4, 103, tile) && tile[0] == 128 && tile[2] == 1);
|
|
CHECK(!caps.sparseTile(80, 2, 102, tile) && tile[0] == 0); // a zero tile is no answer
|
|
CHECK(!caps.sparseTile(80, 8, 101, tile)); // no such sample count
|
|
CHECK(!caps.sparseTile(80, 1, 104, tile)); // no such page
|
|
CHECK(!caps.sparseTile(130, 1, 101, tile)); // not listed
|
|
CHECK(caps.supportsSampleCount(1));
|
|
CHECK(caps.supportsSampleCount(4));
|
|
CHECK(!caps.supportsSampleCount(2));
|
|
CHECK(!caps.supportsSampleCount(8));
|
|
CHECK(!caps.supportsSampleCount(3)); // not a power the blob holds
|
|
CHECK(caps.supportsPrimitiveType(3));
|
|
CHECK(!caps.supportsPrimitiveType(0));
|
|
CHECK(caps.supportsWriteRoundingMode(2));
|
|
CHECK(!caps.supportsWriteRoundingMode(1));
|
|
CHECK(caps.limit(kRgfxLimitDeviceLinearTextureAlignmentBytes) == 64);
|
|
CHECK(caps.limit(kRgfxLimitMaxViewportCount) == 16);
|
|
CHECK(caps.flag(kRgfxFlagAreRasterOrderGroupsSupported));
|
|
CHECK(caps.flag(kRgfxFlagSupportsTileShaders));
|
|
CHECK(!caps.flag(kRgfxFlagSupportsImageBlocks));
|
|
CHECK(std::strcmp(caps.name(), "NVIDIA GeForce RTX 5080 Laptop GPU") == 0);
|
|
}
|
|
|
|
// A heap or buffer whose GPU address finds no room in the context's range is no object: the
|
|
// create posts nothing and answers ids of 0, so the caller answers nil, as Metal does for one it
|
|
// cannot place; a smaller one that fits is made after it.
|
|
void test_creates_with_no_address_post_nothing()
|
|
{
|
|
TestRing ring(0x8000);
|
|
ring.setConsumerIdle(1);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
|
|
nullptr);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
const uint64_t past = RGFX_CONTEXT_VA_SPAN; // its span, with the guard page, passes the range
|
|
RgfxCreated h = ser.createHeap(past, 0, 1);
|
|
RgfxCreated hh = ser.createHeapOverHostMemory(past, 0, 1, 0x40000);
|
|
RgfxCreated b = ser.createBuffer(past, 0);
|
|
RgfxCreated bh = ser.createBufferOverHostMemory(past, 0, 0x50000);
|
|
for (const RgfxCreated &c : {h, hh, b, bh})
|
|
CHECK(!c.posted && c.obj_id == 0 && c.gpu_address == 0);
|
|
RgfxMsgHeader header = {};
|
|
std::vector<uint8_t> bytes;
|
|
CHECK(!ring.next(&header, &bytes));
|
|
RgfxCreated fits = ser.createHeap(0x10000, 0, 1);
|
|
CHECK(fits.posted && fits.obj_id == 1 && fits.gpu_address != 0);
|
|
CHECK(expectMessage<RgfxHeapCreate>(ring, RGFX_CMD_HEAP_CREATE).obj_id == 1);
|
|
}
|
|
|
|
void test_lifecycle_messages()
|
|
{
|
|
TestRing ring(0x8000);
|
|
ring.setConsumerIdle(1); // the host is idle, so each post rings the doorbell
|
|
int before = TestRing::doorbells.load();
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
|
|
nullptr);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
|
|
// Queue.
|
|
RgfxCreated q = ser.createQueue(0x20000, 0x30000, 0x1000, 0x1000, 2, 1);
|
|
CHECK(q.posted);
|
|
CHECK(q.obj_id == 1);
|
|
CHECK(q.seqno == 1); // the first message on the ring
|
|
auto qm = expectMessage<RgfxQueueCreate>(ring, RGFX_CMD_QUEUE_CREATE);
|
|
CHECK(qm.header.seqno == 1);
|
|
CHECK(qm.obj_id == 1);
|
|
CHECK(qm.submit_offset == 0x20000 && qm.complete_offset == 0x30000);
|
|
CHECK(qm.submit_data_size == 0x1000 && qm.complete_data_size == 0x1000);
|
|
CHECK(qm.priority == 2 && qm.vector == 1);
|
|
|
|
// Heap (device) and heap over host memory.
|
|
RgfxCreated h = ser.createHeap(0x10000, 0, 1 /*Placement*/, 4096);
|
|
CHECK(h.posted && (h.gpu_address % 4096) == 0);
|
|
auto hm = expectMessage<RgfxHeapCreate>(ring, RGFX_CMD_HEAP_CREATE);
|
|
CHECK(hm.obj_id == h.obj_id && hm.gpu_address == h.gpu_address);
|
|
CHECK(hm.size_bytes == 0x10000 && hm.heap_type == 1);
|
|
|
|
RgfxCreated hh = ser.createHeapOverHostMemory(0x2000, 0, 0, 0x40000);
|
|
CHECK(hh.posted);
|
|
auto hhm = expectMessage<RgfxHeapOverHostMemory>(ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY);
|
|
CHECK(hhm.obj_id == hh.obj_id && hhm.region_offset == 0x40000 && hhm.size_bytes == 0x2000);
|
|
|
|
// Buffers: device, over host memory, at offset in a heap.
|
|
RgfxCreated b = ser.createBuffer(0x1000, 0);
|
|
CHECK(b.posted && b.gpu_address != 0);
|
|
auto bm = expectMessage<RgfxBufferCreate>(ring, RGFX_CMD_BUFFER_CREATE);
|
|
CHECK(bm.obj_id == b.obj_id && bm.gpu_address == b.gpu_address && bm.length == 0x1000);
|
|
CHECK(bm.reserved_2c == 0);
|
|
|
|
RgfxCreated bh = ser.createBufferOverHostMemory(0x800, 0, 0x50000);
|
|
CHECK(bh.posted);
|
|
auto bhm = expectMessage<RgfxBufferOverHostMemory>(ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
|
|
CHECK(bhm.obj_id == bh.obj_id && bhm.region_offset == 0x50000 && bhm.length == 0x800);
|
|
|
|
RgfxCreated bo = ser.createBufferAtOffset(h.obj_id, 0x100, 0x200, 0);
|
|
CHECK(bo.posted && bo.gpu_address == 0); // derived host-side from the heap
|
|
auto bom = expectMessage<RgfxBufferAtOffset>(ring, RGFX_CMD_BUFFER_AT_OFFSET);
|
|
CHECK(bom.obj_id == bo.obj_id && bom.heap_obj_id == h.obj_id);
|
|
CHECK(bom.offset == 0x100 && bom.length == 0x200);
|
|
|
|
// Textures: device-placed and heap-placed and from a buffer.
|
|
RgfxTextureDescriptor desc = {};
|
|
desc.pixel_format = 80; // MTLPixelFormatBGRA8Unorm
|
|
desc.texture_type = 2; // MTLTextureType2D
|
|
desc.width = 1920;
|
|
desc.height = 1080;
|
|
desc.depth = 1;
|
|
desc.mipmap_level_count = 1;
|
|
desc.array_length = 1;
|
|
desc.sample_count = 1;
|
|
desc.usage = 4; // MTLTextureUsageRenderTarget
|
|
|
|
RgfxCreated t = ser.createTexture(desc);
|
|
CHECK(t.posted && t.resource_id != 0 && t.gpu_address != 0);
|
|
auto tm = expectMessage<RgfxTextureCreate>(ring, RGFX_CMD_TEXTURE_CREATE);
|
|
CHECK(tm.obj_id == t.obj_id && tm.resource_id == t.resource_id);
|
|
CHECK(tm.gpu_address == t.gpu_address && tm.heap_obj_id == 0);
|
|
CHECK(tm.desc.width == 1920 && tm.desc.height == 1080 && tm.desc.pixel_format == 80);
|
|
|
|
RgfxCreated th = ser.createTexture(desc, h.obj_id, 0x400);
|
|
CHECK(th.posted && th.gpu_address == 0); // heap-placed: no device address
|
|
auto thm = expectMessage<RgfxTextureCreate>(ring, RGFX_CMD_TEXTURE_CREATE);
|
|
CHECK(thm.heap_obj_id == h.obj_id && thm.heap_offset == 0x400);
|
|
|
|
RgfxCreated tb = ser.createTextureFromBuffer(b.obj_id, 0x10, 7680, desc);
|
|
CHECK(tb.posted);
|
|
auto tbm = expectMessage<RgfxTextureFromBuffer>(ring, RGFX_CMD_TEXTURE_FROM_BUFFER);
|
|
CHECK(tbm.buffer_obj_id == b.obj_id && tbm.offset == 0x10 && tbm.bytes_per_row == 7680);
|
|
CHECK(tbm.resource_id == tb.resource_id && tbm.desc.width == 1920);
|
|
|
|
// A view: the parent and shape as given, the ids picked.
|
|
RgfxTextureView v = {};
|
|
v.obj_id = 0x77; // not read
|
|
v.resource_id = 0x77; // not read
|
|
v.parent_obj_id = tb.obj_id;
|
|
v.pixel_format = 81;
|
|
v.flags = RGFX_TEXTURE_VIEW_SUBRANGE | RGFX_TEXTURE_VIEW_SWIZZLE;
|
|
v.texture_type = 2;
|
|
v.level_count = 1;
|
|
v.slice_start = 0;
|
|
v.slice_count = 1;
|
|
v.swizzle = 0x05020202;
|
|
RgfxCreated tv = ser.createTextureView(v);
|
|
CHECK(tv.posted && tv.resource_id != 0 && tv.resource_id != tb.resource_id);
|
|
auto tvm = expectMessage<RgfxTextureView>(ring, RGFX_CMD_TEXTURE_VIEW);
|
|
CHECK(tvm.obj_id == tv.obj_id && tvm.resource_id == tv.resource_id);
|
|
CHECK(tvm.parent_obj_id == tb.obj_id && tvm.pixel_format == 81 && tvm.flags == 3);
|
|
CHECK(tvm.texture_type == 2 && tvm.level_count == 1 && tvm.slice_count == 1);
|
|
CHECK(tvm.swizzle == 0x05020202);
|
|
|
|
// Sampler: the float clamps are stored as bits.
|
|
RgfxSamplerParams sp = {};
|
|
sp.min_filter = 1;
|
|
sp.mag_filter = 1;
|
|
sp.mip_filter = 1;
|
|
sp.max_anisotropy = 4;
|
|
sp.lod_min_clamp = 0.0f;
|
|
sp.lod_max_clamp = 7.5f;
|
|
sp.flags = 0x1;
|
|
RgfxCreated s = ser.createSampler(sp);
|
|
CHECK(s.posted);
|
|
auto sm = expectMessage<RgfxSamplerCreate>(ring, RGFX_CMD_SAMPLER_CREATE);
|
|
CHECK(sm.obj_id == s.obj_id && sm.max_anisotropy == 4 && sm.flags == 0x1);
|
|
float lodMax;
|
|
std::memcpy(&lodMax, &sm.lod_max_clamp_bits, 4);
|
|
CHECK(lodMax == 7.5f);
|
|
|
|
// Depth/stencil.
|
|
RgfxStencilDescriptor front = {};
|
|
front.stencil_compare = 7;
|
|
front.read_mask = 0xff;
|
|
front.write_mask = 0xff;
|
|
RgfxStencilDescriptor back = {};
|
|
RgfxCreated ds = ser.createDepthStencil(4 /*compare*/, true, front, back);
|
|
CHECK(ds.posted);
|
|
auto dsm = expectMessage<RgfxDepthStencilCreate>(ring, RGFX_CMD_DEPTH_STENCIL_CREATE);
|
|
CHECK(dsm.obj_id == ds.obj_id && dsm.depth_compare == 4 && dsm.depth_write_enabled == 1);
|
|
CHECK(dsm.front.stencil_compare == 7 && dsm.front.read_mask == 0xff);
|
|
|
|
// Sync objects.
|
|
RgfxCreated ev = ser.createEvent();
|
|
CHECK(ev.posted);
|
|
auto evm = expectMessage<RgfxObjectCreate>(ring, RGFX_CMD_EVENT_CREATE);
|
|
CHECK(evm.obj_id == ev.obj_id);
|
|
|
|
RgfxCreated fe = ser.createFence();
|
|
CHECK(fe.posted);
|
|
auto fem = expectMessage<RgfxObjectCreate>(ring, RGFX_CMD_FENCE_CREATE);
|
|
CHECK(fem.obj_id == fe.obj_id);
|
|
|
|
RgfxCreated se = ser.createSharedEvent(42);
|
|
CHECK(se.posted);
|
|
auto sem = expectMessage<RgfxSharedEventCreate>(ring, RGFX_CMD_SHARED_EVENT_CREATE);
|
|
CHECK(sem.obj_id == se.obj_id && sem.initial_value == 42);
|
|
|
|
// Destroy carries the id alone.
|
|
CHECK(ser.destroy(b.obj_id));
|
|
auto dm = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
|
|
CHECK(dm.obj_id == b.obj_id);
|
|
|
|
// The ring is now drained and every post rang the idle host's doorbell.
|
|
RgfxMsgHeader spare = {};
|
|
std::vector<uint8_t> none;
|
|
CHECK(!ring.next(&spare, &none));
|
|
CHECK(TestRing::doorbells.load() > before);
|
|
}
|
|
|
|
void test_library_message()
|
|
{
|
|
TestRing ring(0x8000);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, nullptr, nullptr);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
|
|
const uint8_t air[6] = { 1, 2, 3, 4, 5, 6 };
|
|
RgfxCreated lib = ser.createLibrary(air, sizeof(air));
|
|
CHECK(lib.posted);
|
|
|
|
RgfxMsgHeader h = {};
|
|
std::vector<uint8_t> bytes;
|
|
CHECK(ring.next(&h, &bytes));
|
|
CHECK(h.type == RGFX_CMD_LIBRARY_CREATE);
|
|
// header struct (72) + 6 bytes, rounded up to a multiple of 8 = 80.
|
|
CHECK(h.size == 80);
|
|
RgfxLibraryCreate head;
|
|
std::memcpy(&head, bytes.data(), sizeof(head));
|
|
CHECK(head.obj_id == lib.obj_id && head.byte_length == 6);
|
|
CHECK(head.flags == 0); // no key
|
|
// A ring the process writes itself hands back no answer.
|
|
CHECK(lib.status == kRgfxNoAnswer);
|
|
CHECK(std::memcmp(bytes.data() + RGFX_LIBRARY_BYTES_OFFSET, air, sizeof(air)) == 0);
|
|
|
|
// A library larger than the ring cannot be posted in one message.
|
|
std::vector<uint8_t> huge(ring.dataSize, 0xcc);
|
|
RgfxCreated big = ser.createLibrary(huge.data(), huge.size());
|
|
CHECK(!big.posted);
|
|
}
|
|
|
|
void test_pipeline_messages()
|
|
{
|
|
TestRing ring(0x8000);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, nullptr, nullptr);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
|
|
// A render pipeline: two function names, a label, one colour attachment with
|
|
// source-over blend, and a one-entry vertex descriptor, all in the tail.
|
|
RgfxRenderPipelineParams rp = {};
|
|
rp.vertex.library = 10;
|
|
rp.vertex.entry_point = "vmain";
|
|
rp.fragment.library = 10;
|
|
rp.fragment.entry_point = "frag_main";
|
|
rp.label = "pipe";
|
|
rp.raster_sample_count = 1;
|
|
rp.color_attachment_count = 1;
|
|
rp.colors[0].pixel_format = 80; // BGRA8Unorm
|
|
rp.colors[0].blending_enabled = 1;
|
|
rp.colors[0].source_rgb_blend_factor = 1; // One
|
|
rp.colors[0].destination_rgb_blend_factor = 5; // OneMinusSourceAlpha
|
|
rp.colors[0].write_mask = 0xf;
|
|
rp.depth_pixel_format = 252; // Depth32Float
|
|
RgfxVertexBufferLayout layout = {};
|
|
layout.buffer_index = 0;
|
|
layout.stride = 32;
|
|
layout.step_function = 1;
|
|
rp.vertex_layouts = &layout;
|
|
rp.vertex_layout_count = 1;
|
|
RgfxVertexAttribute attr = {};
|
|
attr.format = 29; // Float4
|
|
rp.vertex_attributes = &attr;
|
|
rp.vertex_attribute_count = 1;
|
|
rp.flags = RGFX_RENDER_PIPELINE_RASTERIZATION_ENABLED;
|
|
|
|
RgfxCreated r = ser.createRenderPipeline(rp);
|
|
CHECK(r.posted);
|
|
|
|
RgfxMsgHeader h = {};
|
|
std::vector<uint8_t> bytes;
|
|
CHECK(ring.next(&h, &bytes));
|
|
CHECK(h.type == RGFX_CMD_RENDER_PIPELINE_CREATE);
|
|
CHECK(h.size == bytes.size());
|
|
CHECK(h.size % 8 == 0);
|
|
RgfxRenderPipelineCreate rc;
|
|
std::memcpy(&rc, bytes.data(), sizeof(rc));
|
|
CHECK(rc.obj_id == r.obj_id);
|
|
CHECK(rc.vertex_library_obj_id == 10 && rc.fragment_library_obj_id == 10);
|
|
CHECK(rc.color_attachment_count == 1 && rc.colors[0].pixel_format == 80);
|
|
CHECK(rc.colors[0].destination_rgb_blend_factor == 5);
|
|
CHECK(rc.depth_pixel_format == 252);
|
|
CHECK(rc.vertex_layout_count == 1 && rc.vertex_attribute_count == 1);
|
|
CHECK(rc.vertex_name_len == 5);
|
|
CHECK(std::memcmp(bytes.data() + rc.vertex_name_offset, "vmain", 5) == 0);
|
|
CHECK(rc.fragment_name_len == 9);
|
|
CHECK(std::memcmp(bytes.data() + rc.fragment_name_offset, "frag_main", 9) == 0);
|
|
CHECK(rc.label_len == 4);
|
|
CHECK(std::memcmp(bytes.data() + rc.label_offset, "pipe", 4) == 0);
|
|
RgfxVertexBufferLayout gotLayout;
|
|
std::memcpy(&gotLayout, bytes.data() + rc.vertex_layouts_offset, sizeof(gotLayout));
|
|
CHECK(gotLayout.stride == 32 && gotLayout.step_function == 1);
|
|
RgfxVertexAttribute gotAttr;
|
|
std::memcpy(&gotAttr, bytes.data() + rc.vertex_attributes_offset, sizeof(gotAttr));
|
|
CHECK(gotAttr.format == 29);
|
|
|
|
// A compute pipeline specialised by one function constant.
|
|
RgfxFunctionConstant k = {};
|
|
k.index = 2;
|
|
k.data_type = 84; // Long4, the widest
|
|
for (size_t i = 0; i < sizeof(k.value); i++)
|
|
k.value[i] = static_cast<uint8_t>(i + 1);
|
|
RgfxComputePipelineParams cp = {};
|
|
cp.function.library = 10;
|
|
cp.function.entry_point = "cmain";
|
|
cp.function.constants = &k;
|
|
cp.function.constant_count = 1;
|
|
cp.max_total_threads_per_threadgroup = 256;
|
|
cp.flags = RGFX_COMPUTE_PIPELINE_SUPPORT_ICB;
|
|
|
|
RgfxCreated c = ser.createComputePipeline(cp);
|
|
CHECK(c.posted);
|
|
CHECK(ring.next(&h, &bytes));
|
|
CHECK(h.type == RGFX_CMD_COMPUTE_PIPELINE_CREATE);
|
|
CHECK(h.size == bytes.size());
|
|
RgfxComputePipelineCreate cc;
|
|
std::memcpy(&cc, bytes.data(), sizeof(cc));
|
|
CHECK(cc.obj_id == c.obj_id && cc.function_library_obj_id == 10);
|
|
CHECK(cc.name_len == 5);
|
|
CHECK(std::memcmp(bytes.data() + cc.name_offset, "cmain", 5) == 0);
|
|
CHECK(cc.constant_count == 1);
|
|
RgfxFunctionConstant gotK;
|
|
std::memcpy(&gotK, bytes.data() + cc.constants_offset, sizeof(gotK));
|
|
CHECK(gotK.index == 2 && gotK.data_type == 84);
|
|
CHECK(std::memcmp(gotK.value, k.value, sizeof(k.value)) == 0);
|
|
CHECK(cc.max_total_threads_per_threadgroup == 256);
|
|
|
|
// The host's reflection reply, matched to the create by its seqno: built as
|
|
// the host would and read back, asserting the reply layout the guest reads.
|
|
RgfxPipelineReflection refl = {};
|
|
refl.header.type = RGFX_EVT_PIPELINE_REFLECTION;
|
|
refl.header.size = sizeof(refl);
|
|
refl.header.seqno = c.seqno;
|
|
refl.obj_id = c.obj_id;
|
|
refl.status = RGFX_PIPELINE_OK;
|
|
refl.kind = RGFX_PIPELINE_KIND_COMPUTE;
|
|
refl.max_total_threads_per_threadgroup = 1024;
|
|
refl.thread_execution_width = 32;
|
|
std::vector<uint8_t> wire(sizeof(refl), 0);
|
|
std::memcpy(wire.data(), &refl, sizeof(refl));
|
|
RgfxPipelineReflection back;
|
|
std::memcpy(&back, wire.data(), sizeof(back));
|
|
CHECK(back.header.seqno == c.seqno && back.obj_id == c.obj_id);
|
|
CHECK(back.status == RGFX_PIPELINE_OK && back.kind == RGFX_PIPELINE_KIND_COMPUTE);
|
|
CHECK(back.thread_execution_width == 32);
|
|
}
|
|
|
|
void test_ring_wrap_and_no_room()
|
|
{
|
|
// A small ring so a message must pad to the end and wrap.
|
|
const uint32_t kData = 256;
|
|
TestRing ring(kData);
|
|
RgfxRingWriter writer(ring.base(), kData, RGFX_CONTROL_RING_ID, nullptr, nullptr);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
|
|
// Each OBJECT_DESTROY is 24 bytes. Post and drain to push the producer near
|
|
// the ring's end, then post one that must pad over the tail.
|
|
for (int i = 0; i < 10; i++) {
|
|
CHECK(ser.destroy(100 + i));
|
|
auto m = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
|
|
CHECK(m.obj_id == static_cast<uint64_t>(100 + i));
|
|
}
|
|
// 10 * 24 = 240; 16 bytes to the end. The next 24-byte message pads and wraps.
|
|
CHECK(ser.destroy(999));
|
|
auto wrapped = expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY);
|
|
CHECK(wrapped.obj_id == 999);
|
|
|
|
// Fill the ring without draining until a post finds no room.
|
|
TestRing full(kData);
|
|
RgfxRingWriter fw(full.base(), kData, RGFX_CONTROL_RING_ID, nullptr, nullptr);
|
|
RgfxIdSpace fids;
|
|
RgfxSerializer fser(fw, fids);
|
|
int posted = 0;
|
|
bool hitNoRoom = false;
|
|
for (int i = 0; i < 100; i++) {
|
|
if (fser.destroy(i)) {
|
|
posted++;
|
|
} else {
|
|
hitNoRoom = true;
|
|
break;
|
|
}
|
|
}
|
|
CHECK(hitNoRoom);
|
|
CHECK(posted == static_cast<int>(kData / sizeof(RgfxObjectDestroy))); // 256/24 = 10
|
|
}
|
|
|
|
// A minimal host-side op-stream consumer, the mirror of
|
|
// crates/reims-vgpu/src/graphics/decode/cmdbuf.rs's walk: it reads each
|
|
// RgfxOpHeader, checks `len`, splits the body, and tracks which encoder is open.
|
|
struct OpWalk {
|
|
const uint8_t *ops;
|
|
size_t size; // op_bytes
|
|
size_t pos = 0;
|
|
|
|
OpWalk(const uint8_t *p, size_t n) : ops(p), size(n) {}
|
|
|
|
bool done() const { return pos >= size; }
|
|
|
|
// Reads the next op; fills `tag`, `flags`, `len` and points `body`/`body_len`
|
|
// at its body. Returns false (and does not advance) on a structural fault.
|
|
bool next(uint16_t *tag, uint16_t *flags, uint32_t *len, const uint8_t **body,
|
|
size_t *body_len)
|
|
{
|
|
if (size - pos < sizeof(RgfxOpHeader))
|
|
return false;
|
|
RgfxOpHeader h;
|
|
std::memcpy(&h, ops + pos, sizeof(h));
|
|
if (h.len < RGFX_OP_BODY_OFFSET || (h.len % 8) != 0 || h.len > size - pos)
|
|
return false;
|
|
*tag = h.tag;
|
|
*flags = h.flags;
|
|
*len = h.len;
|
|
*body = ops + pos + RGFX_OP_BODY_OFFSET;
|
|
*body_len = h.len - RGFX_OP_BODY_OFFSET;
|
|
pos += h.len;
|
|
return true;
|
|
}
|
|
};
|
|
|
|
// `tag >> 12`, the op's group, as the host splits it.
|
|
uint16_t opGroup(uint16_t tag) { return static_cast<uint16_t>(tag >> 12); }
|
|
|
|
// post() waits while the ring is full, ringing the doorbell and calling its hook, until the
|
|
// host takes room; a message over half the ring does not fit() and is refused at once; and
|
|
// beforePublish sees the seqno before `producer` moves.
|
|
void test_ring_post_waits_for_room()
|
|
{
|
|
constexpr uint32_t kData = 0x1000;
|
|
TestRing ring(kData);
|
|
RgfxRingWriter writer(ring.base(), kData, 1, TestRing::doorbell, nullptr);
|
|
CHECK(writer.fits(kData / 2));
|
|
CHECK(!writer.fits(kData / 2 + 8));
|
|
CHECK(!writer.fits(12));
|
|
std::vector<uint8_t> big(kData / 2 + 8, 0);
|
|
CHECK(!writer.post(RGFX_CMD_COMMAND_BUFFER, big.data(), static_cast<uint32_t>(big.size()),
|
|
nullptr));
|
|
CHECK(ring.producer() == 0);
|
|
|
|
uint8_t msg[256] = {};
|
|
int filled = 0;
|
|
while (writer.tryPost(RGFX_CMD_COMMAND_BUFFER, msg, sizeof(msg), nullptr))
|
|
filled++;
|
|
CHECK(filled == kData / 256);
|
|
uint64_t full = ring.producer();
|
|
int before = TestRing::doorbells.load();
|
|
|
|
// The host takes everything 20 ms from now.
|
|
std::thread host([&ring, full] {
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
|
__atomic_store_n(reinterpret_cast<uint64_t *>(ring.mem.data() +
|
|
__builtin_offsetof(RgfxRingHeader, consumer)),
|
|
full, __ATOMIC_RELEASE);
|
|
});
|
|
std::atomic<int> waits{0};
|
|
uint64_t seen = 0, producerAtPublish = ~0ull, seqno = 0;
|
|
auto start = std::chrono::steady_clock::now();
|
|
CHECK(writer.post(RGFX_CMD_COMMAND_BUFFER, msg, sizeof(msg), &seqno, [&] { waits++; },
|
|
[&](uint64_t s) {
|
|
seen = s;
|
|
producerAtPublish = ring.producer();
|
|
}));
|
|
auto took = std::chrono::steady_clock::now() - start;
|
|
host.join();
|
|
CHECK(took >= std::chrono::milliseconds(15));
|
|
CHECK(waits.load() >= 1);
|
|
CHECK(TestRing::doorbells.load() > before); // rung while it waited
|
|
CHECK(seen == seqno && seqno == static_cast<uint64_t>(filled) + 1);
|
|
CHECK(producerAtPublish == full); // seen before the message was published
|
|
CHECK(ring.producer() == full + sizeof(msg));
|
|
}
|
|
|
|
void test_command_buffer_encoder()
|
|
{
|
|
TestRing ring(0x8000);
|
|
ring.setConsumerIdle(1);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
|
|
nullptr);
|
|
|
|
RgfxEncoder enc(writer, /*queue*/ 1, /*cb*/ 100);
|
|
|
|
// Render encoder: a pass with one colour attachment, then a scalar op, an
|
|
// array-tailed op (setVertexBuffers), a no-arg op (setDepthCleared) and a draw.
|
|
RgfxRenderPassDesc pass = {};
|
|
pass.flags = RGFX_PASS_FLAG_RT_SIZE;
|
|
pass.render_target_width = 1920;
|
|
pass.render_target_height = 1080;
|
|
RgfxRenderPassColorAttachment color = {};
|
|
color.texture_obj_id = 4;
|
|
color.load_action = 2; // Clear
|
|
color.store_action = 1; // Store
|
|
double one = 1.0;
|
|
std::memcpy(&color.clear_color_bits[3], &one, 8);
|
|
enc.beginRenderPass(pass, &color, 1);
|
|
enc.renderSetRenderPipelineState(7);
|
|
enc.renderSetVertexBuffer(2, 0, 0);
|
|
enc.renderSetViewport(0.0, 0.0, 1920.0, 1080.0, 0.0, 1.0);
|
|
RgfxBufferBinding vbs[2] = {};
|
|
vbs[0].buffer_obj_id = 2;
|
|
vbs[0].offset = 0;
|
|
vbs[1].buffer_obj_id = 3;
|
|
vbs[1].offset = 256;
|
|
enc.renderSetVertexBuffers(0, vbs, 2);
|
|
enc.renderSetDepthCleared();
|
|
enc.renderDrawPrimitives(3, 0, 3);
|
|
enc.endEncoder();
|
|
|
|
// Compute encoder: default pass, a scalar, a dispatch, an array-tailed op and a
|
|
// no-body op.
|
|
enc.beginComputePass();
|
|
enc.computeSetComputePipelineState(8);
|
|
enc.computeDispatchThreadgroups(16, 8, 1, 32, 1, 1);
|
|
RgfxComputeBufferBinding cbs[2] = {};
|
|
cbs[0].buffer_obj_id = 2;
|
|
cbs[0].offset = 0;
|
|
cbs[1].buffer_obj_id = 3;
|
|
cbs[1].offset = 512;
|
|
enc.computeSetBuffers(0, cbs, 2);
|
|
enc.computeEncodeStartElse();
|
|
enc.endEncoder();
|
|
|
|
// Blit encoder: a copy, a fill-texture (trailing bytes), and a fence wait.
|
|
enc.beginBlitPass();
|
|
enc.blitCopyBufferToBuffer(2, 3, 16, 32, 4096);
|
|
const uint8_t fill[5] = { 0xde, 0xad, 0xbe, 0xef, 0x01 };
|
|
enc.blitFillTexture(4, 0, 0, 0, 0, 0, 32, 32, 1, fill, sizeof(fill));
|
|
enc.blitWaitForFence(9);
|
|
enc.endEncoder();
|
|
|
|
uint64_t seqno = 0;
|
|
CHECK(enc.finish(&seqno));
|
|
CHECK(seqno == 1);
|
|
|
|
// Read the command-buffer message back off the ring and check its framing.
|
|
RgfxMsgHeader h = {};
|
|
std::vector<uint8_t> bytes;
|
|
CHECK(ring.next(&h, &bytes));
|
|
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER);
|
|
CHECK(h.size == bytes.size());
|
|
CHECK(h.size % 8 == 0);
|
|
CHECK(h.seqno == 1);
|
|
|
|
RgfxCommandBuffer cb = {};
|
|
std::memcpy(&cb, bytes.data(), sizeof(cb));
|
|
CHECK(cb.queue_obj_id == 1);
|
|
CHECK(cb.cb_obj_id == 100);
|
|
CHECK(cb.op_bytes == bytes.size() - RGFX_COMMAND_BUFFER_OPS_OFFSET);
|
|
CHECK(cb.op_bytes == enc.opBytes());
|
|
|
|
// The op stream follows the header at RGFX_COMMAND_BUFFER_OPS_OFFSET.
|
|
OpWalk walk(bytes.data() + RGFX_COMMAND_BUFFER_OPS_OFFSET, cb.op_bytes);
|
|
|
|
// The exact op sequence the encoder wrote.
|
|
const uint16_t want[] = {
|
|
RGFX_OP_ENCODER_BEGIN_RENDER,
|
|
RGFX_OP_RENDER_SET_RENDER_PIPELINE_STATE,
|
|
RGFX_OP_RENDER_SET_VERTEX_BUFFER,
|
|
RGFX_OP_RENDER_SET_VIEWPORT,
|
|
RGFX_OP_RENDER_SET_VERTEX_BUFFERS,
|
|
RGFX_OP_RENDER_SET_DEPTH_CLEARED,
|
|
RGFX_OP_RENDER_DRAW_PRIMITIVES,
|
|
RGFX_OP_ENCODER_END,
|
|
RGFX_OP_ENCODER_BEGIN_COMPUTE,
|
|
RGFX_OP_COMPUTE_SET_COMPUTE_PIPELINE_STATE,
|
|
RGFX_OP_COMPUTE_DISPATCH_THREADGROUPS,
|
|
RGFX_OP_COMPUTE_SET_BUFFERS,
|
|
RGFX_OP_COMPUTE_ENCODE_START_ELSE,
|
|
RGFX_OP_ENCODER_END,
|
|
RGFX_OP_ENCODER_BEGIN_BLIT,
|
|
RGFX_OP_BLIT_COPY_BUFFER_TO_BUFFER,
|
|
RGFX_OP_BLIT_FILL_TEXTURE,
|
|
RGFX_OP_BLIT_WAIT_FOR_FENCE,
|
|
RGFX_OP_ENCODER_END,
|
|
};
|
|
const size_t want_n = sizeof(want) / sizeof(want[0]);
|
|
|
|
int open = 0; // 0 none, 1 render, 2 compute, 3 blit
|
|
int begins = 0, ends = 0;
|
|
size_t i = 0;
|
|
while (!walk.done()) {
|
|
uint16_t tag = 0, flags = 0;
|
|
uint32_t len = 0;
|
|
const uint8_t *body = nullptr;
|
|
size_t body_len = 0;
|
|
CHECK(walk.next(&tag, &flags, &len, &body, &body_len));
|
|
CHECK(len % 8 == 0);
|
|
CHECK(i < want_n);
|
|
CHECK(tag == want[i]);
|
|
|
|
// Framing is balanced: a begin opens exactly one encoder, an end closes it,
|
|
// and every body op's group matches the open encoder.
|
|
if (opGroup(tag) == RGFX_OP_GROUP_FRAMING) {
|
|
if (tag == RGFX_OP_ENCODER_BEGIN_RENDER) {
|
|
CHECK(open == 0);
|
|
open = 1;
|
|
begins++;
|
|
} else if (tag == RGFX_OP_ENCODER_BEGIN_COMPUTE) {
|
|
CHECK(open == 0);
|
|
open = 2;
|
|
begins++;
|
|
} else if (tag == RGFX_OP_ENCODER_BEGIN_BLIT) {
|
|
CHECK(open == 0);
|
|
open = 3;
|
|
begins++;
|
|
} else if (tag == RGFX_OP_ENCODER_END) {
|
|
CHECK(open != 0);
|
|
open = 0;
|
|
ends++;
|
|
}
|
|
} else {
|
|
CHECK(static_cast<int>(opGroup(tag)) == open);
|
|
}
|
|
|
|
// Spot-check the bodies of representative ops across all three encoders.
|
|
if (tag == RGFX_OP_ENCODER_BEGIN_RENDER) {
|
|
CHECK(len == 8 + sizeof(RgfxRenderPassDesc) + 1 * sizeof(RgfxRenderPassColorAttachment));
|
|
RgfxRenderPassDesc gotPass;
|
|
std::memcpy(&gotPass, body, sizeof(gotPass));
|
|
CHECK(gotPass.color_count == 1);
|
|
CHECK(gotPass.flags == RGFX_PASS_FLAG_RT_SIZE);
|
|
CHECK(gotPass.render_target_width == 1920 && gotPass.render_target_height == 1080);
|
|
RgfxRenderPassColorAttachment gotColor;
|
|
std::memcpy(&gotColor, body + RGFX_RENDER_PASS_COLOR_OFFSET, sizeof(gotColor));
|
|
CHECK(gotColor.texture_obj_id == 4);
|
|
CHECK(gotColor.load_action == 2 && gotColor.store_action == 1);
|
|
double a;
|
|
std::memcpy(&a, &gotColor.clear_color_bits[3], 8);
|
|
CHECK(a == 1.0);
|
|
} else if (tag == RGFX_OP_RENDER_SET_VERTEX_BUFFER) {
|
|
RgfxOpSetVertexBuffer b;
|
|
std::memcpy(&b, body, sizeof(b));
|
|
CHECK(b.buffer_obj_id == 2 && b.offset == 0 && b.index == 0);
|
|
} else if (tag == RGFX_OP_RENDER_SET_VERTEX_BUFFERS) {
|
|
// Array-tailed: head's range then two RgfxBufferBinding records.
|
|
CHECK(len == 8 + sizeof(RgfxOpSetVertexBuffers) + 2 * sizeof(RgfxBufferBinding));
|
|
RgfxOpSetVertexBuffers head;
|
|
std::memcpy(&head, body, sizeof(head));
|
|
CHECK(head.range_location == 0 && head.range_length == 2);
|
|
RgfxBufferBinding e0, e1;
|
|
std::memcpy(&e0, body + sizeof(head), sizeof(e0));
|
|
std::memcpy(&e1, body + sizeof(head) + sizeof(e0), sizeof(e1));
|
|
CHECK(e0.buffer_obj_id == 2 && e0.offset == 0);
|
|
CHECK(e1.buffer_obj_id == 3 && e1.offset == 256);
|
|
} else if (tag == RGFX_OP_RENDER_SET_DEPTH_CLEARED) {
|
|
CHECK(len == 8 && body_len == 0); // no-arg render op: header only
|
|
} else if (tag == RGFX_OP_RENDER_DRAW_PRIMITIVES) {
|
|
RgfxOpDrawPrimitives b;
|
|
std::memcpy(&b, body, sizeof(b));
|
|
CHECK(b.primitive_type == 3 && b.vertex_start == 0 && b.vertex_count == 3);
|
|
} else if (tag == RGFX_OP_ENCODER_BEGIN_COMPUTE) {
|
|
CHECK(len == 8 && body_len == 0); // default pass: empty body
|
|
} else if (tag == RGFX_OP_COMPUTE_DISPATCH_THREADGROUPS) {
|
|
RgfxComputeOpDispatchThreadgroups b;
|
|
std::memcpy(&b, body, sizeof(b));
|
|
CHECK(b.threadgroups_width == 16 && b.threadgroups_height == 8);
|
|
CHECK(b.threads_width == 32 && b.threads_height == 1 && b.threads_depth == 1);
|
|
} else if (tag == RGFX_OP_COMPUTE_SET_BUFFERS) {
|
|
CHECK(len == 8 + sizeof(RgfxComputeOpSetBuffers) +
|
|
2 * sizeof(RgfxComputeBufferBinding));
|
|
RgfxComputeOpSetBuffers head;
|
|
std::memcpy(&head, body, sizeof(head));
|
|
CHECK(head.location == 0 && head.length == 2);
|
|
RgfxComputeBufferBinding e1;
|
|
std::memcpy(&e1, body + sizeof(head) + sizeof(e1), sizeof(e1));
|
|
CHECK(e1.buffer_obj_id == 3 && e1.offset == 512);
|
|
} else if (tag == RGFX_OP_COMPUTE_ENCODE_START_ELSE) {
|
|
CHECK(len == 8 && body_len == 0); // no-body compute op
|
|
} else if (tag == RGFX_OP_BLIT_COPY_BUFFER_TO_BUFFER) {
|
|
RgfxBlitOpCopyBufferToBuffer b;
|
|
std::memcpy(&b, body, sizeof(b));
|
|
CHECK(b.source_buffer_obj_id == 2 && b.destination_buffer_obj_id == 3);
|
|
CHECK(b.source_offset == 16 && b.destination_offset == 32 && b.size == 4096);
|
|
} else if (tag == RGFX_OP_BLIT_FILL_TEXTURE) {
|
|
// Head then `length` fill bytes at offset 80, padded to a multiple of 8.
|
|
CHECK(len == 8 + 88); // 80-byte head + 5 fill bytes padded to 88
|
|
RgfxBlitOpFillTexture head;
|
|
std::memcpy(&head, body, sizeof(head));
|
|
CHECK(head.texture_obj_id == 4 && head.length == 5);
|
|
CHECK(head.region_size_width == 32 && head.region_size_height == 32);
|
|
const uint8_t expect[5] = { 0xde, 0xad, 0xbe, 0xef, 0x01 };
|
|
CHECK(std::memcmp(body + RGFX_OP_BLIT_FILL_TEXTURE_BYTES_OFFSET, expect, 5) == 0);
|
|
} else if (tag == RGFX_OP_BLIT_WAIT_FOR_FENCE) {
|
|
RgfxBlitOpWaitForFence b;
|
|
std::memcpy(&b, body, sizeof(b));
|
|
CHECK(b.fence_obj_id == 9);
|
|
}
|
|
i++;
|
|
}
|
|
|
|
// The whole stream was consumed: the tag sequence matched and the framing is
|
|
// balanced (three encoders opened and closed).
|
|
CHECK(i == want_n);
|
|
CHECK(open == 0);
|
|
CHECK(begins == 3 && ends == 3);
|
|
|
|
// op_bytes is the stream the walk consumed, 8-aligned.
|
|
CHECK(walk.pos == cb.op_bytes);
|
|
CHECK(cb.op_bytes % 8 == 0);
|
|
}
|
|
|
|
} // namespace
|
|
|
|
// A forwarding writer hands each whole message, its type and size stamped, to its forward,
|
|
// whose seqno it returns; a refusal posts nothing. A reflection the kext hands back before its
|
|
// wrapper registers is kept for the registration.
|
|
struct ForwardLog {
|
|
std::vector<std::vector<uint8_t>> messages;
|
|
bool refuse = false;
|
|
uint64_t nextSeqno = 41;
|
|
uint32_t answer = kRgfxNoAnswer; // the COMPLETE status the "kext" hands back
|
|
};
|
|
|
|
bool forwardTo(void *context, const void *message, uint32_t size, uint64_t *out_seqno,
|
|
uint32_t *out_status)
|
|
{
|
|
ForwardLog *log = static_cast<ForwardLog *>(context);
|
|
if (log->refuse)
|
|
return false;
|
|
const uint8_t *b = static_cast<const uint8_t *>(message);
|
|
log->messages.emplace_back(b, b + size);
|
|
*out_seqno = log->nextSeqno++;
|
|
if (out_status)
|
|
*out_status = log->answer;
|
|
return true;
|
|
}
|
|
|
|
void test_forwarded_lifecycle()
|
|
{
|
|
ForwardLog log;
|
|
RgfxRingWriter writer(&forwardTo, &log, 4096);
|
|
CHECK(writer.dataSize() == 4096);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
RgfxCreated ev = ser.createEvent();
|
|
CHECK(ev.posted);
|
|
CHECK(ev.seqno == 41);
|
|
CHECK(log.messages.size() == 1);
|
|
RgfxObjectCreate m = {};
|
|
std::memcpy(&m, log.messages[0].data(), sizeof(m));
|
|
CHECK(m.header.type == RGFX_CMD_EVENT_CREATE);
|
|
CHECK(m.header.size == sizeof(RgfxObjectCreate));
|
|
CHECK(m.header.seqno == 0); // the kext stamps it
|
|
CHECK(m.obj_id == ev.obj_id);
|
|
log.refuse = true;
|
|
CHECK(!ser.createEvent().posted);
|
|
CHECK(log.messages.size() == 1);
|
|
// Too large for the forward: refused before it is handed over.
|
|
std::vector<uint8_t> big(8192, 0);
|
|
CHECK(!writer.tryPost(RGFX_CMD_LIBRARY_CREATE, big.data(), 8192, nullptr));
|
|
|
|
RgfxReplyReader reader;
|
|
CHECK(reader.pump() == 0);
|
|
RgfxPipelineReflection r = {};
|
|
r.header.type = RGFX_EVT_PIPELINE_REFLECTION;
|
|
r.header.size = sizeof(r);
|
|
r.header.seqno = 7;
|
|
r.obj_id = 99;
|
|
reader.deliver(&r, sizeof(r));
|
|
uint64_t got = 0;
|
|
reader.expectReflection(7, [&got](const RgfxPipelineReflection &m) { got = m.obj_id; });
|
|
CHECK(got == 99);
|
|
CHECK(!reader.awaitingReflection(7));
|
|
reader.expectReflection(8, [&got](const RgfxPipelineReflection &m) { got = m.obj_id + 1; });
|
|
CHECK(reader.awaitingReflection(8));
|
|
r.header.seqno = 8;
|
|
reader.deliver(&r, sizeof(r));
|
|
CHECK(got == 100);
|
|
CHECK(!reader.awaitingReflection(8));
|
|
}
|
|
|
|
// A synthetic .metallib: its header (the bitcode section at 0x60, 16 bytes), a stand-in for the
|
|
// function list, the bitcode, and a tail.
|
|
std::vector<uint8_t> syntheticMetallib()
|
|
{
|
|
std::vector<uint8_t> b(0x58, 0);
|
|
std::memcpy(b.data(), "MTLB", 4);
|
|
const uint64_t at = 0x60, size = 0x10;
|
|
std::memcpy(b.data() + 0x48, &at, 8);
|
|
std::memcpy(b.data() + 0x50, &size, 8);
|
|
for (const char *part : { "funclist", "BITCODE-BITCODE!", "tail-end" })
|
|
b.insert(b.end(), part, part + std::strlen(part));
|
|
return b;
|
|
}
|
|
|
|
// A library's content key is the SHA-256 of the prefix and the bytes around the bitcode section:
|
|
// the digest computed independently (and pinned on the host's side too), the same whatever the
|
|
// section holds, and none for bytes that are no .metallib or whose section lies outside them.
|
|
void test_library_key()
|
|
{
|
|
static const uint8_t expect[32] = {
|
|
0xc0, 0x99, 0x93, 0x08, 0x93, 0xa6, 0x91, 0xa1, 0xaa, 0xed, 0xfa, 0x6d, 0xee, 0xd4, 0x1a, 0x58,
|
|
0x09, 0x95, 0x3e, 0x36, 0xa8, 0xe6, 0x9e, 0xd9, 0x86, 0xe1, 0xb2, 0x11, 0xff, 0x4e, 0x21, 0x7d,
|
|
};
|
|
std::vector<uint8_t> lib = syntheticMetallib();
|
|
CHECK(lib.size() == 0x78);
|
|
uint8_t key[32] = {};
|
|
CHECK(rgfxLibraryKey(lib.data(), lib.size(), key));
|
|
CHECK(std::memcmp(key, expect, sizeof(key)) == 0);
|
|
// The bitcode is not keyed (its HASH tags are); the bytes around it are.
|
|
lib[0x65] ^= 0xff;
|
|
CHECK(rgfxLibraryKey(lib.data(), lib.size(), key));
|
|
CHECK(std::memcmp(key, expect, sizeof(key)) == 0);
|
|
lib[0x75] ^= 0xff;
|
|
CHECK(rgfxLibraryKey(lib.data(), lib.size(), key));
|
|
CHECK(std::memcmp(key, expect, sizeof(key)) != 0);
|
|
// No key: not a .metallib, a section past the end, too short for a header.
|
|
std::vector<uint8_t> other = syntheticMetallib();
|
|
other[0] = 'X';
|
|
CHECK(!rgfxLibraryKey(other.data(), other.size(), key));
|
|
other = syntheticMetallib();
|
|
const uint64_t past = 0x70;
|
|
std::memcpy(other.data() + 0x50, &past, 8);
|
|
CHECK(!rgfxLibraryKey(other.data(), other.size(), key));
|
|
CHECK(!rgfxLibraryKey(other.data(), 0x40, key));
|
|
}
|
|
|
|
// Keyed library messages through the kext's route: the create carries its key and hands back the
|
|
// device's answer; a lookup is one LIBRARY_LOOKUP of its own, answered; a streamed library's
|
|
// chunks carry the key and its answer.
|
|
void test_keyed_library_messages()
|
|
{
|
|
ForwardLog log;
|
|
RgfxRingWriter writer(&forwardTo, &log, 4096);
|
|
RgfxIdSpace ids;
|
|
RgfxSerializer ser(writer, ids);
|
|
std::vector<uint8_t> lib = syntheticMetallib();
|
|
uint8_t key[32] = {};
|
|
CHECK(rgfxLibraryKey(lib.data(), lib.size(), key));
|
|
|
|
log.answer = RGFX_STATUS_NOT_FOUND;
|
|
RgfxCreated found = ser.lookupLibrary(key, lib.size());
|
|
CHECK(found.posted && found.status == RGFX_STATUS_NOT_FOUND);
|
|
CHECK(log.messages.size() == 1);
|
|
RgfxLibraryLookup lookup = {};
|
|
CHECK(log.messages[0].size() == sizeof(lookup));
|
|
std::memcpy(&lookup, log.messages[0].data(), sizeof(lookup));
|
|
CHECK(lookup.header.type == RGFX_CMD_LIBRARY_LOOKUP);
|
|
CHECK(lookup.header.size == sizeof(RgfxLibraryLookup));
|
|
CHECK(lookup.obj_id == found.obj_id);
|
|
CHECK(lookup.slice_size == lib.size());
|
|
CHECK(std::memcmp(lookup.key, key, 32) == 0);
|
|
|
|
log.answer = RGFX_STATUS_OK;
|
|
RgfxCreated made = ser.createLibrary(lib.data(), lib.size(), key);
|
|
CHECK(made.posted && made.status == RGFX_STATUS_OK);
|
|
RgfxLibraryCreate head = {};
|
|
std::memcpy(&head, log.messages[1].data(), sizeof(head));
|
|
CHECK(head.header.type == RGFX_CMD_LIBRARY_CREATE);
|
|
CHECK(head.flags == RGFX_LIBRARY_FLAG_KEYED);
|
|
CHECK(std::memcmp(head.key, key, 32) == 0);
|
|
CHECK(std::memcmp(log.messages[1].data() + RGFX_LIBRARY_BYTES_OFFSET, lib.data(), lib.size()) ==
|
|
0);
|
|
|
|
log.answer = RGFX_STATUS_REFUSED;
|
|
uint32_t status = 0;
|
|
CHECK(ser.postLibraryChunk(made.obj_id, 0x1000, 8, 8, 0, 0x2000, 1, key, &status));
|
|
CHECK(status == RGFX_STATUS_REFUSED);
|
|
RgfxLibraryFromRegion chunk = {};
|
|
std::memcpy(&chunk, log.messages[2].data(), sizeof(chunk));
|
|
CHECK(chunk.header.type == RGFX_CMD_LIBRARY_FROM_REGION);
|
|
CHECK(chunk.flags == RGFX_LIBRARY_FLAG_KEYED);
|
|
CHECK(std::memcmp(chunk.key, key, 32) == 0);
|
|
}
|
|
|
|
// The archive file: its sections round-trip, whatever does not parse whole is no archive, and a
|
|
// Metal archive is told by its fat header, every slice inside the file.
|
|
void test_archive_file()
|
|
{
|
|
RgfxArchiveKey k1(kRgfxArchiveCompute), k2(kRgfxArchiveCompute), k3(kRgfxArchiveVertex);
|
|
k1.text("a");
|
|
k2.text("b");
|
|
k3.text("a");
|
|
RgfxArchiveEntry a = k1.finish(), b = k2.finish(), v = k3.finish();
|
|
CHECK(!(a == b));
|
|
CHECK(!(a == v)); // the kind is part of the key
|
|
RgfxArchiveKey k4(kRgfxArchiveCompute);
|
|
k4.text("a");
|
|
CHECK(k4.finish() == a);
|
|
// A field's length goes in with it: "ab" then "" is not "a" then "b".
|
|
RgfxArchiveKey s1(kRgfxArchiveCompute), s2(kRgfxArchiveCompute);
|
|
s1.text("ab");
|
|
s1.text("");
|
|
s2.text("a");
|
|
s2.text("b");
|
|
CHECK(!(s1.finish() == s2.finish()));
|
|
|
|
std::vector<RgfxArchiveSection> in(2);
|
|
in[0].architecture = "vulkan_10de_2c58_00";
|
|
in[0].entries = {a, v};
|
|
in[1].architecture = "applegpu_g15s";
|
|
in[1].entries = {b};
|
|
std::vector<uint8_t> file = rgfxWriteArchiveFile(in);
|
|
std::vector<RgfxArchiveSection> out;
|
|
CHECK(rgfxReadArchiveFile(file.data(), file.size(), out) == RgfxArchiveFileKind::Ours);
|
|
CHECK(out.size() == 2);
|
|
CHECK(out[0].architecture == in[0].architecture && out[0].entries == in[0].entries);
|
|
CHECK(out[1].architecture == in[1].architecture && out[1].entries == in[1].entries);
|
|
CHECK(file.size() == 8 + 4 + (4 + 19 + 4 + 2 * 33) + (4 + 13 + 4 + 33));
|
|
|
|
for (size_t cut = 0; cut < file.size(); cut++)
|
|
CHECK(rgfxReadArchiveFile(file.data(), cut, out) == RgfxArchiveFileKind::Invalid);
|
|
std::vector<uint8_t> longer = file;
|
|
longer.push_back(0);
|
|
CHECK(rgfxReadArchiveFile(longer.data(), longer.size(), out) == RgfxArchiveFileKind::Invalid);
|
|
CHECK(out.empty());
|
|
std::vector<uint8_t> none = rgfxWriteArchiveFile({});
|
|
CHECK(rgfxReadArchiveFile(none.data(), none.size(), out) == RgfxArchiveFileKind::Ours);
|
|
CHECK(out.empty());
|
|
|
|
// One slice of 4 bytes at 28: a Metal archive; its slice past the end: no archive.
|
|
const uint8_t fat[] = {0xcb, 0xfe, 0xba, 0xbe, 0, 0, 0, 1, 1, 0, 0, 0x17, 0, 0, 0, 0xd,
|
|
0, 0, 0, 28, 0, 0, 0, 4, 0, 0, 0, 0, 1, 2, 3, 4};
|
|
CHECK(rgfxReadArchiveFile(fat, sizeof(fat), out) == RgfxArchiveFileKind::Metal);
|
|
CHECK(rgfxReadArchiveFile(fat, sizeof(fat) - 1, out) == RgfxArchiveFileKind::Invalid);
|
|
CHECK(rgfxReadArchiveFile(fat, 8, out) == RgfxArchiveFileKind::Invalid);
|
|
}
|
|
|
|
// An Automatic heap's placements, in the order Metal's took them (measured: M3 Max, macOS 27,
|
|
// a Private heap of 1000000 bytes, 1015808 once rounded): each at the lowest offset at its
|
|
// alignment where all its bytes are free, the sizes summed as used, the free bytes joined as
|
|
// they come back, and the longest free run from an aligned offset as the most available.
|
|
void test_heap_ranges()
|
|
{
|
|
RgfxHeapRanges r(1015808);
|
|
uint64_t at = 1;
|
|
CHECK(r.used() == 0 && r.maxAvailable(0) == 1015808 && r.maxAvailable(65536) == 1015808);
|
|
uint64_t b1 = 0, b2 = 0, b3 = 0, t1 = 0;
|
|
CHECK(r.take(100, 256, &b1) && b1 == 0);
|
|
CHECK(r.used() == 100 && r.maxAvailable(1) == 1015708 && r.maxAvailable(256) == 1015552);
|
|
CHECK(r.maxAvailable(4096) == 1011712 && r.maxAvailable(65536) == 950272);
|
|
CHECK(r.take(100, 256, &b2) && b2 == 256);
|
|
CHECK(r.take(70000, 256, &b3) && b3 == 512);
|
|
CHECK(r.used() == 70200 && r.maxAvailable(1) == 945296 && r.maxAvailable(256) == 945152);
|
|
CHECK(r.maxAvailable(4096) == 942080 && r.maxAvailable(65536) == 884736);
|
|
CHECK(r.take(264192, 128, &t1) && t1 == 70528);
|
|
CHECK(r.used() == 334392 && r.maxAvailable(1) == 681088 && r.maxAvailable(256) == 680960);
|
|
r.give(b1, 100);
|
|
CHECK(r.used() == 334292 && r.maxAvailable(1) == 681088);
|
|
uint64_t b4 = 0, b5 = 0, b7 = 0;
|
|
CHECK(r.take(50, 256, &b4) && b4 == 0);
|
|
r.give(b2, 100); // made aliasable
|
|
CHECK(r.take(60, 256, &b5) && b5 == 256);
|
|
CHECK(r.used() == 334302 && r.maxAvailable(256) == 680960);
|
|
CHECK(!r.take(680961, 256, &at) && at == 1);
|
|
CHECK(r.take(680960, 256, &b7) && b7 == 334848);
|
|
CHECK(r.used() == 1015262 && r.maxAvailable(1) == 206 && r.maxAvailable(256) == 0);
|
|
CHECK(!r.take(16, 256, &at));
|
|
// First fit, not best fit: with holes of 5000 and 1000 bytes in that order, 800 bytes go in
|
|
// the first (Metal's order of a 5000, 256, 1000 and 256-byte buffer, the first and third
|
|
// freed).
|
|
RgfxHeapRanges f(1 << 20);
|
|
uint64_t a = 0, b = 0, c = 0, d = 0, e = 0, g = 0, h = 0, i = 0;
|
|
CHECK(f.take(5000, 256, &a) && f.take(256, 256, &b) && f.take(1000, 256, &c) &&
|
|
f.take(256, 256, &d));
|
|
CHECK(a == 0 && b == 5120 && c == 5376 && d == 6400);
|
|
f.give(a, 5000);
|
|
f.give(c, 1000);
|
|
CHECK(f.take(800, 256, &e) && e == 0);
|
|
CHECK(f.take(3000, 256, &g) && g == 1024);
|
|
CHECK(f.take(3000, 256, &h) && h == 6656);
|
|
uint64_t k = 0;
|
|
CHECK(f.take(100, 256, &k) && k == 4096);
|
|
// B, E and F back: [0, 4096) and [4196, 6400) are free, neither holds 5500.
|
|
f.give(b, 256);
|
|
f.give(e, 800);
|
|
f.give(g, 3000);
|
|
CHECK(f.take(5500, 256, &i) && i == 9728);
|
|
CHECK(f.maxAvailable(1) == (1 << 20) - 15228 && f.take(16, 256, &at) && at == 0);
|
|
// Nothing for a size of 0, nor at an alignment that is not a power of two.
|
|
CHECK(!f.take(0, 256, &at) && !f.take(16, 3, &at) && f.maxAvailable(3) == 0);
|
|
RgfxHeapRanges none(0);
|
|
CHECK(!none.take(1, 1, &at) && none.maxAvailable(1) == 0);
|
|
}
|
|
|
|
// What a fake device answers a heap texture size query, and what it was asked.
|
|
struct SizeAsker {
|
|
RgfxHeapTextureSizeAndAlign asked = {};
|
|
uint32_t status = RGFX_STATUS_OK;
|
|
bool answers = true;
|
|
int calls = 0;
|
|
|
|
static bool ask(void *context, const void *message, uint32_t size, void *reply,
|
|
uint32_t capacity, uint32_t *reply_size)
|
|
{
|
|
SizeAsker *self = static_cast<SizeAsker *>(context);
|
|
self->calls++;
|
|
CHECK(size == sizeof(RgfxHeapTextureSizeAndAlign));
|
|
std::memcpy(&self->asked, message, sizeof(self->asked));
|
|
if (!self->answers)
|
|
return false;
|
|
RgfxSizeAndAlign answer = {};
|
|
answer.header = {RGFX_EVT_SIZE_AND_ALIGN, sizeof(answer), 9};
|
|
answer.status = self->status;
|
|
answer.size = self->status == RGFX_STATUS_OK ? 264192 : 0;
|
|
answer.align = self->status == RGFX_STATUS_OK ? 128 : 0;
|
|
CHECK(capacity >= sizeof(answer));
|
|
std::memcpy(reply, &answer, sizeof(answer));
|
|
*reply_size = sizeof(answer);
|
|
return true;
|
|
}
|
|
};
|
|
|
|
// A heap texture size query asks the device with the texture's shape under a new id of the
|
|
// context and posts nothing on the ring; it answers the device's size and alignment, and
|
|
// nothing where no asker is set, nothing came back, or the device refused the shape.
|
|
void test_heap_texture_size_query()
|
|
{
|
|
TestRing ring(0x4000);
|
|
ring.setConsumerIdle(1);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell,
|
|
nullptr);
|
|
RgfxIdSpace ids;
|
|
ids.setBases(2ull << RGFX_CONTEXT_OBJ_ID_SHIFT, RgfxIdSpace::kDefaultAddressBase);
|
|
RgfxSerializer ser(writer, ids);
|
|
RgfxTextureDescriptor desc = {};
|
|
desc.pixel_format = 70;
|
|
desc.texture_type = 2;
|
|
desc.width = 256;
|
|
desc.height = 256;
|
|
desc.depth = 1;
|
|
desc.mipmap_level_count = 1;
|
|
desc.array_length = 1;
|
|
desc.sample_count = 1;
|
|
uint64_t size = 1, align = 1;
|
|
CHECK(!ser.heapTextureSizeAndAlign(desc, &size, &align) && size == 1 && align == 1);
|
|
|
|
SizeAsker asker;
|
|
ser.setAsker(&SizeAsker::ask, &asker);
|
|
CHECK(ser.heapTextureSizeAndAlign(desc, &size, &align));
|
|
CHECK(size == 264192 && align == 128 && asker.calls == 1);
|
|
CHECK(asker.asked.header.type == RGFX_CMD_HEAP_TEXTURE_SIZE_AND_ALIGN);
|
|
CHECK(asker.asked.header.size == sizeof(RgfxHeapTextureSizeAndAlign));
|
|
CHECK(asker.asked.obj_id >> RGFX_CONTEXT_OBJ_ID_SHIFT == 2);
|
|
CHECK(std::memcmp(&asker.asked.desc, &desc, sizeof(desc)) == 0);
|
|
const uint64_t first = asker.asked.obj_id;
|
|
RgfxMsgHeader h = {};
|
|
std::vector<uint8_t> bytes;
|
|
CHECK(!ring.next(&h, &bytes));
|
|
|
|
asker.status = RGFX_STATUS_REFUSED;
|
|
size = align = 1;
|
|
CHECK(!ser.heapTextureSizeAndAlign(desc, &size, &align) && size == 1 && align == 1);
|
|
CHECK(asker.asked.obj_id != first);
|
|
asker.answers = false;
|
|
CHECK(!ser.heapTextureSizeAndAlign(desc, &size, &align) && asker.calls == 3);
|
|
}
|
|
|
|
// A no-copy buffer's block and the app's memory (RgfxMemoryShadow): the block starts as the
|
|
// memory; each sync moves the bytes one side changed since the two last agreed, byte by byte,
|
|
// so a CPU write and a GPU write beside it in one word both stand; memory mapped read-only is
|
|
// never written; the encoder's notes sync each shadow once and keep the ones written.
|
|
void test_memory_shadow()
|
|
{
|
|
CHECK(!RgfxMemoryShadow::anyLive());
|
|
const size_t n = 0x3003; // a tail past the last whole word and chunk
|
|
std::vector<uint8_t> app(n), block(n, 0xee);
|
|
for (size_t i = 0; i < n; i++)
|
|
app[i] = static_cast<uint8_t>(i * 7);
|
|
{
|
|
auto s = std::make_shared<RgfxMemoryShadow>(app.data(), block.data(), n, true);
|
|
CHECK(s->ok() && s->length() == n && s->writable() && RgfxMemoryShadow::anyLive());
|
|
CHECK(block == app);
|
|
|
|
// The CPU writes; the GPU writes elsewhere, before the commit's sync.
|
|
app[0x10] = 0xa1;
|
|
std::memset(&app[0x1000], 0xa2, 8); // a whole word
|
|
app[0x3002] = 0xa3; // the tail
|
|
block[0x2000] = 0xb1; // a GPU write not yet written back
|
|
block[0x400] = 0xb2;
|
|
app[0x401] = 0xa4; // beside it, in the same word
|
|
s->syncIn();
|
|
CHECK(block[0x10] == 0xa1 && block[0x1000] == 0xa2 && block[0x1007] == 0xa2);
|
|
CHECK(block[0x3002] == 0xa3 && block[0x401] == 0xa4);
|
|
CHECK(block[0x2000] == 0xb1 && block[0x400] == 0xb2); // the GPU's stay
|
|
CHECK(app[0x2000] == static_cast<uint8_t>(0x2000 * 7));
|
|
|
|
// The completion writes the GPU's back, and keeps a CPU write made meanwhile.
|
|
app[0x402] = 0xa5;
|
|
s->writeBack();
|
|
CHECK(app[0x2000] == 0xb1 && app[0x400] == 0xb2 && app[0x401] == 0xa4);
|
|
CHECK(app[0x402] == 0xa5 && block[0x402] == static_cast<uint8_t>(0x402 * 7));
|
|
s->syncIn();
|
|
CHECK(block == app);
|
|
s->writeBack();
|
|
CHECK(block == app);
|
|
}
|
|
CHECK(!RgfxMemoryShadow::anyLive());
|
|
|
|
// Read-only memory: synced in, never written.
|
|
std::vector<uint8_t> ro(64, 3), roBlock(64, 0);
|
|
auto r = std::make_shared<RgfxMemoryShadow>(ro.data(), roBlock.data(), ro.size(), false);
|
|
CHECK(!r->writable() && roBlock == ro);
|
|
roBlock[5] = 9;
|
|
r->writeBack();
|
|
CHECK(ro[5] == 3);
|
|
|
|
// The notes: each shadow synced once, the ones any use writes kept.
|
|
std::vector<uint8_t> a2(16, 1), b2(16, 2), aBlock(16), bBlock(16);
|
|
auto a = std::make_shared<RgfxMemoryShadow>(a2.data(), aBlock.data(), 16, true);
|
|
auto b = std::make_shared<RgfxMemoryShadow>(b2.data(), bBlock.data(), 16, true);
|
|
TestRing ring(0x1000);
|
|
RgfxRingWriter writer(ring.base(), ring.dataSize, 1, TestRing::doorbell, nullptr);
|
|
RgfxEncoder enc(writer, 1, 2);
|
|
enc.noteShadowUse(a, false);
|
|
enc.noteShadowUse(a, false); // the same as the last: one note
|
|
enc.noteShadowUse(b, false);
|
|
enc.noteShadowUse(a, true);
|
|
enc.noteShadowUse(r, false);
|
|
std::vector<RgfxShadowUse> uses = enc.takeShadowUses();
|
|
CHECK(uses.size() == 4 && enc.takeShadowUses().empty());
|
|
a2[0] = 5;
|
|
b2[0] = 6;
|
|
std::vector<std::shared_ptr<RgfxMemoryShadow>> written = rgfxShadowsSyncIn(uses);
|
|
CHECK(aBlock[0] == 5 && bBlock[0] == 6);
|
|
CHECK(written.size() == 1 && written[0] == a);
|
|
CHECK(rgfxShadowsSyncIn({}).empty());
|
|
}
|
|
|
|
int main()
|
|
{
|
|
test_id_space();
|
|
test_address_picks();
|
|
test_resource_id_chunks();
|
|
test_caps();
|
|
test_archive_file();
|
|
test_lifecycle_messages();
|
|
test_creates_with_no_address_post_nothing();
|
|
test_library_message();
|
|
test_pipeline_messages();
|
|
test_ring_wrap_and_no_room();
|
|
test_ring_post_waits_for_room();
|
|
test_command_buffer_encoder();
|
|
test_forwarded_lifecycle();
|
|
test_library_key();
|
|
test_keyed_library_messages();
|
|
test_heap_ranges();
|
|
test_heap_texture_size_query();
|
|
test_memory_shadow();
|
|
std::printf("serializer_tests: OK (%d checks)\n", g_checks);
|
|
return 0;
|
|
}
|