Files
reims-vgpu/guest/bundle/tests/shell_tests.mm
T
Anees Iqbal 2fb018a8e1 🐛 Make tiled textures over Shared buffers as WindowServer asks
With the display on the accelerated model, the first WindowServer's first
Metal composite builds a MetalTiledBacking for the display's backing and
calls newTiledTextureWithDescriptor:offset:bytesPerRow: on its buffer. The
bundle answered no such selector, and WindowServer died raising it (pm14 with
"ReimsGraphicsAMD", pm16 with "ReimsGraphicsIntel": the vendor does not
decide the call). Its arguments (pm15): a 2D BGRA8Unorm descriptor of
1024 x 1024, usage ShaderRead | RenderTarget, storage Managed, at offset 0
with a pitch of 15360 bytes, on a Shared buffer of 36864000 bytes, the
3840 x 2400 display's backing: one tile of it at the backing's pitch.

The buffer now makes a texture over its bytes from the offset, rows
bytesPerRow apart, as newTextureWithDescriptor:offset:bytesPerRow: does,
with the buffer's storage. Measured on the M3 Max under macOS 27.0.1: Metal's
validation layer's buffer (MTLDebugBuffer, type `@40@0:8@16Q24Q32`) answers
the selector and asserts that the descriptor is Managed, the buffer Shared
and offset + bytesPerRow x (height - 1) + a row's bytes within the buffer,
with no alignment of offset or pitch; the M3's own buffers answer no such
selector. Those three rules answer nil here, logged. What a Managed-storage
GPU's driver answers is not measured, as no such GPU is on hand.

Measured on a cold boot of the x86 guest on the effort tip's host (pm17): the
first WindowServer builds its tiled backing, renders through it twice, tears
it down, and stays up through the login to the desktop, compositing with
CompositorMetal at 23-49 frames a second; nothing on the tiled path is
refused or unrecognized.
2026-11-05 21:59:19 -08:00

5928 lines
261 KiB
Plaintext

/*
* shell_tests: the Metal shell's user-space check, run on the Mac's native arch
* (guest/bundle/Makefile `test`). It exercises the NSObject-based object wrappers
* — the part of the shell that does not need Apple's private device base — and
* pins the ROUTING ASSERTION PATTERN the four later slices copy:
*
* build a ring + serialiser (the shared tests/rgfx_test_ring.hpp harness, the
* same one the serialiser check uses) -> instantiate a wrapper, which routes its
* create through the serialiser -> read the message back off the ring with
* expectMessage<T> and assert the exact wire fields, plus the wrapper's getters.
*
* The device shell (RgfxMetalDevice) is NOT built into this binary: it subclasses
* an Apple-private class whose symbols resolve only in the guest. Only the
* NSObject-based wrappers are tested here.
*
* Exits 0 and prints a one-line summary when every check passes; aborts on the
* first failure.
*/
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>
#import <objc/message.h>
#include <cstdint>
#include <cstring>
#import "RgfxBuffer.h"
#import "RgfxResource.h"
#import "RgfxEvent.h"
#import "RgfxFence.h"
#import "RgfxSharedEvent.h"
#import "RgfxDepthStencilState.h"
#import "RgfxHeap.h"
#import "RgfxSampler.h"
#import "RgfxTexture.h"
#import "RgfxArgumentEncoder.h"
#import "RgfxBinaryArchive.h"
#import "RgfxComputePipelineState.h"
#import "RgfxFunction.h"
#import "RgfxLibrary.h"
#import "RgfxMetalError.h"
#import "RgfxRenderPipelineState.h"
#include <set>
#include <vector>
#import "RgfxCommandObjects.h"
#import "RgfxIOSurface.h"
#import "RgfxMetalPrivate.h"
#import "RgfxUnsupported.h"
#include "RgfxHeapSizes.hpp"
#include <IOSurface/IOSurface.h>
#include <mach/mach.h>
#include <pthread.h>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <string>
#include <thread>
#include "RgfxCompletionThread.hpp"
#include "RgfxFunctionConstants.hpp"
#include "RgfxManagedLayout.hpp"
#include "RgfxMemoryShadow.hpp"
#include "RgfxObjectModel.hpp"
#include "RgfxRegion.hpp"
#include "RgfxReplyReader.hpp"
#include "RgfxRingWriter.hpp"
#include "RgfxSerializer.hpp"
#include "reims_graphics_wire.h"
#include "rgfx_test_ring.hpp" // CHECK, g_checks, TestRing, expectMessage
@interface TestHandle : RgfxResource <MTLBuffer, MTLTexture, MTLRenderPipelineState,
MTLComputePipelineState, MTLDepthStencilState,
MTLSamplerState, MTLFence, MTLHeap,
MTLIndirectCommandBuffer>
@end
@implementation TestHandle
@end
// The control ring's helpers (below), which the tests in the namespace use too.
uint64_t nextDestroyed(TestRing &ring);
bool ringEmpty(TestRing &ring);
void drainRing(TestRing &ring);
namespace {
// A ring + id space + serialiser over a plain-buffer region, the fixture every
// wrapper routing test stands up. Mirrors how a device category would reach its
// serialiser, minus the device (nil here, as a wrapper allows).
// The transport is never freed: an object a test lets go may dealloc after the test (its
// autorelease pool drains later, or a retirement waits) and post its destroy here.
struct Fixture {
TestRing &ring;
RgfxRingWriter &writer;
RgfxIdSpace &ids;
RgfxSerializer &ser;
Fixture()
: ring(*new TestRing(0x8000)),
writer(*new RgfxRingWriter(ring.base(), ring.dataSize, RGFX_CONTROL_RING_ID,
TestRing::doorbell, nullptr)),
ids(*new RgfxIdSpace()), ser(*new RgfxSerializer(writer, ids))
{
ring.setConsumerIdle(1); // host idle, so each post rings the doorbell
}
};
// A buffer wrapper's create routes an RGFX_CMD_BUFFER_CREATE onto the ring, and
// its getters answer from the created values. This is the pattern the resource
// slice replicates for textures/samplers/heaps.
void test_buffer_routing()
{
Fixture fx;
const NSUInteger length = 0x2000;
const MTLResourceOptions options =
MTLResourceStorageModeShared | MTLResourceCPUCacheModeWriteCombined;
RgfxBuffer *buf = [RgfxBuffer bufferWithLength:length
options:options
device:nil
serializer:&fx.ser];
CHECK(buf != nil);
// The wrapper's getters answer from the created values.
CHECK(buf.rgfxObjId == 1); // first object on this device
CHECK([buf length] == length); // MTLBuffer.length
CHECK([buf gpuAddress] != 0); // a GPU address was picked
CHECK(([buf gpuAddress] % RgfxSerializer::kDefaultAddressAlign) == 0);
CHECK([buf gpuAddress] >= RgfxIdSpace::kDefaultAddressBase);
// Its options as Metal answers them: a Default hazard tracking mode is Tracked.
CHECK([buf resourceOptions] == (options | MTLResourceHazardTrackingModeTracked));
CHECK(buf.device == nil); // no device in this test
CHECK([buf serializer] == &fx.ser); // borrowed route is wired
// contents is a usable, zeroed, length-sized CPU backing.
void *contents = [buf contents];
CHECK(contents != nullptr);
uint8_t *bytes = static_cast<uint8_t *>(contents);
CHECK(bytes[0] == 0 && bytes[length - 1] == 0);
bytes[0] = 0xab;
bytes[length - 1] = 0xcd;
CHECK(bytes[0] == 0xab && bytes[length - 1] == 0xcd);
// The create wrote exactly one BUFFER_CREATE, and its fields match the wrapper.
auto msg = expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
CHECK(msg.header.seqno == 1);
CHECK(msg.obj_id == buf.rgfxObjId);
CHECK(msg.gpu_address == [buf gpuAddress]);
CHECK(msg.length == length);
CHECK(msg.options == static_cast<uint32_t>(options));
// didModifyRange: is a no-op for coherent Shared storage (slice 0) and must not
// post anything or fault. (Apple deprecated the selector on macOS 27 — Managed
// storage has no effect on Apple Silicon — but we still implement it for
// MTLBuffer conformance and older guests, so the call is deprecation-silenced.)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[buf didModifyRange:NSMakeRange(0, length)];
#pragma clang diagnostic pop
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes)); // nothing more on the ring
}
// The bytes this process has resident or compressed, as its footprint counts them.
uint64_t physFootprint()
{
task_vm_info_data_t info = {};
mach_msg_type_number_t count = TASK_VM_INFO_COUNT;
if (task_info(mach_task_self(), TASK_VM_INFO, reinterpret_cast<task_info_t>(&info), &count) !=
KERN_SUCCESS)
return 0;
return info.phys_footprint;
}
// A Private buffer's bytes are the GPU's alone: its create routes as any other's, and no guest
// memory stands for them, whatever its length (`contents` answers NULL, as Metal documents for
// the mode). A Managed one made without a region still has zeroed contents of its own.
void test_private_buffer_has_no_contents()
{
Fixture fx;
// Drained while fx lives: a buffer's dealloc posts its destroy through fx.
@autoreleasepool {
const NSUInteger length = 0x4000000; // 64 MiB, which a zeroed backing would make resident
const uint64_t before = physFootprint();
RgfxBuffer *priv = [RgfxBuffer bufferWithLength:length
options:MTLResourceStorageModePrivate
device:nil
serializer:&fx.ser];
CHECK(priv != nil);
CHECK([priv contents] == nullptr);
CHECK(physFootprint() < before + 0x800000);
CHECK([priv length] == length && [priv storageMode] == MTLStorageModePrivate);
auto msg = expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
CHECK(msg.obj_id == priv.rgfxObjId && msg.gpu_address == [priv gpuAddress]);
CHECK(msg.length == length);
CHECK(msg.options == static_cast<uint32_t>(MTLResourceStorageModePrivate));
// didModifyRange: on it posts nothing and touches nothing.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[priv didModifyRange:NSMakeRange(0, 0x1000)];
#pragma clang diagnostic pop
RgfxBuffer *managed = [RgfxBuffer bufferWithLength:0x1000
options:MTLResourceStorageModeManaged
device:nil
serializer:&fx.ser];
CHECK(managed != nil && [managed contents] != nullptr);
CHECK(static_cast<uint8_t *>([managed contents])[0xfff] == 0);
(void)expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes)); // nothing more on the ring
}
}
// The device's buffers answer as Metal's (measured on the M3 Max, macOS 27): a Shared one lies
// over a block of the region with the bytes given (or zeros), a Managed one's CPU copy too, and
// a Private one has no contents. None of 0 bytes or past maxBufferLength, in any mode; none
// where the region has no room for a Shared or Managed one (no device buffer the host would
// never see); none for bytes with a Private one. A refusal posts nothing.
void test_device_buffers_answer_as_metal()
{
Fixture fx;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x10000, 0xee);
RgfxRegion region(mem.data(), mem.size());
auto make = [&](NSUInteger length, MTLResourceOptions options, const void *bytes,
NSUInteger maxLength, RgfxRegion *in) {
return [RgfxBuffer bufferForDeviceWithLength:length
options:options
bytes:bytes
maxLength:maxLength
region:in
device:nil
serializer:&fx.ser];
};
auto nothingPosted = [&]() {
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
return !fx.ring.next(&h, &bytes);
};
@autoreleasepool {
uint8_t pattern[0x100];
for (size_t i = 0; i < sizeof(pattern); i++)
pattern[i] = static_cast<uint8_t>(i * 3 + 1);
RgfxBuffer *shared = make(sizeof(pattern), MTLResourceStorageModeShared, pattern, 0x2000,
&region);
CHECK(shared != nil && shared.length == sizeof(pattern));
uint8_t *at = static_cast<uint8_t *>([shared contents]);
CHECK(at >= mem.data() + RGFX_ALLOCATIONS_OFFSET && at < mem.data() + mem.size());
CHECK(std::memcmp(at, pattern, sizeof(pattern)) == 0);
auto over = expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(over.obj_id == shared.rgfxObjId && over.length == sizeof(pattern));
CHECK(over.region_offset == static_cast<uint64_t>(at - mem.data()));
RgfxBuffer *managed = make(0x1000, MTLResourceStorageModeManaged, nullptr, 0x2000, &region);
CHECK(managed != nil && managed.storageMode == MTLStorageModeManaged);
CHECK(static_cast<uint8_t *>([managed contents])[0] == 0 &&
static_cast<uint8_t *>([managed contents])[0xfff] == 0);
(void)expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
RgfxBuffer *priv = make(0x1000, MTLResourceStorageModePrivate, nullptr, 0x2000, &region);
CHECK(priv != nil && [priv contents] == nullptr);
(void)expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
// No limit known: none held back.
RgfxBuffer *unlimited = make(0x3000, MTLResourceStorageModePrivate, nullptr, 0, &region);
CHECK(unlimited != nil);
(void)expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
CHECK(nothingPosted());
const MTLResourceOptions modes[] = { MTLResourceStorageModeShared,
MTLResourceStorageModeManaged,
MTLResourceStorageModePrivate };
for (MTLResourceOptions mode : modes) {
CHECK(make(0, mode, nullptr, 0x2000, &region) == nil);
CHECK(make(0x2001, mode, nullptr, 0x2000, &region) == nil);
}
// Bytes for a Private buffer; a Shared or Managed one with no region, or too large for
// what it has left.
CHECK(make(0x100, MTLResourceStorageModePrivate, pattern, 0x2000, &region) == nil);
CHECK(make(0x100, MTLResourceStorageModeShared, nullptr, 0x2000, nullptr) == nil);
CHECK(make(0x20000, MTLResourceStorageModeShared, nullptr, 0, &region) == nil);
CHECK(make(0x20000, MTLResourceStorageModeManaged, pattern, 0, &region) == nil);
CHECK(nothingPosted());
} // the buffers go while the region lives
std::vector<uint8_t> drain;
RgfxMsgHeader h;
while (fx.ring.next(&h, &drain)) {
}
}
// The id space is monotonic across wrappers: a second buffer gets the next objId
// and a disjoint, higher GPU address, and its own BUFFER_CREATE.
void test_second_buffer_is_monotonic()
{
Fixture fx;
RgfxBuffer *a = [RgfxBuffer bufferWithLength:0x1000
options:MTLResourceStorageModeShared
device:nil
serializer:&fx.ser];
RgfxBuffer *b = [RgfxBuffer bufferWithLength:0x1000
options:MTLResourceStorageModeShared
device:nil
serializer:&fx.ser];
CHECK(a != nil && b != nil);
CHECK(b.rgfxObjId == a.rgfxObjId + 1);
CHECK([b gpuAddress] >= [a gpuAddress] + 0x1000);
auto ma = expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
auto mb = expectMessage<RgfxBufferCreate>(fx.ring, RGFX_CMD_BUFFER_CREATE);
CHECK(ma.obj_id == a.rgfxObjId && mb.obj_id == b.rgfxObjId);
CHECK(mb.header.seqno == ma.header.seqno + 1);
}
// A wrapper with no serialiser route cannot be created (a buffer must reach the
// host), and the base label getter/setter work.
void test_wrapper_guards_and_base()
{
RgfxBuffer *none = [RgfxBuffer bufferWithLength:0x1000
options:MTLResourceStorageModeShared
device:nil
serializer:nullptr];
CHECK(none == nil);
Fixture fx;
RgfxBuffer *buf = [RgfxBuffer bufferWithLength:0x1000
options:MTLResourceStorageModeShared
device:nil
serializer:&fx.ser];
CHECK(buf.label == nil);
buf.label = @"scratch";
CHECK([buf.label isEqualToString:@"scratch"]);
// RgfxBuffer is a RgfxResource and conforms to MTLBuffer.
CHECK([buf isKindOfClass:[RgfxResource class]]);
CHECK([buf conformsToProtocol:@protocol(MTLBuffer)]);
}
// --- sync slice (slice 4): event / fence / shared-event wrappers -------------
// An event wrapper's create routes one RGFX_CMD_EVENT_CREATE (an RgfxObjectCreate
// carrying its objId), and the wrapper carries that id, its device and route.
void test_event_routing()
{
Fixture fx;
RgfxEvent *ev = [RgfxEvent eventWithDevice:nil serializer:&fx.ser];
CHECK(ev != nil);
CHECK(ev.rgfxObjId == 1); // first object on this device
CHECK(ev.device == nil);
CHECK([ev serializer] == &fx.ser);
CHECK([ev isKindOfClass:[RgfxResource class]]);
CHECK([ev conformsToProtocol:@protocol(MTLEvent)]);
auto msg = expectMessage<RgfxObjectCreate>(fx.ring, RGFX_CMD_EVENT_CREATE);
CHECK(msg.header.seqno == 1);
CHECK(msg.obj_id == ev.rgfxObjId);
// Nothing else reached the ring.
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes));
// A null route declines the create (an event must reach the host).
CHECK([RgfxEvent eventWithDevice:nil serializer:nullptr] == nil);
}
// A fence wrapper's create routes one RGFX_CMD_FENCE_CREATE, same shape as an
// event.
void test_fence_routing()
{
Fixture fx;
RgfxFence *fence = [RgfxFence fenceWithDevice:nil serializer:&fx.ser];
CHECK(fence != nil);
CHECK(fence.rgfxObjId == 1);
CHECK([fence conformsToProtocol:@protocol(MTLFence)]);
auto msg = expectMessage<RgfxObjectCreate>(fx.ring, RGFX_CMD_FENCE_CREATE);
CHECK(msg.header.seqno == 1);
CHECK(msg.obj_id == fence.rgfxObjId);
CHECK([RgfxFence fenceWithDevice:nil serializer:nullptr] == nil);
}
// A shared-event wrapper's create routes one RGFX_CMD_SHARED_EVENT_CREATE carrying
// the initial value, and its signaledValue starts there. A CPU set goes to the host
// (RGFX_CMD_SHARED_EVENT_SET_VALUE) and raises the value; one to a lower value goes too,
// and leaves it, as Metal's does.
void test_shared_event_routing()
{
Fixture fx;
const uint64_t initial = 0x1234;
RgfxSharedEvent *ev = [RgfxSharedEvent sharedEventWithInitialValue:initial
device:nil
serializer:&fx.ser];
CHECK(ev != nil);
CHECK(ev.rgfxObjId == 1);
CHECK([ev conformsToProtocol:@protocol(MTLSharedEvent)]);
auto msg = expectMessage<RgfxSharedEventCreate>(fx.ring, RGFX_CMD_SHARED_EVENT_CREATE);
CHECK(msg.header.seqno == 1);
CHECK(msg.obj_id == ev.rgfxObjId);
CHECK(msg.initial_value == initial);
CHECK(ev.signaledValue == initial);
ev.signaledValue = initial + 7;
CHECK(ev.signaledValue == initial + 7);
auto set = expectMessage<RgfxSharedEventSetValue>(fx.ring, RGFX_CMD_SHARED_EVENT_SET_VALUE);
CHECK(set.obj_id == ev.rgfxObjId && set.value == initial + 7);
ev.signaledValue = 1;
CHECK(ev.signaledValue == initial + 7);
auto lower = expectMessage<RgfxSharedEventSetValue>(fx.ring, RGFX_CMD_SHARED_EVENT_SET_VALUE);
CHECK(lower.value == 1);
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes));
CHECK([ev newSharedEventHandle] == nil);
CHECK([RgfxSharedEvent sharedEventWithInitialValue:0 device:nil serializer:nullptr] == nil);
}
// The CPU's copies of a texture: one over a buffer writes and reads the region's rows in the
// buffer's bytes, at the texture's rows; a Private texture's are refused with nothing posted,
// as is a device texture's copy with no device to blit on.
void test_texture_cpu_copies()
{
Fixture fx;
@autoreleasepool {
// A 4 x 3 BGRA8 texture over a buffer, its rows 32 bytes apart from offset 16.
std::vector<uint8_t> memory(16 + 32 * 3, 0xee);
RgfxBuffer *buf = [RgfxBuffer bufferOverHostMemoryWithContents:memory.data()
regionOffset:0x10000
length:memory.size()
options:MTLResourceStorageModeShared
deallocator:nil
device:nil
serializer:&fx.ser];
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:4
height:3
mipmapped:NO];
desc.storageMode = MTLStorageModeShared;
RgfxTexture *tex = [RgfxTexture textureWithDescriptor:desc
buffer:buf
offset:16
bytesPerRow:32
device:nil
serializer:&fx.ser];
CHECK(tex != nil);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (fx.ring.next(&h, &bytes)) {
}
// Two pixels of each of two rows, from (1, 1), the caller's rows 12 bytes apart.
uint8_t in[24];
for (int i = 0; i < 24; i++)
in[i] = static_cast<uint8_t>(i);
[tex replaceRegion:MTLRegionMake2D(1, 1, 2, 2) mipmapLevel:0 withBytes:in bytesPerRow:12];
CHECK(std::memcmp(&memory[16 + 32 * 1 + 4], &in[0], 8) == 0);
CHECK(std::memcmp(&memory[16 + 32 * 2 + 4], &in[12], 8) == 0);
CHECK(memory[16 + 32 * 1] == 0xee && memory[16 + 32 * 1 + 12] == 0xee); // around it
CHECK(memory[16 + 32 * 0 + 4] == 0xee);
uint8_t out[16] = {};
[tex getBytes:out bytesPerRow:8 fromRegion:MTLRegionMake2D(1, 1, 2, 2) mipmapLevel:0];
CHECK(std::memcmp(&out[0], &in[0], 8) == 0 && std::memcmp(&out[8], &in[12], 8) == 0);
// Past the texture, or rows shorter than the region's: nothing is copied.
[tex replaceRegion:MTLRegionMake2D(3, 0, 2, 1) mipmapLevel:0 withBytes:in bytesPerRow:8];
[tex replaceRegion:MTLRegionMake2D(0, 0, 2, 1) mipmapLevel:0 withBytes:in bytesPerRow:4];
CHECK(memory[16] == 0xee && memory[16 + 12] == 0xee);
// A Private texture: refused, nothing posted. A Shared device texture with no device:
// no queue to blit on, nothing posted.
desc.storageMode = MTLStorageModePrivate;
RgfxTexture *priv = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
desc.storageMode = MTLStorageModeShared;
RgfxTexture *shared = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
CHECK(priv != nil && shared != nil);
while (fx.ring.next(&h, &bytes)) {
}
[priv replaceRegion:MTLRegionMake2D(0, 0, 2, 2) mipmapLevel:0 withBytes:in bytesPerRow:12];
[priv getBytes:out bytesPerRow:8 fromRegion:MTLRegionMake2D(0, 0, 2, 2) mipmapLevel:0];
[shared replaceRegion:MTLRegionMake2D(0, 0, 2, 2) mipmapLevel:0 withBytes:in bytesPerRow:12];
CHECK(!fx.ring.next(&h, &bytes));
// A resource's purgeable state is kept as told, the previous one answered, and nothing
// is posted: the device purges nothing. A texture over a buffer stays NonVolatile, as
// Metal's (resource_tests.mm).
CHECK([buf setPurgeableState:MTLPurgeableStateKeepCurrent] == MTLPurgeableStateNonVolatile);
CHECK([buf setPurgeableState:MTLPurgeableStateVolatile] == MTLPurgeableStateNonVolatile);
CHECK([buf setPurgeableState:MTLPurgeableStateKeepCurrent] == MTLPurgeableStateVolatile);
CHECK([tex setPurgeableState:MTLPurgeableStateEmpty] == MTLPurgeableStateNonVolatile);
CHECK([tex setPurgeableState:MTLPurgeableStateNonVolatile] == MTLPurgeableStateNonVolatile);
CHECK(!fx.ring.next(&h, &bytes));
// A buffer's resource options decode as a texture's; a resource made in no heap answers
// none, and cannot be made aliasable.
CHECK(buf.storageMode == MTLStorageModeShared && tex.storageMode == MTLStorageModeShared);
CHECK(buf.cpuCacheMode == MTLCPUCacheModeDefaultCache);
CHECK(buf.hazardTrackingMode == MTLHazardTrackingModeTracked);
CHECK(buf.heap == nil && buf.heapOffset == 0 && tex.heap == nil);
[buf makeAliasable];
CHECK(!buf.isAliasable);
CHECK([buf setOwnerWithIdentity:0] == KERN_SUCCESS);
// No resource is protected: the device protects no content.
CHECK([buf protectionOptions] == 0 && [tex protectionOptions] == 0);
}
}
// A tiled texture (newTiledTextureWithDescriptor:offset:bytesPerRow:, RgfxBuffer.mm), as
// WindowServer's MetalTiledBacking makes one: a tile of a Shared backing buffer at the backing's
// pitch, from a Managed descriptor. It is a texture over the buffer's bytes with the buffer's
// storage (TEXTURE_FROM_BUFFER), whose CPU copies read and write the tile's bytes in the
// buffer. What Metal's validation asserts at answers nil and posts nothing.
void test_tiled_texture_over_backing()
{
Fixture fx;
@autoreleasepool {
// A backing of 8 x 6 BGRA8 pixels, 32 bytes a row, and a 3 x 2 tile of it at (2, 3).
const NSUInteger pitch = 32, tileOffset = 3 * pitch + 2 * 4;
std::vector<uint8_t> memory(pitch * 6, 0xee);
RgfxBuffer *buf = [RgfxBuffer bufferOverHostMemoryWithContents:memory.data()
regionOffset:0x10000
length:memory.size()
options:MTLResourceStorageModeShared
deallocator:nil
device:nil
serializer:&fx.ser];
CHECK(buf != nil);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (fx.ring.next(&h, &bytes)) {
}
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:3
height:2
mipmapped:NO];
desc.usage = MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
desc.storageMode = MTLStorageModeManaged;
#pragma clang diagnostic pop
id<RgfxMetalBufferInternals> tiled = (id<RgfxMetalBufferInternals>)buf;
id<MTLTexture> tex = [tiled newTiledTextureWithDescriptor:desc
offset:tileOffset
bytesPerRow:pitch];
CHECK(tex != nil && tex.buffer == buf && tex.bufferOffset == tileOffset &&
tex.bufferBytesPerRow == pitch);
CHECK(tex.storageMode == MTLStorageModeShared && tex.width == 3 && tex.height == 2);
auto made = expectMessage<RgfxTextureFromBuffer>(fx.ring, RGFX_CMD_TEXTURE_FROM_BUFFER);
CHECK(made.buffer_obj_id == buf.rgfxObjId && made.offset == tileOffset &&
made.bytes_per_row == pitch);
CHECK(made.desc.width == 3 && made.desc.height == 2 &&
made.desc.pixel_format == MTLPixelFormatBGRA8Unorm &&
(made.desc.options & MTLResourceStorageModeMask) == MTLResourceStorageModeShared);
CHECK(ringEmpty(fx.ring));
// The CPU's bytes in the backing are the tile's texels, and the tile's writes land there.
for (NSUInteger i = 0; i < memory.size(); i++)
memory[i] = static_cast<uint8_t>(i);
uint8_t out[3 * 4 * 2] = {};
[tex getBytes:out bytesPerRow:12 fromRegion:MTLRegionMake2D(0, 0, 3, 2) mipmapLevel:0];
CHECK(std::memcmp(&out[0], &memory[tileOffset], 12) == 0);
CHECK(std::memcmp(&out[12], &memory[tileOffset + pitch], 12) == 0);
uint8_t in[8] = {0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7};
[tex replaceRegion:MTLRegionMake2D(1, 1, 2, 1) mipmapLevel:0 withBytes:in bytesPerRow:8];
CHECK(std::memcmp(&memory[tileOffset + pitch + 4], in, 8) == 0);
CHECK(memory[tileOffset + pitch] == static_cast<uint8_t>(tileOffset + pitch)); // beside it
CHECK(memory[tileOffset + pitch + 12] == static_cast<uint8_t>(tileOffset + pitch + 12));
// Metal's validation's rules: a descriptor other than Managed, and a tile past the
// buffer's bytes (offset + pitch x (height - 1) + the row's bytes), answer nil.
desc.storageMode = MTLStorageModeShared;
CHECK([tiled newTiledTextureWithDescriptor:desc offset:tileOffset bytesPerRow:pitch] == nil);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
desc.storageMode = MTLStorageModeManaged;
#pragma clang diagnostic pop
const NSUInteger last = memory.size() - (pitch + 3 * 4); // the last offset that fits
id<MTLTexture> atLast = [tiled newTiledTextureWithDescriptor:desc
offset:last
bytesPerRow:pitch];
CHECK(atLast != nil);
CHECK(expectMessage<RgfxTextureFromBuffer>(fx.ring, RGFX_CMD_TEXTURE_FROM_BUFFER).offset ==
last);
CHECK([tiled newTiledTextureWithDescriptor:desc offset:last + 4 bytesPerRow:pitch] == nil);
// Any offset and pitch inside the buffer: no alignment is asked.
id<MTLTexture> odd = [tiled newTiledTextureWithDescriptor:desc offset:4 bytesPerRow:pitch + 4];
CHECK(odd != nil);
CHECK(expectMessage<RgfxTextureFromBuffer>(fx.ring, RGFX_CMD_TEXTURE_FROM_BUFFER)
.bytes_per_row == pitch + 4);
while (fx.ring.next(&h, &bytes)) {
}
// A buffer other than Shared answers nil.
std::vector<uint8_t> other(pitch * 6, 0);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
RgfxBuffer *managed = [RgfxBuffer bufferOverHostMemoryWithContents:other.data()
regionOffset:0x20000
length:other.size()
options:MTLResourceStorageModeManaged
deallocator:nil
device:nil
serializer:&fx.ser];
#pragma clang diagnostic pop
CHECK(managed != nil);
while (fx.ring.next(&h, &bytes)) {
}
CHECK([(id<RgfxMetalBufferInternals>)managed newTiledTextureWithDescriptor:desc
offset:0
bytesPerRow:pitch] == nil);
CHECK(ringEmpty(fx.ring));
}
}
// A texture wrapper's create routes an RGFX_CMD_TEXTURE_CREATE onto the ring
// (device-placed: a GPU address and a resource id are picked, heap_obj_id 0), and
// its getters answer the mapped descriptor. The RgfxBuffer routing pattern, for
// the texture's shape.
void test_texture_routing()
{
Fixture fx;
// Drained while fx lives: a texture's dealloc posts its destroy through fx.
@autoreleasepool {
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:1920
height:1080
mipmapped:NO];
desc.usage = MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead;
desc.storageMode = MTLStorageModePrivate;
RgfxTexture *tex = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
CHECK(tex != nil);
// Getters answer the mapped descriptor.
CHECK(tex.rgfxObjId == 1);
CHECK([tex textureType] == MTLTextureType2D);
CHECK([tex pixelFormat] == MTLPixelFormatBGRA8Unorm);
CHECK([tex width] == 1920 && [tex height] == 1080 && [tex depth] == 1);
CHECK([tex mipmapLevelCount] == 1 && [tex arrayLength] == 1 && [tex sampleCount] == 1);
CHECK([tex usage] == (MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead));
CHECK([tex storageMode] == MTLStorageModePrivate);
// Its Default hazard tracking mode answered resolved, as Metal's (resource_tests.mm).
CHECK([tex resourceOptions] == (desc.resourceOptions | MTLResourceHazardTrackingModeTracked));
MTLTextureSwizzleChannels sw = [tex swizzle]; // the descriptor's default swizzle
CHECK(sw.red == MTLTextureSwizzleRed && sw.green == MTLTextureSwizzleGreen);
CHECK(sw.blue == MTLTextureSwizzleBlue && sw.alpha == MTLTextureSwizzleAlpha);
CHECK([tex gpuResourceID]._impl != 0); // a resource id was picked
CHECK([tex parentTexture] == nil && [tex buffer] == nil);
// The create wrote exactly one TEXTURE_CREATE matching the wrapper.
auto msg = expectMessage<RgfxTextureCreate>(fx.ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(msg.header.seqno == 1);
CHECK(msg.obj_id == tex.rgfxObjId);
CHECK(msg.resource_id == [tex gpuResourceID]._impl);
CHECK(msg.gpu_address != 0 && msg.heap_obj_id == 0); // device-placed
CHECK(msg.desc.pixel_format == MTLPixelFormatBGRA8Unorm);
CHECK(msg.desc.texture_type == MTLTextureType2D);
CHECK(msg.desc.width == 1920 && msg.desc.height == 1080);
CHECK(msg.desc.usage == (uint32_t)(MTLTextureUsageRenderTarget | MTLTextureUsageShaderRead));
CHECK(msg.desc.options == (uint32_t)desc.resourceOptions);
}
}
// One chunk of texture resource ids (ids 1 + 4 * 64 to 64 + 4 * 64), as the kext would hand
// it, and none after it.
bool oneChunk(void *context, uint64_t *first_id)
{
int *calls = static_cast<int *>(context);
if ((*calls)++ != 0)
return false;
*first_id = 1 + 4 * RGFX_RESOURCE_ID_CHUNK;
return true;
}
// A texture's resource id comes from the process's chunks and goes back as the texture goes,
// for the next texture; with every id held and no chunk left, newTexture answers nil and posts
// nothing.
void test_texture_resource_ids()
{
Fixture fx;
// Drained while fx lives: a texture's dealloc posts its destroy through fx.
@autoreleasepool {
int calls = 0;
fx.ids.setResourceIdSource(&oneChunk, &calls);
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:16
height:16
mipmapped:NO];
const uint64_t first = 1 + 4 * RGFX_RESOURCE_ID_CHUNK;
NSMutableArray<RgfxTexture *> *held = [NSMutableArray array];
for (uint64_t i = 0; i < RGFX_RESOURCE_ID_CHUNK; i++) {
// Each texture's autoreleased return drains here, so `held` alone keeps it.
@autoreleasepool {
RgfxTexture *tex = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
CHECK(tex != nil && [tex gpuResourceID]._impl == first + i);
auto msg = expectMessage<RgfxTextureCreate>(fx.ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(msg.resource_id == first + i);
[held addObject:tex];
}
}
CHECK(calls == 1);
RgfxTexture *none = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
CHECK(none == nil);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(!fx.ring.next(&h, &bytes));
// The texture holding id first + 10 goes: the host drops it (no command buffer is in
// flight), then the next texture takes its id, after the destroy on the ring.
uint64_t goneObjId = 0;
@autoreleasepool {
goneObjId = held[10].rgfxObjId;
[held removeObjectAtIndex:10];
}
auto gone = expectMessage<RgfxObjectDestroy>(fx.ring, RGFX_CMD_OBJECT_DESTROY);
CHECK(gone.obj_id == goneObjId);
RgfxTexture *again = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
CHECK(again != nil && [again gpuResourceID]._impl == first + 10);
auto msg = expectMessage<RgfxTextureCreate>(fx.ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(msg.resource_id == first + 10 && msg.obj_id == again.rgfxObjId);
}
}
// A sampler wrapper's create routes an RGFX_CMD_SAMPLER_CREATE, mapping every
// descriptor field (the LOD clamps as f32 bits, the booleans packed into flags).
void test_sampler_routing()
{
Fixture fx;
MTLSamplerDescriptor *desc = [[MTLSamplerDescriptor alloc] init];
desc.minFilter = MTLSamplerMinMagFilterLinear;
desc.magFilter = MTLSamplerMinMagFilterLinear;
desc.mipFilter = MTLSamplerMipFilterLinear;
desc.sAddressMode = MTLSamplerAddressModeClampToEdge;
desc.tAddressMode = MTLSamplerAddressModeRepeat;
desc.rAddressMode = MTLSamplerAddressModeMirrorRepeat;
desc.maxAnisotropy = 4;
desc.compareFunction = MTLCompareFunctionLess;
desc.lodMinClamp = 0.0f;
desc.lodMaxClamp = 7.5f;
desc.normalizedCoordinates = YES;
desc.supportArgumentBuffers = YES;
RgfxSampler *smp = [RgfxSampler samplerWithDescriptor:desc device:nil serializer:&fx.ser];
CHECK(smp != nil && smp.rgfxObjId == 1);
CHECK([smp conformsToProtocol:@protocol(MTLSamplerState)]);
auto msg = expectMessage<RgfxSamplerCreate>(fx.ring, RGFX_CMD_SAMPLER_CREATE);
CHECK(msg.obj_id == smp.rgfxObjId);
CHECK(msg.min_filter == (uint32_t)MTLSamplerMinMagFilterLinear);
CHECK(msg.mag_filter == (uint32_t)MTLSamplerMinMagFilterLinear);
CHECK(msg.mip_filter == (uint32_t)MTLSamplerMipFilterLinear);
CHECK(msg.s_address_mode == (uint32_t)MTLSamplerAddressModeClampToEdge);
CHECK(msg.t_address_mode == (uint32_t)MTLSamplerAddressModeRepeat);
CHECK(msg.r_address_mode == (uint32_t)MTLSamplerAddressModeMirrorRepeat);
CHECK(msg.max_anisotropy == 4);
CHECK(msg.compare_function == (uint32_t)MTLCompareFunctionLess);
float lodMax;
std::memcpy(&lodMax, &msg.lod_max_clamp_bits, 4);
CHECK(lodMax == 7.5f);
CHECK(msg.flags == (0x1u | 0x4u)); // normalized coords + argument-buffer usable
}
// A depth/stencil wrapper's create routes an RGFX_CMD_DEPTH_STENCIL_CREATE,
// mapping the depth test/write and both faces' stencil state.
void test_depth_stencil_routing()
{
Fixture fx;
MTLDepthStencilDescriptor *desc = [[MTLDepthStencilDescriptor alloc] init];
desc.depthCompareFunction = MTLCompareFunctionLessEqual;
desc.depthWriteEnabled = YES;
MTLStencilDescriptor *front = [[MTLStencilDescriptor alloc] init];
front.stencilCompareFunction = MTLCompareFunctionEqual;
front.stencilFailureOperation = MTLStencilOperationKeep;
front.depthFailureOperation = MTLStencilOperationIncrementClamp;
front.depthStencilPassOperation = MTLStencilOperationReplace;
front.readMask = 0xfe;
front.writeMask = 0xcd;
desc.frontFaceStencil = front;
RgfxDepthStencilState *ds =
[RgfxDepthStencilState depthStencilStateWithDescriptor:desc device:nil serializer:&fx.ser];
CHECK(ds != nil && ds.rgfxObjId == 1);
CHECK([ds conformsToProtocol:@protocol(MTLDepthStencilState)]);
auto msg = expectMessage<RgfxDepthStencilCreate>(fx.ring, RGFX_CMD_DEPTH_STENCIL_CREATE);
CHECK(msg.obj_id == ds.rgfxObjId);
CHECK(msg.depth_compare == (uint32_t)MTLCompareFunctionLessEqual);
CHECK(msg.depth_write_enabled == 1);
CHECK(msg.front.stencil_compare == (uint32_t)MTLCompareFunctionEqual);
CHECK(msg.front.stencil_fail_op == (uint32_t)MTLStencilOperationKeep);
CHECK(msg.front.depth_fail_op == (uint32_t)MTLStencilOperationIncrementClamp);
CHECK(msg.front.pass_op == (uint32_t)MTLStencilOperationReplace);
CHECK(msg.front.read_mask == 0xfe && msg.front.write_mask == 0xcd);
// The untouched back face carries Metal's default MTLStencilDescriptor:
// stencilCompareFunction Always, keep operations, all-ones masks.
CHECK(msg.back.stencil_compare == (uint32_t)MTLCompareFunctionAlways);
CHECK(msg.back.read_mask == 0xffffffffu && msg.back.write_mask == 0xffffffffu);
}
// A heap wrapper's create routes an RGFX_CMD_HEAP_CREATE; its getters answer the
// descriptor; and a Placement heap sub-allocates a buffer (BUFFER_AT_OFFSET) and a
// texture (TEXTURE_CREATE into the heap), both wrapped. The offset-less variants
// are documented nil stubs this slice.
void test_heap_routing_and_suballoc()
{
Fixture fx;
// Drained while fx lives: a texture's dealloc posts its destroy through fx.
@autoreleasepool {
MTLHeapDescriptor *hd = [[MTLHeapDescriptor alloc] init];
hd.size = 0x100000;
hd.storageMode = MTLStorageModePrivate;
hd.type = MTLHeapTypePlacement;
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:hd device:nil serializer:&fx.ser];
CHECK(heap != nil && heap.rgfxObjId == 1);
CHECK([heap size] == 0x100000);
CHECK([heap type] == MTLHeapTypePlacement);
CHECK([heap storageMode] == MTLStorageModePrivate);
// Its options as Metal answers them: a Default hazard tracking mode is Untracked for a heap.
CHECK([heap resourceOptions] == (hd.resourceOptions | MTLResourceHazardTrackingModeUntracked));
auto hm = expectMessage<RgfxHeapCreate>(fx.ring, RGFX_CMD_HEAP_CREATE);
CHECK(hm.obj_id == heap.rgfxObjId && hm.gpu_address != 0);
CHECK(hm.size_bytes == 0x100000 && hm.heap_type == (int32_t)MTLHeapTypePlacement);
CHECK(hm.options == (uint32_t)hd.resourceOptions);
// Placement buffer at an offset -> BUFFER_AT_OFFSET into this heap.
id<MTLBuffer> hb = [heap newBufferWithLength:0x400
options:MTLResourceStorageModePrivate
offset:0x2000];
CHECK(hb != nil);
CHECK([(RgfxBuffer *)hb rgfxObjId] == heap.rgfxObjId + 1); // next objId
CHECK([hb length] == 0x400);
auto bm = expectMessage<RgfxBufferAtOffset>(fx.ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(bm.obj_id == [(RgfxBuffer *)hb rgfxObjId]);
CHECK(bm.heap_obj_id == heap.rgfxObjId);
CHECK(bm.offset == 0x2000 && bm.length == 0x400);
// Placement texture at an offset -> TEXTURE_CREATE into this heap.
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:256
height:256
mipmapped:NO];
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> ht = [heap newTextureWithDescriptor:td offset:0x4000];
CHECK(ht != nil);
CHECK([ht width] == 256 && [ht height] == 256);
auto tm = expectMessage<RgfxTextureCreate>(fx.ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(tm.obj_id == [(RgfxTexture *)ht rgfxObjId]);
CHECK(tm.heap_obj_id == heap.rgfxObjId && tm.heap_offset == 0x4000);
CHECK(tm.gpu_address == 0); // heap-placed: no device address
CHECK(tm.desc.pixel_format == MTLPixelFormatRGBA8Unorm);
// Each answers its heap and offset, and is aliasable, as a Placement heap's resources are
// from their making.
CHECK(hb.heap == heap && hb.heapOffset == 0x2000);
CHECK(ht.heap == heap && ht.heapOffset == 0x4000);
CHECK(hb.storageMode == MTLStorageModePrivate);
CHECK([hb contents] == nullptr); // a Private heap's buffer: the GPU's bytes alone
CHECK(ht.isAliasable && hb.isAliasable);
[ht makeAliasable];
CHECK(ht.isAliasable);
// The offset-less (Automatic-placement) variants are nil stubs this slice.
CHECK([heap newBufferWithLength:0x100 options:MTLResourceStorageModePrivate] == nil);
CHECK([heap newTextureWithDescriptor:td] == nil);
// Of an Automatic heap, a placement at an offset is nil, and nothing is posted.
hd.type = MTLHeapTypeAutomatic;
RgfxHeap *automatic = [RgfxHeap heapWithDescriptor:hd device:nil serializer:&fx.ser];
(void)expectMessage<RgfxHeapCreate>(fx.ring, RGFX_CMD_HEAP_CREATE);
CHECK([automatic newTextureWithDescriptor:td offset:0x4000] == nil);
CHECK([automatic newBufferWithLength:0x400
options:MTLResourceStorageModePrivate
offset:0x2000] == nil);
RgfxMsgHeader h = {};
std::vector<uint8_t> posted;
CHECK(!fx.ring.next(&h, &posted));
}
}
// A wrapper with no serialiser route cannot be created (each resource must reach
// the host).
void test_resource_guards()
{
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:16
height:16
mipmapped:NO];
CHECK([RgfxTexture textureWithDescriptor:td
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:nullptr] == nil);
CHECK([RgfxSampler samplerWithDescriptor:[[MTLSamplerDescriptor alloc] init]
device:nil
serializer:nullptr] == nil);
CHECK([RgfxDepthStencilState depthStencilStateWithDescriptor:[[MTLDepthStencilDescriptor alloc]
init]
device:nil
serializer:nullptr] == nil);
CHECK([RgfxHeap heapWithDescriptor:[[MTLHeapDescriptor alloc] init]
device:nil
serializer:nullptr] == nil);
}
// Reads the next message off the ring into `bytes` and checks its type; returns the
// full message bytes (head + tail) for a variable-size wire struct the fixed-size
// expectMessage<T> cannot read. Aborts (via CHECK) if there is no message.
std::vector<uint8_t> nextMessage(TestRing &ring, uint32_t type)
{
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(ring.next(&h, &bytes));
CHECK(h.type == type);
return bytes;
}
// A library create forwards its bytes unchanged (RGFX_CMD_LIBRARY_CREATE), and the
// library vends a function by name as a guest-side RgfxFunction (no wire message).
void test_library_and_function_routing()
{
Fixture fx;
const uint8_t libBytes[] = {0xDE, 0xAD, 0xBE, 0xEF, 0x01, 0x02, 0x03};
uint32_t libStatus = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&libStatus];
CHECK(lib != nil);
CHECK(lib.rgfxObjId == 1); // first object on this device
CHECK([lib conformsToProtocol:@protocol(MTLLibrary)]);
auto bytes = nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE);
RgfxLibraryCreate head;
std::memcpy(&head, bytes.data(), sizeof(head));
CHECK(head.header.seqno == 1);
CHECK(head.obj_id == lib.rgfxObjId);
CHECK(head.byte_length == sizeof(libBytes));
CHECK(std::memcmp(bytes.data() + RGFX_LIBRARY_BYTES_OFFSET, libBytes, sizeof(libBytes)) == 0);
// A function is a guest-side reference: it holds the library objId + name, picks
// no objId, and posts nothing.
id<MTLFunction> fn = [lib newFunctionWithName:@"vmain"];
CHECK(fn != nil);
RgfxFunction *rf = (RgfxFunction *)fn;
CHECK(rf.rgfxObjId == 0); // RGFX_OBJ_NONE: no host handle of its own
CHECK(rf.rgfxLibraryObjId == lib.rgfxObjId);
CHECK(std::strcmp([rf rgfxEntryPointUTF8], "vmain") == 0);
CHECK([rf rgfxConstantCount] == 0);
CHECK([[fn name] isEqualToString:@"vmain"]);
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes)); // newFunctionWithName: posts nothing
// No function table: a stand-in hash, the same for the same function, another for
// another name.
id<MTLFunction> other = [lib newFunctionWithName:@"fmain"];
CHECK(std::memcmp([rf bitCodeHash]->bytes, [(RgfxFunction *)[lib newFunctionWithName:@"vmain"]
bitCodeHash]->bytes, 32) == 0);
CHECK(std::memcmp([rf bitCodeHash]->bytes, [(RgfxFunction *)other bitCodeHash]->bytes, 32) != 0);
// A .metallib's function list: its entry's stage from TYPE and its hash from HASH.
std::vector<uint8_t> metallib(0x30, 0);
std::memcpy(metallib.data(), "MTLB", 4);
metallib[0x18] = 0x30; // the function list's offset
auto put32 = [&](uint32_t v) {
for (int i = 0; i < 4; i++)
metallib.push_back(static_cast<uint8_t>(v >> (8 * i)));
};
auto tag = [&](const char *name, const uint8_t *data, uint16_t size) {
metallib.insert(metallib.end(), name, name + 4);
metallib.push_back(static_cast<uint8_t>(size));
metallib.push_back(static_cast<uint8_t>(size >> 8));
metallib.insert(metallib.end(), data, data + size);
};
uint8_t hash[32];
for (int i = 0; i < 32; i++)
hash[i] = static_cast<uint8_t>(0xa0 + i);
const uint8_t stage = 2; // a kernel
put32(1);
put32(4 + (6 + 6) + (6 + 1) + (6 + 32) + 4);
tag("NAME", reinterpret_cast<const uint8_t *>("kmain"), 6);
tag("TYPE", &stage, 1);
tag("HASH", hash, 32);
metallib.insert(metallib.end(), {'E', 'N', 'D', 'T'});
RgfxLibrary *tabled = [RgfxLibrary libraryWithData:metallib.data()
length:metallib.size()
key:nullptr
device:nil
serializer:&fx.ser
status:&libStatus];
CHECK(tabled != nil);
RgfxFunction *k = (RgfxFunction *)[tabled newFunctionWithName:@"kmain"];
CHECK(k != nil && k.functionType == MTLFunctionTypeKernel);
CHECK(std::memcmp([k bitCodeHash]->bytes, hash, 32) == 0);
CHECK([tabled newFunctionWithName:@"vmain"] == nil);
while (fx.ring.next(&extra, &extraBytes)) {
}
// A library with no route cannot be created.
RgfxLibrary *none = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:nullptr
status:&libStatus];
CHECK(none == nil);
}
// A render pipeline create maps the MTLRenderPipelineDescriptor into the wire: the
// functions, label, colour attachment, flags and vertex descriptor; the wrapper
// holds objId + seqno and answers reflection getters with documented placeholders.
void test_render_pipeline_routing()
{
Fixture fx;
const uint8_t libBytes[] = {1, 2, 3, 4};
uint32_t libStatus = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&libStatus];
(void)nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE); // drain the library create
id<MTLFunction> vfn = [lib newFunctionWithName:@"vmain"];
id<MTLFunction> ffn = [lib newFunctionWithName:@"fmain"];
MTLRenderPipelineDescriptor *desc = [[MTLRenderPipelineDescriptor alloc] init];
desc.vertexFunction = vfn;
desc.fragmentFunction = ffn;
desc.label = @"pipe";
desc.rasterSampleCount = 4;
desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
desc.colorAttachments[0].blendingEnabled = YES;
desc.colorAttachments[0].sourceRGBBlendFactor = MTLBlendFactorSourceAlpha;
desc.colorAttachments[0].destinationRGBBlendFactor = MTLBlendFactorOneMinusSourceAlpha;
desc.depthAttachmentPixelFormat = MTLPixelFormatDepth32Float;
desc.alphaToCoverageEnabled = YES;
desc.supportIndirectCommandBuffers = YES;
desc.vertexLinkedFunctions.functions = @[ [lib newFunctionWithName:@"vlink"] ];
desc.fragmentLinkedFunctions.privateFunctions = @[ [lib newFunctionWithName:@"flink"] ];
MTLVertexDescriptor *vd = [MTLVertexDescriptor vertexDescriptor];
vd.layouts[0].stride = 32;
vd.layouts[0].stepFunction = MTLVertexStepFunctionPerVertex;
vd.layouts[0].stepRate = 1;
vd.attributes[0].format = MTLVertexFormatFloat3;
vd.attributes[0].offset = 0;
vd.attributes[0].bufferIndex = 0;
desc.vertexDescriptor = vd;
NSError *err = nil;
RgfxRenderPipelineState *ps =
[RgfxRenderPipelineState renderPipelineStateWithDescriptor:desc
device:nil
serializer:&fx.ser
error:&err];
CHECK(ps != nil);
CHECK(err == nil);
CHECK(ps.rgfxObjId == 2); // library was objId 1, the pipeline the next
CHECK(ps.rgfxSeqno == 2); // library post was seqno 1, the pipeline the next
CHECK([ps conformsToProtocol:@protocol(MTLRenderPipelineState)]);
auto bytes = nextMessage(fx.ring, RGFX_CMD_RENDER_PIPELINE_CREATE);
RgfxRenderPipelineCreate head;
std::memcpy(&head, bytes.data(), sizeof(head));
CHECK(head.obj_id == ps.rgfxObjId);
CHECK(head.vertex_library_obj_id == lib.rgfxObjId);
CHECK(head.fragment_library_obj_id == lib.rgfxObjId);
CHECK(head.raster_sample_count == 4);
CHECK(head.color_attachment_count == 1);
CHECK(head.colors[0].pixel_format == static_cast<uint32_t>(MTLPixelFormatBGRA8Unorm));
CHECK(head.colors[0].blending_enabled == 1);
CHECK(head.colors[0].source_rgb_blend_factor == static_cast<uint32_t>(MTLBlendFactorSourceAlpha));
CHECK(head.colors[0].destination_rgb_blend_factor ==
static_cast<uint32_t>(MTLBlendFactorOneMinusSourceAlpha));
CHECK(head.depth_pixel_format == static_cast<uint32_t>(MTLPixelFormatDepth32Float));
CHECK((head.flags & RGFX_RENDER_PIPELINE_ALPHA_TO_COVERAGE) != 0);
CHECK((head.flags & RGFX_RENDER_PIPELINE_RASTERIZATION_ENABLED) != 0); // default on
CHECK((head.flags & RGFX_RENDER_PIPELINE_SUPPORT_ICB) != 0);
// Each stage's linked functions, in their lists.
CHECK(head.vertex_linked_count == 1 && head.fragment_linked_count == 1);
RgfxLinkedFunction vlink, flink;
std::memcpy(&vlink, bytes.data() + head.vertex_linked_offset, sizeof(vlink));
std::memcpy(&flink, bytes.data() + head.fragment_linked_offset, sizeof(flink));
CHECK(vlink.list == RGFX_LINKED_FUNCTIONS && vlink.name_len == 5);
CHECK(std::memcmp(bytes.data() + vlink.name_offset, "vlink", 5) == 0);
CHECK(flink.list == RGFX_LINKED_PRIVATE_FUNCTIONS && flink.name_len == 5);
CHECK(std::memcmp(bytes.data() + flink.name_offset, "flink", 5) == 0);
CHECK(vlink.library_obj_id == lib.rgfxObjId && flink.library_obj_id == lib.rgfxObjId);
// The functions, label and vertex descriptor are in the tail at their offsets.
CHECK(head.vertex_name_len == 5);
CHECK(std::memcmp(bytes.data() + head.vertex_name_offset, "vmain", 5) == 0);
CHECK(head.fragment_name_len == 5);
CHECK(std::memcmp(bytes.data() + head.fragment_name_offset, "fmain", 5) == 0);
CHECK(head.label_len == 4);
CHECK(std::memcmp(bytes.data() + head.label_offset, "pipe", 4) == 0);
CHECK(head.vertex_layout_count == 1);
RgfxVertexBufferLayout vl;
std::memcpy(&vl, bytes.data() + head.vertex_layouts_offset, sizeof(vl));
CHECK(vl.buffer_index == 0);
CHECK(vl.stride == 32);
CHECK(vl.step_function == static_cast<uint32_t>(MTLVertexStepFunctionPerVertex));
CHECK(head.vertex_attribute_count == 1);
RgfxVertexAttribute va;
std::memcpy(&va, bytes.data() + head.vertex_attributes_offset, sizeof(va));
CHECK(va.attribute_index == 0);
CHECK(va.format == static_cast<uint32_t>(MTLVertexFormatFloat3));
CHECK(va.buffer_index == 0);
// Reflection getters are documented placeholders until the reply reader lands.
CHECK([ps maxTotalThreadsPerThreadgroup] == 1024);
CHECK(ps.gpuResourceID._impl == 0);
// No serialiser route is a refusal with an error.
NSError *err2 = nil;
RgfxRenderPipelineState *noRoute =
[RgfxRenderPipelineState renderPipelineStateWithDescriptor:desc
device:nil
serializer:nullptr
error:&err2];
CHECK(noRoute == nil);
CHECK(err2 != nil);
}
// A compute pipeline create maps the function (and the descriptor knobs) into the
// wire; the wrapper holds objId + seqno.
void test_compute_pipeline_routing()
{
Fixture fx;
const uint8_t libBytes[] = {9, 9, 9};
uint32_t libStatus = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&libStatus];
(void)nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE);
id<MTLFunction> kfn = [lib newFunctionWithName:@"kmain"];
NSError *err = nil;
RgfxComputePipelineState *cs =
[RgfxComputePipelineState computePipelineStateWithFunction:kfn
device:nil
serializer:&fx.ser
error:&err];
CHECK(cs != nil);
CHECK(err == nil);
CHECK(cs.rgfxObjId == 2);
CHECK(cs.rgfxSeqno == 2);
auto bytes = nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
RgfxComputePipelineCreate head;
std::memcpy(&head, bytes.data(), sizeof(head));
CHECK(head.obj_id == cs.rgfxObjId);
CHECK(head.function_library_obj_id == lib.rgfxObjId);
CHECK(head.name_len == 5);
CHECK(std::memcmp(bytes.data() + head.name_offset, "kmain", 5) == 0);
CHECK(head.flags == 0);
CHECK(head.max_call_stack_depth == 1); // Metal's default
CHECK(head.stage_input_layout_count == 0 && head.stage_input_attribute_count == 0);
CHECK(head.linked_count == 0);
CHECK([cs threadExecutionWidth] == 32); // documented placeholder
CHECK([cs maxTotalThreadsPerThreadgroup] == 1024); // documented placeholder
// The descriptor variant carries the ICB/exec-width flags and the thread cap.
MTLComputePipelineDescriptor *desc = [[MTLComputePipelineDescriptor alloc] init];
desc.computeFunction = kfn;
desc.threadGroupSizeIsMultipleOfThreadExecutionWidth = YES;
desc.maxTotalThreadsPerThreadgroup = 256;
NSError *err2 = nil;
RgfxComputePipelineState *cs2 =
[RgfxComputePipelineState computePipelineStateWithDescriptor:desc
device:nil
serializer:&fx.ser
error:&err2];
CHECK(cs2 != nil);
CHECK(err2 == nil);
auto bytes2 = nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
RgfxComputePipelineCreate head2;
std::memcpy(&head2, bytes2.data(), sizeof(head2));
CHECK((head2.flags & RGFX_COMPUTE_PIPELINE_TG_MULTIPLE_OF_EXEC_WIDTH) != 0);
CHECK(head2.max_total_threads_per_threadgroup == 256);
// The stage-input descriptor's layouts and attributes in use, its index type and buffer,
// the call stack depth, and the linked functions in their lists, a function made by
// descriptor with its options, and one with a specialized name, which it answers, under
// its entry point.
MTLFunctionDescriptor *fd = [MTLFunctionDescriptor functionDescriptor];
fd.name = @"bin";
fd.options = MTLFunctionOptionCompileToBinary;
id<MTLFunction> binary = [lib newFunctionWithDescriptor:fd error:nil];
CHECK(binary.options == MTLFunctionOptionCompileToBinary);
CHECK([binary.name isEqualToString:@"bin"]);
MTLFunctionDescriptor *pd = [MTLFunctionDescriptor functionDescriptor];
pd.name = @"fp";
pd.specializedName = @"custom_fn";
id<MTLFunction> specialized = [lib newFunctionWithDescriptor:pd error:nil];
CHECK([specialized.name isEqualToString:@"custom_fn"]);
MTLComputePipelineDescriptor *whole = [[MTLComputePipelineDescriptor alloc] init];
whole.computeFunction = kfn;
whole.maxCallStackDepth = 3;
MTLStageInputOutputDescriptor *sd = [MTLStageInputOutputDescriptor stageInputOutputDescriptor];
sd.layouts[2].stride = 8;
sd.layouts[2].stepFunction = MTLStepFunctionThreadPositionInGridX;
sd.attributes[1].format = MTLAttributeFormatFloat2;
sd.attributes[1].bufferIndex = 2;
sd.indexType = MTLIndexTypeUInt32;
sd.indexBufferIndex = 5;
whole.stageInputDescriptor = sd;
MTLLinkedFunctions *linked = [MTLLinkedFunctions linkedFunctions];
linked.functions = @[ [lib newFunctionWithName:@"fa"] ];
linked.binaryFunctions = @[ binary ];
linked.groups = @{
@"zeta" : @[ [lib newFunctionWithName:@"gz"] ],
@"alpha" : @[ [lib newFunctionWithName:@"ga"], [lib newFunctionWithName:@"gb"] ],
};
linked.privateFunctions = @[ specialized ];
whole.linkedFunctions = linked;
RgfxComputePipelineState *cs4 =
[RgfxComputePipelineState computePipelineStateWithDescriptor:whole
device:nil
serializer:&fx.ser
error:nil];
CHECK(cs4 != nil);
auto bytes4 = nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
RgfxComputePipelineCreate head4;
std::memcpy(&head4, bytes4.data(), sizeof(head4));
CHECK(head4.max_call_stack_depth == 3);
CHECK(head4.stage_input_layout_count == 1);
RgfxVertexBufferLayout sl;
std::memcpy(&sl, bytes4.data() + head4.stage_input_layouts_offset, sizeof(sl));
CHECK(sl.buffer_index == 2 && sl.stride == 8);
CHECK(sl.step_function == static_cast<uint32_t>(MTLStepFunctionThreadPositionInGridX));
CHECK(head4.stage_input_attribute_count == 1);
RgfxVertexAttribute sa;
std::memcpy(&sa, bytes4.data() + head4.stage_input_attributes_offset, sizeof(sa));
CHECK(sa.attribute_index == 1 && sa.buffer_index == 2);
CHECK(sa.format == static_cast<uint32_t>(MTLAttributeFormatFloat2));
CHECK(head4.stage_input_index_type == static_cast<uint32_t>(MTLIndexTypeUInt32));
CHECK(head4.stage_input_index_buffer_index == 5);
CHECK(head4.linked_count == 6);
struct Want {
const char *name;
uint32_t list;
uint32_t options;
const char *group;
const char *specialized;
};
const Want want[6] = {
{"fa", RGFX_LINKED_FUNCTIONS, 0, "", ""},
{"bin", RGFX_LINKED_BINARY_FUNCTIONS, MTLFunctionOptionCompileToBinary, "", ""},
{"ga", RGFX_LINKED_GROUP, 0, "alpha", ""},
{"gb", RGFX_LINKED_GROUP, 0, "alpha", ""},
{"gz", RGFX_LINKED_GROUP, 0, "zeta", ""},
{"fp", RGFX_LINKED_PRIVATE_FUNCTIONS, 0, "", "custom_fn"},
};
for (uint32_t i = 0; i < 6; i++) {
RgfxLinkedFunction r;
std::memcpy(&r, bytes4.data() + head4.linked_offset + i * sizeof(r), sizeof(r));
CHECK(r.library_obj_id == lib.rgfxObjId);
CHECK(r.name_len == std::strlen(want[i].name));
CHECK(std::memcmp(bytes4.data() + r.name_offset, want[i].name, r.name_len) == 0);
CHECK(r.list == want[i].list);
CHECK(r.options == want[i].options);
CHECK(r.group_len == std::strlen(want[i].group));
CHECK(std::memcmp(bytes4.data() + r.group_offset, want[i].group, r.group_len) == 0);
CHECK(r.specialized_name_len == std::strlen(want[i].specialized));
CHECK((r.specialized_name_offset == 0) == (r.specialized_name_len == 0));
CHECK(std::memcmp(bytes4.data() + r.specialized_name_offset, want[i].specialized,
r.specialized_name_len) == 0);
}
// A linked function another device's library made is refused before anything is sent:
// the next create is the one the ring holds next.
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
id<MTLLibrary> real =
[metal newLibraryWithSource:@"[[visible]] int f(int x) { return x + 1; }" options:nil error:nil];
id<MTLFunction> foreign = [real newFunctionWithName:@"f"];
CHECK(foreign != nil);
MTLLinkedFunctions *other = [MTLLinkedFunctions linkedFunctions];
other.privateFunctions = @[ foreign ];
whole.linkedFunctions = other;
NSError *foreignErr = nil;
CHECK([RgfxComputePipelineState computePipelineStateWithDescriptor:whole
device:nil
serializer:&fx.ser
error:&foreignErr] == nil);
CHECK(foreignErr.code == RgfxMetalErrorInvalidDescriptor);
whole.linkedFunctions = nil;
RgfxComputePipelineState *after =
[RgfxComputePipelineState computePipelineStateWithDescriptor:whole
device:nil
serializer:&fx.ser
error:nil];
auto bytes5 = nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
RgfxComputePipelineCreate head5;
std::memcpy(&head5, bytes5.data(), sizeof(head5));
CHECK(head5.obj_id == after.rgfxObjId);
CHECK(head5.linked_count == 0);
// A compute create with no function is a refusal with an error. (The nil goes
// through a variable so the nonnull parameter's literal-nil diagnostic does not
// fire; a guest can still reach this path with a nil id at runtime.)
NSError *err3 = nil;
id<MTLFunction> nilFn = nil;
RgfxComputePipelineState *noFn =
[RgfxComputePipelineState computePipelineStateWithFunction:nilFn
device:nil
serializer:&fx.ser
error:&err3];
CHECK(noFn == nil);
CHECK(err3 != nil);
}
// One function of a test .metallib: its entry point, its stage (the TYPE tag's byte: 0
// vertex, 1 fragment, 2 kernel) and the constants its public metadata declares.
struct TestFunction {
const char *name;
uint8_t stage;
std::vector<RgfxConstantDecl> constants;
};
void put16(std::vector<uint8_t> &v, uint16_t x) { v.insert(v.end(), (uint8_t *)&x, (uint8_t *)&x + 2); }
void put32(std::vector<uint8_t> &v, uint32_t x) { v.insert(v.end(), (uint8_t *)&x, (uint8_t *)&x + 4); }
void put64(std::vector<uint8_t> &v, uint64_t x) { v.insert(v.end(), (uint8_t *)&x, (uint8_t *)&x + 8); }
// A tag: its four-character name, a u16 size and the data.
void putTag(std::vector<uint8_t> &v, const char *name, const std::vector<uint8_t> &data)
{
v.insert(v.end(), name, name + 4);
put16(v, static_cast<uint16_t>(data.size()));
v.insert(v.end(), data.begin(), data.end());
}
// A .metallib of `functions` in the layout Apple's compiler writes (measured: macOS 27's
// `metal`): the header's function list offset and size at 0x18, its public metadata's at 0x28;
// per function a group of tags (NAME, TYPE, OFFT, whose first field places the function's
// entry in the public metadata), and per function a public entry (its size, then a CNST tag
// where it declares constants: a u16 count, then each name, MTLDataType byte, u16 index and
// required byte), whose size counts itself where `sizeCountsItself` (macOS 27's) and not
// otherwise (macOS 26's). No bitcode: the shell never reads it.
std::vector<uint8_t> metallibOf(const std::vector<TestFunction> &functions,
bool sizeCountsItself = true)
{
std::vector<uint8_t> list, pub;
put32(list, static_cast<uint32_t>(functions.size()));
for (const TestFunction &f : functions) {
std::vector<uint8_t> entry;
put32(entry, 0);
if (!f.constants.empty()) {
std::vector<uint8_t> cnst;
put16(cnst, static_cast<uint16_t>(f.constants.size()));
for (const RgfxConstantDecl &d : f.constants) {
cnst.insert(cnst.end(), d.name.begin(), d.name.end());
cnst.push_back(0);
cnst.push_back(static_cast<uint8_t>(d.type));
put16(cnst, static_cast<uint16_t>(d.index));
cnst.push_back(d.required ? 1 : 0);
}
putTag(entry, "CNST", cnst);
}
entry.insert(entry.end(), { 'E', 'N', 'D', 'T' });
uint32_t entrySize = static_cast<uint32_t>(entry.size() - (sizeCountsItself ? 0 : 4));
std::memcpy(entry.data(), &entrySize, 4);
std::vector<uint8_t> group, offt;
put32(group, 0);
std::vector<uint8_t> name(f.name, f.name + std::strlen(f.name) + 1);
putTag(group, "NAME", name);
putTag(group, "TYPE", { f.stage });
put64(offt, pub.size());
put64(offt, 0);
put64(offt, 0);
putTag(group, "OFFT", offt);
group.insert(group.end(), { 'E', 'N', 'D', 'T' });
uint32_t groupSize = static_cast<uint32_t>(group.size());
std::memcpy(group.data(), &groupSize, 4);
list.insert(list.end(), group.begin(), group.end());
pub.insert(pub.end(), entry.begin(), entry.end());
}
std::vector<uint8_t> out(0x58, 0);
std::memcpy(out.data(), "MTLB", 4);
uint64_t fields[4] = { 0x58, list.size(), 0x58 + list.size(), pub.size() };
std::memcpy(out.data() + 0x18, fields, sizeof(fields));
out.insert(out.end(), list.begin(), list.end());
out.insert(out.end(), pub.begin(), pub.end());
return out;
}
// The constant `function` carries at `index`, or null.
const RgfxFunctionConstant *constantAt(id<MTLFunction> function, uint32_t index)
{
RgfxFunction *rf = (RgfxFunction *)function;
for (uint32_t i = 0; i < [rf rgfxConstantCount]; i++) {
if ([rf rgfxConstants][i].index == index)
return &[rf rgfxConstants][i];
}
return nullptr;
}
// A stitched library is Metal's own, stitched over the shadows of our functions and of no binary
// archive, and made ours from the bytes Metal answers for it: its functions are the graphs'.
void test_stitched_library_over_shadows()
{
Fixture fx;
const char *path = getenv("RGFX_STITCHABLE");
CHECK(path != nullptr);
if (path == nullptr)
return;
NSData *bytes = [NSData dataWithContentsOfFile:@(path)];
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
auto make = [&](const void *p, size_t n) {
uint32_t status = 0;
return [RgfxLibrary libraryWithData:p
length:n
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
};
RgfxLibrary *lib = make(bytes.bytes, bytes.length);
[lib rgfxSetSource:dispatch_data_create(bytes.bytes, bytes.length, nil, ^{
(void)bytes;
})
shadowMaker:^id<MTLLibrary>(dispatch_data_t d) {
return [metal newLibraryWithData:d error:nil];
}];
// A function's reflection is the shadow's, Metal's own answer (for this library, none), with
// no unsupported use; a library with no shadow answers none, as unsupported.
SEL reflect = @selector(reflectionForFunctionWithName:);
MTLFunctionReflection *reflected = [lib reflectionForFunctionWithName:@"stitch_caller"];
MTLFunctionReflection *metals =
[[lib rgfxShadow] reflectionForFunctionWithName:@"stitch_caller"];
CHECK((reflected == nil) == (metals == nil) && reflected.bindings.count == metals.bindings.count);
CHECK(!RgfxUnsupportedWasLogged([RgfxLibrary class], reflect));
CHECK([make(bytes.bytes, bytes.length) reflectionForFunctionWithName:@"stitch_caller"] == nil);
CHECK(RgfxUnsupportedWasLogged([RgfxLibrary class], reflect));
id<MTLFunction> add = [lib newFunctionWithName:@"stitch_add"];
id<MTLFunction> mul = [lib newFunctionWithName:@"stitch_mul"];
CHECK([(id)add isKindOfClass:[RgfxFunction class]] && [(RgfxFunction *)add rgfxShadow] == nil);
MTLFunctionStitchingInputNode *a = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:0];
MTLFunctionStitchingInputNode *b = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:1];
MTLFunctionStitchingInputNode *c = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:2];
MTLFunctionStitchingFunctionNode *sum =
[[MTLFunctionStitchingFunctionNode alloc] initWithName:@"stitch_add"
arguments:@[ a, b ]
controlDependencies:@[]];
MTLFunctionStitchingFunctionNode *product =
[[MTLFunctionStitchingFunctionNode alloc] initWithName:@"stitch_mul"
arguments:@[ sum, c ]
controlDependencies:@[]];
MTLStitchedLibraryDescriptor *d = [[MTLStitchedLibraryDescriptor alloc] init];
d.functionGraphs = @[ [[MTLFunctionStitchingGraph alloc] initWithFunctionName:@"fused"
nodes:@[ sum ]
outputNode:product
attributes:@[]] ];
d.functions = @[ add, mul ];
d.binaryArchives = @[ [metal newBinaryArchiveWithDescriptor:[MTLBinaryArchiveDescriptor new] error:nil] ];
__block MTLStitchedLibraryDescriptor *given = nil;
__block id<MTLLibrary> stitched = nil;
NSError *err = nil;
id<MTLLibrary> ours = RgfxStitchOverShadows(
d, nil,
^id<MTLLibrary>(MTLStitchedLibraryDescriptor *shadowed, NSError **e) {
given = shadowed;
stitched = [metal newLibraryWithStitchedDescriptor:shadowed error:e];
return stitched;
},
^id<MTLLibrary>(dispatch_data_t data, NSError **e) {
const void *p = nullptr;
size_t n = 0;
dispatch_data_t map = dispatch_data_create_map(data, &p, &n);
(void)map;
return make(p, n);
},
&err);
CHECK(err == nil && stitched != nil);
CHECK(given != d && given.binaryArchives.count == 0 && d.binaryArchives.count == 1);
CHECK(given.functions.count == 2 && given.functions[0] == [(RgfxFunction *)add rgfxShadow] &&
given.functions[1] == [(RgfxFunction *)mul rgfxShadow]);
CHECK(![(id)given.functions[0] isKindOfClass:[RgfxFunction class]]);
CHECK(d.functions[0] == add); // the caller's descriptor is unchanged
CHECK([(id)ours isKindOfClass:[RgfxLibrary class]]);
CHECK([[ours functionNames] isEqualToArray:@[ @"fused" ]]);
CHECK([(RgfxLibrary *)ours rgfxShadow] == stitched);
CHECK([ours newFunctionWithName:@"fused"].functionType == MTLFunctionTypeVisible);
std::vector<uint8_t> drain;
RgfxMsgHeader h;
while (fx.ring.next(&h, &drain)) {
}
}
// A stitched library of a DAG (newLibraryWithDAG:functions:error:, SkyLight's and MPS's) is
// Metal's own over the functions' shadows too: its text is Metal's to read, and its answer, here
// Metal's parser's error, is the guest's, with nothing sent to the host.
void test_stitched_dag_over_shadows()
{
Fixture fx;
const char *path = getenv("RGFX_STITCHABLE");
CHECK(path != nullptr);
if (path == nullptr)
return;
NSData *bytes = [NSData dataWithContentsOfFile:@(path)];
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
uint32_t status = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:bytes.bytes
length:bytes.length
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
[lib rgfxSetSource:dispatch_data_create(bytes.bytes, bytes.length, nil, ^{
(void)bytes;
})
shadowMaker:^id<MTLLibrary>(dispatch_data_t d) {
return [metal newLibraryWithData:d error:nil];
}];
id<MTLFunction> add = [lib newFunctionWithName:@"stitch_add"];
id<MTLFunction> mul = [lib newFunctionWithName:@"stitch_mul"];
std::vector<uint8_t> drain;
RgfxMsgHeader h;
while (fx.ring.next(&h, &drain)) {
}
__block NSArray<id<MTLFunction>> *given = nil;
__block NSError *metals = nil;
NSError *err = nil;
id<MTLLibrary> ours = RgfxLinkOverShadows(
@[ add, mul ],
^id<MTLLibrary>(NSArray<id<MTLFunction>> *shadows, NSError **e) {
given = shadows;
id<MTLLibrary> made = [(IOGPUMetalDevice *)metal newLibraryWithDAG:@"fused" functions:shadows error:e];
metals = *e;
return made;
},
^id<MTLLibrary>(dispatch_data_t, NSError **) {
CHECK(false); // nothing to make of no library
return nil;
},
&err);
CHECK(ours == nil && metals != nil && err == metals);
CHECK([err.domain isEqualToString:MTLLibraryErrorDomain] && err.code == MTLLibraryErrorCompileFailure);
CHECK([err.localizedDescription hasPrefix:@"error while parsing script: "]);
CHECK(given.count == 2 && given[0] == [(RgfxFunction *)add rgfxShadow] &&
given[1] == [(RgfxFunction *)mul rgfxShadow] && given[0] != nil);
CHECK(!fx.ring.next(&h, &drain));
}
} // namespace
// A device that stitches as ours does (RgfxStitchOverShadows), on Metal's own stitch, making its
// libraries with `make`: what an archive adds a stitched library through.
@interface StitchingDevice : NSObject <RgfxStitchingDevice>
@property(nonatomic, strong) id<MTLDevice> metal;
@property(nonatomic, copy) RgfxLibraryMaker make;
@property(nonatomic) int stitches;
@end
@implementation StitchingDevice
- (id<MTLLibrary>)newLibraryWithStitchedDescriptor:(MTLStitchedLibraryDescriptor *)descriptor
destinationBinaryArchive:(id<MTLBinaryArchive>)archive
error:(NSError **)error
{
return RgfxStitchOverShadows(
descriptor, archive,
^id<MTLLibrary>(MTLStitchedLibraryDescriptor *shadowed, NSError **e) {
self.stitches++;
return [self.metal newLibraryWithStitchedDescriptor:shadowed error:e];
},
self.make, error);
}
@end
namespace {
// A stitched library kept in a binary archive is found as Metal's archive finds one (measured:
// macOS 27, M3 Max): a create that fails on a miss is made where an archive of the descriptor
// holds the same graphs over the same functions, in any order and of any library over the same
// bytes, and otherwise answers Metal's error with nothing stitched; another graph name, swapped
// arguments or another attribute miss. The archive holds it in no key and writes it to no file. An
// archive adds one by stitching it on its device into itself, answering Metal's error for a graph
// Metal cannot stitch, and for a descriptor that fails on a miss and that no archive holds.
void test_stitched_libraries_in_archives()
{
Fixture fx;
const char *path = getenv("RGFX_STITCHABLE");
CHECK(path != nullptr);
if (path == nullptr)
return;
NSData *bytes = [NSData dataWithContentsOfFile:@(path)];
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
auto make = [&](const void *p, size_t n) {
uint32_t status = 0;
return [RgfxLibrary libraryWithData:p
length:n
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
};
auto drain = [&] {
std::vector<uint8_t> b;
RgfxMsgHeader h;
while (fx.ring.next(&h, &b)) {
}
};
auto source = [&](RgfxLibrary *lib) {
[lib rgfxSetSource:dispatch_data_create(bytes.bytes, bytes.length, nil, ^{
(void)bytes;
})
shadowMaker:^id<MTLLibrary>(dispatch_data_t d) {
return [metal newLibraryWithData:d error:nil];
}];
return lib;
};
RgfxLibrary *lib = source(make(bytes.bytes, bytes.length));
RgfxLibrary *again = source(make(bytes.bytes, bytes.length));
drain();
auto graph = [](NSString *name, bool swapped, NSArray *attributes) {
MTLFunctionStitchingInputNode *a = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:0];
MTLFunctionStitchingInputNode *b = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:1];
MTLFunctionStitchingInputNode *c = [[MTLFunctionStitchingInputNode alloc] initWithArgumentIndex:2];
MTLFunctionStitchingFunctionNode *sum =
[[MTLFunctionStitchingFunctionNode alloc] initWithName:@"stitch_add"
arguments:@[ a, b ]
controlDependencies:@[]];
NSArray *last = swapped ? @[ c, sum ] : @[ sum, c ];
MTLFunctionStitchingFunctionNode *product =
[[MTLFunctionStitchingFunctionNode alloc] initWithName:@"stitch_mul"
arguments:last
controlDependencies:@[]];
return [[MTLFunctionStitchingGraph alloc] initWithFunctionName:name
nodes:@[ sum ]
outputNode:product
attributes:attributes];
};
auto descriptor = [&](RgfxLibrary *from, MTLFunctionStitchingGraph *g, NSArray *archives, bool reversed) {
MTLStitchedLibraryDescriptor *d = [[MTLStitchedLibraryDescriptor alloc] init];
id<MTLFunction> add = [from newFunctionWithName:@"stitch_add"];
id<MTLFunction> mul = [from newFunctionWithName:@"stitch_mul"];
d.functions = reversed ? @[ mul, add ] : @[ add, mul ];
d.functionGraphs = @[ g ];
d.binaryArchives = archives;
d.options = MTLStitchedLibraryOptionFailOnBinaryArchiveMiss;
return d;
};
StitchingDevice *device = [StitchingDevice new];
device.metal = metal;
device.make = ^id<MTLLibrary>(dispatch_data_t data, NSError **e) {
const void *p = nullptr;
size_t n = 0;
dispatch_data_t map = dispatch_data_create_map(data, &p, &n);
(void)map;
return make(p, n);
};
NSError *err = nil;
RgfxBinaryArchive *archive = [RgfxBinaryArchive archiveWithDescriptor:[MTLBinaryArchiveDescriptor new]
device:(id<MTLDevice>)device
architecture:@"arch_a"
error:&err];
CHECK(archive != nil);
auto create = [&](MTLStitchedLibraryDescriptor *d, NSError **e) {
return [device newLibraryWithStitchedDescriptor:d destinationBinaryArchive:nil error:e];
};
auto missed = [&](MTLStitchedLibraryDescriptor *d) {
NSError *e = nil;
const int before = device.stitches;
id<MTLLibrary> made = create(d, &e);
return made == nil && device.stitches == before && [e.domain isEqualToString:MTLLibraryErrorDomain] &&
e.code == MTLLibraryErrorCompileFailure &&
[e.localizedDescription isEqualToString:@"Failed to find library in binary archive."];
};
MTLFunctionStitchingGraph *fused = graph(@"fused", false, @[]);
CHECK(missed(descriptor(lib, fused, @[], false)));
CHECK(missed(descriptor(lib, fused, nil, false)));
CHECK(missed(descriptor(lib, fused, @[ archive ], false)));
// An add that fails on a miss misses too, and keeps nothing.
err = nil;
CHECK(![archive addLibraryWithDescriptor:descriptor(lib, fused, @[ archive ], false) error:&err]);
CHECK([err.localizedDescription isEqualToString:@"Failed to find library in binary archive."]);
CHECK(device.stitches == 0 && missed(descriptor(lib, fused, @[ archive ], false)));
// Added: stitched on the device into the archive, then found.
MTLStitchedLibraryDescriptor *plain = descriptor(lib, fused, @[], false);
plain.options = 0;
CHECK([archive addLibraryWithDescriptor:plain error:&err] && err == nil && device.stitches == 1);
drain();
id<MTLLibrary> found = create(descriptor(lib, fused, @[ archive ], false), &err);
CHECK([(id)found isKindOfClass:[RgfxLibrary class]] && [[found functionNames] isEqualToArray:@[ @"fused" ]]);
CHECK(device.stitches == 2);
drain();
CHECK(create(descriptor(lib, fused, @[ archive ], true), &err) != nil);
CHECK(create(descriptor(again, fused, @[ archive ], false), &err) != nil);
drain();
CHECK(missed(descriptor(lib, graph(@"other", false, @[]), @[ archive ], false)));
CHECK(missed(descriptor(lib, graph(@"fused", true, @[]), @[ archive ], false)));
CHECK(missed(descriptor(lib, graph(@"fused", false, @[ [MTLFunctionStitchingAttributeAlwaysInline new] ]),
@[ archive ], false)));
// Kept in no key and in no file.
CHECK(archive.keys.count == 0);
NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory()
stringByAppendingPathComponent:@"rgfx-stitched-archive.bin"]];
CHECK(![archive serializeToURL:url error:&err]);
CHECK([err.localizedDescription isEqualToString:@"Nothing to serialize"]);
// A graph Metal cannot stitch is not added, with Metal's error.
MTLFunctionStitchingFunctionNode *missing =
[[MTLFunctionStitchingFunctionNode alloc] initWithName:@"nope" arguments:@[] controlDependencies:@[]];
MTLStitchedLibraryDescriptor *bad = descriptor(lib, fused, @[], false);
bad.options = 0;
bad.functionGraphs = @[ [[MTLFunctionStitchingGraph alloc] initWithFunctionName:@"bad"
nodes:@[]
outputNode:missing
attributes:@[]] ];
err = nil;
CHECK(![archive addLibraryWithDescriptor:bad error:&err]);
CHECK([err.domain isEqualToString:MTLLibraryErrorDomain] && err.code == MTLLibraryErrorCompileFailure &&
[err.localizedDescription containsString:@"missing function 'nope' required by DAG 'bad'"]);
// An archive with no device to stitch on adds none.
RgfxBinaryArchive *alone = [RgfxBinaryArchive archiveWithDescriptor:[MTLBinaryArchiveDescriptor new]
device:nil
architecture:@"arch_a"
error:&err];
CHECK(![alone addLibraryWithDescriptor:plain error:&err] && err != nil);
drain();
}
// A function answers Metal's private members from its shadow, Metal's own function of the same
// entry point, made of its library's on first use: a stitchable function's bindings and return
// type, a kernel's nils, and each one's AIR. One made with constant values has no shadow: it
// answers nil for its constants, as Metal's, and nil, logged, for the rest. Its options are what
// it was last given, and its plugin data nil.
void test_function_members_from_shadow()
{
Fixture fx;
const char *path = getenv("RGFX_STITCHABLE");
CHECK(path != nullptr);
if (path == nullptr)
return;
NSData *bytes = [NSData dataWithContentsOfFile:@(path)];
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
uint32_t status = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:bytes.bytes
length:bytes.length
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
dispatch_data_t source = dispatch_data_create(bytes.bytes, bytes.length, nil, ^{
(void)bytes;
});
[lib rgfxSetSource:source
shadowMaker:^id<MTLLibrary>(dispatch_data_t d) {
return [metal newLibraryWithData:d error:nil];
}];
id<MTLLibrary> genuine = [metal newLibraryWithData:source error:nil];
auto ask = [](id object, NSString *member) {
return ((id (*)(id, SEL))objc_msgSend)(object, NSSelectorFromString(member));
};
for (NSString *name in @[ @"stitch_add", @"stitch_caller" ]) {
RgfxFunction *fn = (RgfxFunction *)[lib newFunctionWithName:name];
id<MTLFunction> theirs = [genuine newFunctionWithName:name];
CHECK(fn != nil && theirs != nil && [fn rgfxShadow] == nil);
NSArray *arguments = ask(fn, @"arguments"), *metals = ask(theirs, @"arguments");
CHECK((arguments == nil) == (metals == nil) && arguments.count == metals.count);
for (NSUInteger i = 0; i < arguments.count && i < metals.count; i++)
CHECK([[arguments[i] name] isEqualToString:[metals[i] name]]);
id type = ask(fn, @"returnType"), metalType = ask(theirs, @"returnType");
CHECK((type == nil) == (metalType == nil));
CHECK(type == nil || [type dataType] == [metalType dataType]);
CHECK(ask(fn, @"importedLibraries") == nil && ask(theirs, @"importedLibraries") == nil);
CHECK(ask(fn, @"functionConstants") == nil && ask(theirs, @"functionConstants") == nil);
id air = ask(fn, @"bitcodeData"), metalAir = ask(theirs, @"bitcodeData");
CHECK(air != nil && dispatch_data_get_size((dispatch_data_t)air) ==
dispatch_data_get_size((dispatch_data_t)metalAir));
CHECK([fn rgfxShadow] != nil && ![(id)[fn rgfxShadow] isKindOfClass:[RgfxFunction class]]);
CHECK(ask(fn, @"pluginData") == nil);
}
CHECK(((NSArray *)ask([lib newFunctionWithName:@"stitch_add"], @"arguments")).count == 2);
CHECK(ask([lib newFunctionWithName:@"stitch_add"], @"returnType") != nil);
CHECK(ask([lib newFunctionWithName:@"stitch_caller"], @"returnType") == nil);
RgfxFunctionConstant c = {};
c.data_type = static_cast<uint32_t>(MTLDataTypeFloat);
RgfxFunction *valued = [RgfxFunction functionWithLibrary:lib
name:@"stitch_caller"
constants:&c
count:1
device:nil
serializer:&fx.ser];
CHECK(ask(valued, @"functionConstants") == nil && ask(valued, @"bitcodeData") == nil);
CHECK([valued rgfxShadowOrMake] == nil);
CHECK(RgfxUnsupportedWasLogged([RgfxFunction class], NSSelectorFromString(@"bitcodeData")));
SEL setOptions = NSSelectorFromString(@"setOptions:");
CHECK(valued.options == MTLFunctionOptionNone && [valued respondsToSelector:setOptions]);
((void (*)(id, SEL, MTLFunctionOptions))objc_msgSend)(valued, setOptions,
MTLFunctionOptionCompileToBinary);
CHECK(valued.options == MTLFunctionOptionCompileToBinary);
std::vector<uint8_t> drain;
RgfxMsgHeader h;
while (fx.ring.next(&h, &drain)) {
}
}
// A library made from bytes answers nil for its bitcode, as Metal's, and is written by its shadow
// as the bytes it was made from, with Foundation's error for a URL it cannot write; one made from
// a URL is refused with Metal's error, and one with no shadow is refused, logged. (Metal's answers
// measured on macOS 27, M3 Max.)
void test_library_members_as_metal()
{
Fixture fx;
const char *path = getenv("RGFX_STITCHABLE");
CHECK(path != nullptr);
if (path == nullptr)
return;
NSData *bytes = [NSData dataWithContentsOfFile:@(path)];
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
auto make = [&]() {
uint32_t status = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:bytes.bytes
length:bytes.length
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
[lib rgfxSetSource:dispatch_data_create(bytes.bytes, bytes.length, nil, ^{
(void)bytes;
})
shadowMaker:^id<MTLLibrary>(dispatch_data_t d) {
return [metal newLibraryWithData:d error:nil];
}];
return lib;
};
NSString *dir = [NSTemporaryDirectory()
stringByAppendingPathComponent:[NSString stringWithFormat:@"rgfx-library-tests-%d", getpid()]];
[[NSFileManager defaultManager] createDirectoryAtPath:dir
withIntermediateDirectories:YES
attributes:nil
error:nil];
NSURL *out = [NSURL fileURLWithPath:[dir stringByAppendingPathComponent:@"out.metallib"]];
RgfxLibrary *lib = make();
CHECK([lib bitcodeData] == nil);
NSError *err = nil;
CHECK([lib serializeToURL:out error:&err] && err == nil);
CHECK([[NSData dataWithContentsOfURL:out] isEqualToData:bytes]);
CHECK([lib bitcodeData] == nil); // its shadow's, now made, is nil too
CHECK([lib serializeToURL:out error:&err]); // over the file it wrote
NSURL *missing = [NSURL fileURLWithPath:[dir stringByAppendingPathComponent:@"no/out.metallib"]];
CHECK(![lib serializeToURL:missing error:&err]);
CHECK([err.domain isEqualToString:NSCocoaErrorDomain] && err.code == NSFileNoSuchFileError);
err = nil;
CHECK(![lib serializeToURL:[NSURL URLWithString:@"https://example.invalid/out.metallib"]
error:&err]);
CHECK([err.domain isEqualToString:NSCocoaErrorDomain] &&
err.code == NSFileWriteUnsupportedSchemeError);
RgfxLibrary *fromURL = make();
[fromURL rgfxSetMadeFromURL];
err = nil;
CHECK(![fromURL serializeToURL:out error:&err]);
CHECK([err.domain isEqualToString:MTLLibraryErrorDomain] && err.code == MTLLibraryErrorUnsupported &&
[err.localizedDescription isEqualToString:@"MTLLibrary is not formatted as a MetalLib file."]);
CHECK([fromURL bitcodeData] == nil);
std::vector<uint8_t> drain;
RgfxMsgHeader h;
while (fx.ring.next(&h, &drain)) {
}
uint32_t status = 0;
RgfxLibrary *bare = [RgfxLibrary libraryWithData:bytes.bytes
length:bytes.length
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
CHECK(bare != nil);
err = nil;
CHECK(![bare serializeToURL:out error:&err] && [err.domain isEqualToString:MTLLibraryErrorDomain]);
CHECK(RgfxUnsupportedWasLogged([RgfxLibrary class], @selector(serializeToURL:error:)));
[[NSFileManager defaultManager] removeItemAtPath:dir error:nil];
while (fx.ring.next(&h, &drain)) {
}
}
// A Core Image kernel library's extern functions come from its shadow, Metal's own library over
// the same bytes: their names, each a function of functionType 4 that holds Metal's own, and nil
// for a name the shadow does not hold; functionNames leaves them out, as Metal's does. Core
// Image's link hands Metal each function's shadow, and makes the library Metal's link answers
// ours from the bytes Metal answers for it, keeping Metal's as its shadow.
void test_core_image_extern_functions()
{
Fixture fx;
const char *path = getenv("RGFX_CI_KERNEL");
CHECK(path != nullptr);
if (path == nullptr)
return;
NSData *bytes = [NSData dataWithContentsOfFile:@(path)];
CHECK(bytes.length > 0);
id<MTLDevice> metal = MTLCreateSystemDefaultDevice();
auto make = [&](NSData *from) {
uint32_t status = 0;
return [RgfxLibrary libraryWithData:from.bytes
length:from.length
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
};
RgfxLibrary *lib = make(bytes);
CHECK(lib != nil);
// With no source kept, no shadow and no extern functions.
CHECK([lib rgfxShadow] == nil);
CHECK([lib externFunctionNames].count == 0);
CHECK([lib newExternFunctionWithName:@"swap_red_blue"] == nil);
// The shadow is made once, on first use, from the source.
dispatch_data_t source = dispatch_data_create(bytes.bytes, bytes.length, nil, ^{
(void)bytes;
});
__block int made = 0;
[lib rgfxSetSource:source
shadowMaker:^id<MTLLibrary>(dispatch_data_t d) {
made++;
return [metal newLibraryWithData:d error:nil];
}];
id<MTLLibrary> shadow = [lib rgfxShadow];
CHECK(shadow != nil && [lib rgfxShadow] == shadow && made == 1);
id<RgfxMetalLibraryInternals> internals = (id<RgfxMetalLibraryInternals>)shadow;
NSArray<NSString *> *names = [internals externFunctionNames];
CHECK(names.count == 2);
CHECK([[lib externFunctionNames] isEqualToArray:names]);
CHECK([shadow functionNames].count == 0 && [lib functionNames].count == 0);
RgfxFunction *swap = (RgfxFunction *)[lib newExternFunctionWithName:@"swap_red_blue"];
CHECK([swap isKindOfClass:[RgfxFunction class]]);
CHECK(swap.functionType == kRgfxFunctionTypeExtern);
CHECK([swap.name isEqualToString:@"swap_red_blue"]);
CHECK([swap rgfxShadow].functionType == kRgfxFunctionTypeExtern);
CHECK([[swap rgfxShadow].name isEqualToString:@"swap_red_blue"]);
CHECK([lib newExternFunctionWithName:@"nope"] == nil);
// Its shadow answers what Core Image reflects of the kernel (its return type); a function by
// name answers it from a shadow made of its library's on first use.
SEL returnType = NSSelectorFromString(@"returnType");
CHECK([[swap rgfxShadow] respondsToSelector:returnType] && [swap respondsToSelector:returnType]);
id answered = ((id (*)(id, SEL))objc_msgSend)(swap, returnType);
id metals = ((id (*)(id, SEL))objc_msgSend)([swap rgfxShadow], returnType);
CHECK(answered != nil && [[answered description] isEqualToString:[metals description]]);
RgfxFunction *swapByName = (RgfxFunction *)[lib newFunctionWithName:@"swap_red_blue"];
CHECK([swapByName rgfxShadow] == nil);
id swapType = ((id (*)(id, SEL))objc_msgSend)(swapByName, returnType);
CHECK([swapByName rgfxShadow] != nil &&
[[swapType description] isEqualToString:[metals description]]);
// A kernel by name is of functionType 4 too, as Metal's.
id<MTLFunction> byName = [lib newFunctionWithName:@"scale_red_green"];
CHECK(byName.functionType == kRgfxFunctionTypeExtern);
CHECK([shadow newFunctionWithName:@"scale_red_green"].functionType == kRgfxFunctionTypeExtern);
// The link's functions: ours as their shadows (one made by name given one of its library's
// shadow), Metal's own as they are.
id<MTLFunction> genuine = [internals newExternFunctionWithName:@"scale_red_green"];
NSError *err = nil;
NSArray<id<MTLFunction>> *shadows = RgfxShadowFunctions(@[ swap, byName, genuine ], &err);
CHECK(shadows.count == 3 && err == nil);
CHECK(shadows[0] == [swap rgfxShadow] && shadows[2] == genuine);
CHECK(shadows[1] == [(RgfxFunction *)byName rgfxShadow] &&
![(id)shadows[1] isKindOfClass:[RgfxFunction class]]);
// A function whose library keeps no source has no shadow, and the link is refused.
RgfxLibrary *bare = make(bytes);
CHECK(RgfxShadowFunctions(@[ [bare newFunctionWithName:@"swap_red_blue"] ], &err) == nil);
CHECK(err.code == RgfxMetalErrorInvalidDescriptor);
// Nor any answer of Metal's own: nil, logged.
CHECK(((id (*)(id, SEL))objc_msgSend)([bare newFunctionWithName:@"swap_red_blue"], returnType) ==
nil);
CHECK(RgfxUnsupportedWasLogged([RgfxFunction class], returnType));
// Metal's link answers its own library: made ours from its bytes, Metal's kept as the shadow.
__block NSArray<id<MTLFunction>> *linkedFrom = nil;
__block dispatch_data_t madeFrom = nil;
RgfxLibraryMaker maker = ^id<MTLLibrary>(dispatch_data_t data, NSError **e) {
madeFrom = data;
const void *p = nullptr;
size_t n = 0;
dispatch_data_t map = dispatch_data_create_map(data, &p, &n);
(void)map;
return make([NSData dataWithBytes:p length:n]);
};
err = nil;
id<MTLLibrary> ours = RgfxLinkOverShadows(
@[ swap ],
^id<MTLLibrary>(NSArray<id<MTLFunction>> *given, NSError **e) {
linkedFrom = given;
return shadow;
},
maker, &err);
CHECK(linkedFrom.count == 1 && linkedFrom[0] == [swap rgfxShadow]);
CHECK([(id)ours isKindOfClass:[RgfxLibrary class]] && ours != lib);
CHECK([(RgfxLibrary *)ours rgfxShadow] == shadow);
NSData *contents = [internals libraryDataContents];
CHECK(contents.length > 0 && madeFrom != nil &&
dispatch_data_get_size(madeFrom) == contents.length);
CHECK([[(RgfxLibrary *)ours externFunctionNames] isEqualToArray:names]);
id ourBitcode = [(RgfxLibrary *)ours bitcodeData];
id metalBitcode = ((id (*)(id, SEL))objc_msgSend)(shadow, @selector(bitcodeData));
CHECK((ourBitcode == nil) == (metalBitcode == nil));
// A library the link answers that is ours already is answered as it is, and a refused link
// answers nil with its error.
madeFrom = nil;
CHECK(RgfxLinkOverShadows(
@[ swap ], ^id<MTLLibrary>(NSArray<id<MTLFunction>> *given, NSError **e) { return lib; },
maker, &err) == lib);
CHECK(madeFrom == nil);
err = nil;
CHECK(RgfxLinkOverShadows(
@[ swap ],
^id<MTLLibrary>(NSArray<id<MTLFunction>> *given, NSError **e) {
*e = RgfxMakeError(RgfxMetalErrorRefused, @"refused");
return nil;
},
maker, &err) == nil);
CHECK(err.code == RgfxMetalErrorRefused);
std::vector<uint8_t> drain;
RgfxMsgHeader h;
while (fx.ring.next(&h, &drain)) {
}
}
// A pipeline links a function of another library made with constant values under a specialized
// name, as RenderBox's custom effects link theirs to the `custom_fn` their fragment calls (Metal
// refuses one linked under its own name, "unresolved visible function reference: custom_fn";
// measured: macOS 27): the create carries the fragment's constants, and for the linked function
// its library, list, specialized name and constant values, all the host makes it of.
void test_linked_function_specialised_on_the_wire()
{
Fixture fx;
auto make = [&](const std::vector<uint8_t> &bytes) {
uint32_t status = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:bytes.data()
length:bytes.size()
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
CHECK(lib != nil);
(void)nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE);
return lib;
};
RgfxLibrary *effects = make(metallibOf({
{ "effect_vertex", 0, {} },
{ "effect_fragment", 1, { { "state", 36, 0, true } } },
}));
// An entry the table reads as a visible function.
RgfxLibrary *gradients = make(metallibOf({ { "gradient_v1", 3, { { "variant", 33, 1, true } } } }));
static const uint32_t state[4] = { 0x465, 0x82, 0x1145e, 0xc };
static const uint32_t variant = 7;
MTLFunctionConstantValues *fragmentValues = [MTLFunctionConstantValues new];
[fragmentValues setConstantValue:state type:MTLDataTypeUInt4 atIndex:0];
NSError *err = nil;
id<MTLFunction> fragment = [effects newFunctionWithName:@"effect_fragment"
constantValues:fragmentValues
error:&err];
MTLFunctionDescriptor *fd = [MTLFunctionDescriptor functionDescriptor];
fd.name = @"gradient_v1";
fd.specializedName = @"custom_fn";
fd.constantValues = [MTLFunctionConstantValues new];
[fd.constantValues setConstantValue:&variant type:MTLDataTypeUInt withName:@"variant"];
id<MTLFunction> linked = [gradients newFunctionWithDescriptor:fd error:&err];
CHECK(fragment != nil && linked != nil && err == nil);
CHECK([linked.name isEqualToString:@"custom_fn"]);
MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
desc.vertexFunction = [effects newFunctionWithName:@"effect_vertex"];
desc.fragmentFunction = fragment;
desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
desc.fragmentLinkedFunctions.functions = @[ linked ];
RgfxRenderPipelineState *ps = [RgfxRenderPipelineState renderPipelineStateWithDescriptor:desc
device:nil
serializer:&fx.ser
error:&err];
CHECK(ps != nil && err == nil);
auto bytes = nextMessage(fx.ring, RGFX_CMD_RENDER_PIPELINE_CREATE);
RgfxRenderPipelineCreate head;
std::memcpy(&head, bytes.data(), sizeof(head));
CHECK(head.fragment_library_obj_id == effects.rgfxObjId && head.fragment_constant_count == 1);
RgfxFunctionConstant fc;
std::memcpy(&fc, bytes.data() + head.fragment_constants_offset, sizeof(fc));
CHECK(fc.index == 0 && fc.data_type == static_cast<uint32_t>(MTLDataTypeUInt4));
CHECK(std::memcmp(fc.value, state, sizeof(state)) == 0);
CHECK(head.vertex_linked_count == 0 && head.fragment_linked_count == 1);
RgfxLinkedFunction r;
std::memcpy(&r, bytes.data() + head.fragment_linked_offset, sizeof(r));
CHECK(r.library_obj_id == gradients.rgfxObjId && r.library_obj_id != effects.rgfxObjId);
CHECK(r.list == RGFX_LINKED_FUNCTIONS && r.options == 0 && r.group_len == 0);
CHECK(r.name_len == 11 && std::memcmp(bytes.data() + r.name_offset, "gradient_v1", 11) == 0);
CHECK(r.specialized_name_len == 9 &&
std::memcmp(bytes.data() + r.specialized_name_offset, "custom_fn", 9) == 0);
CHECK(r.constant_count == 1);
RgfxFunctionConstant lc;
std::memcpy(&lc, bytes.data() + r.constants_offset, sizeof(lc));
CHECK(lc.index == 1 && lc.data_type == static_cast<uint32_t>(MTLDataTypeUInt));
CHECK(std::memcmp(lc.value, &variant, sizeof(variant)) == 0);
}
// A library's functions are specialised as Metal specialises them: a value set by name or by
// range reaches its constant's index, an indexed value wins over a named one, values for
// constants the function does not declare are ignored, a required constant left unset reads 0
// and an optional one is not defined, and a value of another type than its constant's fails the
// function with Metal's error. A function made with no values answers its constants and builds
// no pipeline. (Metal's answers measured on macOS 27.0.1, M3 Max.)
void test_function_constants_resolve_as_metal()
{
Fixture fx;
const std::vector<uint8_t> bytes = metallibOf({
{ "frg",
1,
{ { "useRed", 53, 0, true }, { "mode", 29, 7, true }, { "opt", 53, 9, false },
{ "tint", 6, 11, true } } },
{ "knl", 2, { { "scale", 3, 3, true }, { "mode", 29, 7, true } } },
{ "plain", 1, {} },
});
uint32_t status = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:bytes.data()
length:bytes.size()
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
CHECK(lib != nil);
(void)nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE);
static const bool yes = true;
static const int32_t one = 1, two = 2, three = 3;
static const float four[4] = { 1, 2, 3, 4 }, five = 5, nine = 9;
// By name: each value reaches its constant's index, with its bytes; `opt` is not defined.
MTLFunctionConstantValues *named = [MTLFunctionConstantValues new];
[named setConstantValue:&yes type:MTLDataTypeBool withName:@"useRed"];
[named setConstantValue:&two type:MTLDataTypeInt withName:@"mode"];
[named setConstantValue:four type:MTLDataTypeFloat4 withName:@"tint"];
NSError *err = nil;
id<MTLFunction> frg = [lib newFunctionWithName:@"frg" constantValues:named error:&err];
CHECK(frg != nil && err == nil);
CHECK([(RgfxFunction *)frg rgfxConstantCount] == 3);
const RgfxFunctionConstant *k = constantAt(frg, 0);
CHECK(k != nullptr && k->data_type == 53 && k->value[0] == 1);
k = constantAt(frg, 7);
CHECK(k != nullptr && k->data_type == 29 && std::memcmp(k->value, &two, 4) == 0);
k = constantAt(frg, 11);
CHECK(k != nullptr && k->data_type == 6 && std::memcmp(k->value, four, 16) == 0);
CHECK(constantAt(frg, 9) == nullptr);
CHECK(frg.functionConstantsDictionary.count == 0); // specialised: none, as Metal answers
CHECK(![(RgfxFunction *)frg rgfxUnspecialised]);
// A required constant left unset reads 0; the optional one stays undefined.
MTLFunctionConstantValues *some = [MTLFunctionConstantValues new];
[some setConstantValue:&two type:MTLDataTypeInt atIndex:7];
id<MTLFunction> partial = [lib newFunctionWithName:@"frg" constantValues:some error:&err];
CHECK(partial != nil && err == nil);
CHECK([(RgfxFunction *)partial rgfxConstantCount] == 3);
static const uint8_t zeros[RGFX_FUNCTION_CONSTANT_VALUE_BYTES] = {};
k = constantAt(partial, 0);
CHECK(k != nullptr && k->data_type == 53 && std::memcmp(k->value, zeros, sizeof(zeros)) == 0);
k = constantAt(partial, 11);
CHECK(k != nullptr && k->data_type == 6 && std::memcmp(k->value, zeros, sizeof(zeros)) == 0);
CHECK(constantAt(partial, 9) == nullptr);
// nil values specialise with none set.
MTLFunctionConstantValues *nilValues = nil; // through a variable: the parameter is nonnull
id<MTLFunction> none = [lib newFunctionWithName:@"frg" constantValues:nilValues error:&err];
CHECK(none != nil && err == nil && [(RgfxFunction *)none rgfxConstantCount] == 3);
// By range, an index over a name (whose type is then not checked), and values for
// constants the function does not declare, ignored.
MTLFunctionConstantValues *mixed = [MTLFunctionConstantValues new];
[mixed setConstantValues:&five type:MTLDataTypeFloat withRange:NSMakeRange(3, 1)];
[mixed setConstantValue:&nine type:MTLDataTypeFloat withName:@"mode"];
[mixed setConstantValue:&one type:MTLDataTypeInt atIndex:7];
[mixed setConstantValue:&three type:MTLDataTypeInt withName:@"nosuch"];
[mixed setConstantValue:four type:MTLDataTypeBool4 atIndex:30];
id<MTLFunction> knl = [lib newFunctionWithName:@"knl" constantValues:mixed error:&err];
CHECK(knl != nil && err == nil);
CHECK([(RgfxFunction *)knl rgfxConstantCount] == 2);
k = constantAt(knl, 3);
CHECK(k != nullptr && k->data_type == 3 && std::memcmp(k->value, &five, 4) == 0);
k = constantAt(knl, 7);
CHECK(k != nullptr && k->data_type == 29 && std::memcmp(k->value, &one, 4) == 0);
// A value of another type than its constant's: nil, and Metal's error.
MTLFunctionConstantValues *wrong = [MTLFunctionConstantValues new];
[wrong setConstantValue:&five type:MTLDataTypeFloat atIndex:0];
CHECK([lib newFunctionWithName:@"frg" constantValues:wrong error:&err] == nil);
CHECK(err != nil && [err.domain isEqualToString:MTLLibraryErrorDomain] &&
err.code == MTLLibraryErrorCompileFailure);
CHECK([err.localizedDescription
isEqualToString:@"Function frg: constant useRed (0) is of type MTLDataTypeBool but value "
@"found has type MTLDataTypeFloat"]);
MTLFunctionConstantValues *wrongName = [MTLFunctionConstantValues new];
[wrongName setConstantValue:&two type:MTLDataTypeUInt withName:@"mode"];
err = nil;
CHECK([lib newFunctionWithName:@"knl" constantValues:wrongName error:&err] == nil);
CHECK([err.localizedDescription
isEqualToString:@"Function knl: constant mode (7) is of type MTLDataTypeInt but value "
@"found has type MTLDataTypeUInt"]);
static const float span[5] = { 1, 2, 3, 4, 5 };
MTLFunctionConstantValues *wideRange = [MTLFunctionConstantValues new];
[wideRange setConstantValues:span type:MTLDataTypeFloat withRange:NSMakeRange(3, 5)];
err = nil;
CHECK([lib newFunctionWithName:@"knl" constantValues:wideRange error:&err] == nil);
CHECK(err.code == MTLLibraryErrorCompileFailure);
// The completion-handler and descriptor forms answer alike.
__block NSError *handed = nil;
__block id<MTLFunction> handedFn = nil;
[lib newFunctionWithName:@"frg"
constantValues:wrong
completionHandler:^(id<MTLFunction> f, NSError *e) {
handedFn = f;
handed = e;
}];
CHECK(handedFn == nil && handed.code == MTLLibraryErrorCompileFailure);
MTLFunctionDescriptor *fd = [MTLFunctionDescriptor functionDescriptor];
fd.name = @"frg";
fd.constantValues = named;
id<MTLFunction> described = [lib newFunctionWithDescriptor:fd error:&err];
CHECK(described != nil && [(RgfxFunction *)described rgfxConstantCount] == 3);
CHECK(constantAt(described, 7) != nullptr);
fd.constantValues = nil;
described = [lib newFunctionWithDescriptor:fd error:&err];
CHECK(described != nil && ![(RgfxFunction *)described rgfxUnspecialised]);
// A name the library does not hold: Metal's error.
err = nil;
CHECK([lib newFunctionWithName:@"nosuch" constantValues:named error:&err] == nil);
CHECK([err.domain isEqualToString:MTLLibraryErrorDomain] &&
err.code == MTLLibraryErrorFunctionNotFound);
CHECK([err.localizedDescription isEqualToString:@"Function nosuch was not found in the library"]);
// Made with no values: the function answers its constants, and builds no pipeline.
id<MTLFunction> unspecialised = [lib newFunctionWithName:@"frg"];
CHECK([(RgfxFunction *)unspecialised rgfxUnspecialised]);
NSDictionary<NSString *, MTLFunctionConstant *> *table = unspecialised.functionConstantsDictionary;
CHECK(table.count == 4);
CHECK(table[@"opt"].index == 9 && table[@"opt"].type == MTLDataTypeBool && !table[@"opt"].required);
CHECK(table[@"tint"].index == 11 && table[@"tint"].type == MTLDataTypeFloat4 && table[@"tint"].required);
id<MTLFunction> plain = [lib newFunctionWithName:@"plain"];
CHECK(![(RgfxFunction *)plain rgfxUnspecialised] && plain.functionConstantsDictionary.count == 0);
MTLRenderPipelineDescriptor *rd = [[MTLRenderPipelineDescriptor alloc] init];
rd.vertexFunction = knl;
rd.fragmentFunction = unspecialised;
rd.colorAttachments[0].pixelFormat = MTLPixelFormatR16Float;
err = nil;
CHECK([RgfxRenderPipelineState renderPipelineStateWithDescriptor:rd
device:nil
serializer:&fx.ser
error:&err] == nil);
CHECK([err.localizedDescription hasPrefix:@"fragmentFunction frg cannot be used to build a pipeline state."]);
err = nil;
CHECK([RgfxComputePipelineState computePipelineStateWithFunction:[lib newFunctionWithName:@"knl"]
device:nil
serializer:&fx.ser
error:&err] == nil);
CHECK([err.localizedDescription hasPrefix:@"function knl cannot be used to build a pipeline state."]);
RgfxMsgHeader h = {};
std::vector<uint8_t> posted;
CHECK(!fx.ring.next(&h, &posted)); // neither refusal posted a create
// A specialised pipeline carries its functions' records in its create's tail.
rd.fragmentFunction = frg;
RgfxRenderPipelineState *ps = [RgfxRenderPipelineState renderPipelineStateWithDescriptor:rd
device:nil
serializer:&fx.ser
error:&err];
CHECK(ps != nil);
auto create = nextMessage(fx.ring, RGFX_CMD_RENDER_PIPELINE_CREATE);
RgfxRenderPipelineCreate head;
std::memcpy(&head, create.data(), sizeof(head));
CHECK(head.vertex_constant_count == 2 && head.fragment_constant_count == 3);
RgfxFunctionConstant tint;
std::memcpy(&tint, create.data() + head.fragment_constants_offset + 2 * sizeof(tint), sizeof(tint));
CHECK(tint.index == 11 && tint.data_type == 6 && std::memcmp(tint.value, four, 16) == 0);
// A metallib built for macOS 26, whose entries' sizes do not count themselves: its constants
// are read alike, by name and against their types.
const std::vector<uint8_t> older = metallibOf(
{
{ "knl", 2, { { "scale", 3, 3, true }, { "mode", 29, 7, true } } },
{ "plain", 1, {} },
},
false);
RgfxLibrary *lib26 = [RgfxLibrary libraryWithData:older.data()
length:older.size()
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
CHECK(lib26 != nil);
(void)nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE);
MTLFunctionConstantValues *byName = [MTLFunctionConstantValues new];
[byName setConstantValue:&five type:MTLDataTypeFloat withName:@"scale"];
err = nil;
id<MTLFunction> knl26 = [lib26 newFunctionWithName:@"knl" constantValues:byName error:&err];
CHECK(knl26 != nil && [(RgfxFunction *)knl26 rgfxConstantCount] == 2);
CHECK(constantAt(knl26, 3) != nullptr && std::memcmp(constantAt(knl26, 3)->value, &five, 4) == 0);
CHECK(constantAt(knl26, 7) != nullptr && constantAt(knl26, 7)->value[0] == 0);
[byName setConstantValue:&yes type:MTLDataTypeBool withName:@"mode"];
err = nil;
CHECK([lib26 newFunctionWithName:@"knl" constantValues:byName error:&err] == nil);
CHECK(err.code == MTLLibraryErrorCompileFailure);
CHECK([lib26 newFunctionWithName:@"plain"].functionConstantsDictionary.count == 0);
}
static TestHandle *handle(uint64_t objId)
{
return [[TestHandle alloc] initWithObjId:objId device:nil serializer:nullptr];
}
// The host-side op-stream walker, the same minimal consumer as the serialiser check
// (serializer_tests.cpp) and crates/.../decode/cmdbuf.rs.
struct OpWalk {
const uint8_t *ops;
size_t size;
size_t pos = 0;
OpWalk(const uint8_t *p, size_t n) : ops(p), size(n) {}
bool done() const { return pos >= size; }
bool next(uint16_t *tag, 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;
*len = h.len;
*body = ops + pos + RGFX_OP_BODY_OFFSET;
*body_len = h.len - RGFX_OP_BODY_OFFSET;
pos += h.len;
return true;
}
};
static uint16_t opGroup(uint16_t tag) { return static_cast<uint16_t>(tag >> 12); }
// The queue/command-buffer/encoder object graph routes the whole Metal call stream
// through RgfxEncoder onto the queue's submission ring. This drives a command buffer
// through each encoder type and asserts the exact op stream the host decoder expects —
// the routing-assertion pattern of this slice.
void test_command_graph()
{
// Control ring for the serialiser (QUEUE_CREATE), and a separate submission ring
// the queue's command buffers post on (COMMAND_BUFFER).
// Never freed, as Fixture's: the queue and its buffers may go after the test.
TestRing &control = *new TestRing(0x8000);
control.setConsumerIdle(1);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
TestRing submit(0x8000);
submit.setConsumerIdle(1);
RgfxRingWriter submitWriter(submit.base(), submit.dataSize, /*ring_id*/ 1, TestRing::doorbell,
nullptr);
// The queue: its create routes a QUEUE_CREATE on the control ring and picks objId 1.
RgfxCommandQueue *queue = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:&ser];
CHECK(queue != nil);
CHECK(queue.rgfxObjId == 1);
CHECK([queue conformsToProtocol:@protocol(MTLCommandQueue)]);
auto qc = expectQueueCreate(control);
CHECK(qc.obj_id == 1);
CHECK(qc.submit_data_size == submit.dataSize);
// A command buffer: the next objId after the queue's eight barrier fences (10), bound to
// the queue, not yet enqueued.
id<MTLCommandBuffer> cb = [queue commandBuffer];
CHECK(cb != nil);
CHECK([cb conformsToProtocol:@protocol(MTLCommandBuffer)]);
CHECK(((RgfxResource *)cb).rgfxObjId == 10);
CHECK(cb.commandQueue == queue);
CHECK(cb.retainedReferences == YES);
CHECK(cb.status == MTLCommandBufferStatusNotEnqueued);
// --- render encoder ---
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = handle(42);
rp.colorAttachments[0].loadAction = MTLLoadActionClear;
rp.colorAttachments[0].storeAction = MTLStoreActionStore;
rp.colorAttachments[0].clearColor = MTLClearColorMake(0.0, 0.0, 0.0, 1.0);
rp.renderTargetWidth = 1920;
rp.renderTargetHeight = 1080;
id<MTLRenderCommandEncoder> renc = [cb renderCommandEncoderWithDescriptor:rp];
CHECK(renc != nil);
CHECK(renc.device == nil);
[renc setRenderPipelineState:handle(7)];
[renc setVertexBuffer:handle(10) offset:16 atIndex:0];
[renc setViewport:(MTLViewport){ 0.0, 0.0, 1920.0, 1080.0, 0.0, 1.0 }];
{
id<MTLBuffer> bufs[2] = { handle(10), handle(11) };
NSUInteger offs[2] = { 0, 256 };
[renc setVertexBuffers:bufs offsets:offs withRange:NSMakeRange(0, 2)];
}
[renc setFragmentTexture:handle(42) atIndex:3];
[renc setScissorRect:(MTLScissorRect){ 1, 2, 3, 4 }];
[renc setDepthStencilState:handle(8)];
[renc setCullMode:MTLCullModeBack];
[renc useResource:handle(9) usage:MTLResourceUsageRead];
[renc drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[renc drawIndexedPrimitives:MTLPrimitiveTypeTriangle
indexCount:6
indexType:MTLIndexTypeUInt16
indexBuffer:handle(12)
indexBufferOffset:0
instanceCount:2];
[renc endEncoding];
// --- compute encoder ---
id<MTLComputeCommandEncoder> cenc = [cb computeCommandEncoder];
CHECK(cenc != nil);
[cenc setComputePipelineState:handle(20)];
[cenc setBuffer:handle(21) offset:64 atIndex:0];
[cenc setTexture:handle(22) atIndex:1];
[cenc dispatchThreadgroups:MTLSizeMake(16, 8, 1) threadsPerThreadgroup:MTLSizeMake(32, 1, 1)];
[cenc memoryBarrierWithScope:MTLBarrierScopeBuffers];
[cenc updateFence:handle(30)];
[cenc endEncoding];
// --- blit encoder ---
id<MTLBlitCommandEncoder> benc = [cb blitCommandEncoder];
CHECK(benc != nil);
[benc copyFromBuffer:handle(40)
sourceOffset:16
toBuffer:handle(41)
destinationOffset:32
size:4096];
[benc fillBuffer:handle(40) range:NSMakeRange(0, 256) value:0xab];
[benc generateMipmapsForTexture:handle(50)];
[benc synchronizeTexture:handle(51) slice:0 level:1];
[benc waitForFence:handle(60)];
[benc endEncoding];
// Holding a completed handler must not fault; commit posts the command buffer.
[cb addCompletedHandler:^(id<MTLCommandBuffer> _Nonnull done) {
(void)done;
}];
[cb commit];
CHECK(cb.status == MTLCommandBufferStatusCommitted);
// Read the command buffer off the submission ring and check its header.
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(submit.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER);
CHECK(h.size == bytes.size());
RgfxCommandBuffer cbh = {};
std::memcpy(&cbh, bytes.data(), sizeof(cbh));
CHECK(cbh.queue_obj_id == 1);
CHECK(cbh.cb_obj_id == 10);
CHECK(cbh.op_bytes == bytes.size() - RGFX_COMMAND_BUFFER_OPS_OFFSET);
// The exact op sequence the three encoders produced.
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_FRAGMENT_TEXTURE,
RGFX_OP_RENDER_SET_SCISSOR_RECT,
RGFX_OP_RENDER_SET_DEPTH_STENCIL_STATE,
RGFX_OP_RENDER_SET_CULL_MODE,
RGFX_OP_RENDER_USE_RESOURCES,
RGFX_OP_RENDER_DRAW_PRIMITIVES,
RGFX_OP_RENDER_DRAW_INDEXED_PRIMITIVES_INSTANCES,
RGFX_OP_RENDER_UPDATE_FENCE, // the queue barrier fence (QUEUE BARRIERS)
RGFX_OP_ENCODER_END,
RGFX_OP_ENCODER_BEGIN_COMPUTE,
RGFX_OP_COMPUTE_SET_COMPUTE_PIPELINE_STATE,
RGFX_OP_COMPUTE_SET_BUFFERS,
RGFX_OP_COMPUTE_SET_TEXTURE,
RGFX_OP_COMPUTE_DISPATCH_THREADGROUPS,
RGFX_OP_COMPUTE_MEMORY_BARRIER_SCOPE,
RGFX_OP_COMPUTE_UPDATE_FENCE,
RGFX_OP_COMPUTE_UPDATE_FENCE, // the queue barrier fence
RGFX_OP_ENCODER_END,
RGFX_OP_ENCODER_BEGIN_BLIT,
RGFX_OP_BLIT_COPY_BUFFER_TO_BUFFER,
RGFX_OP_BLIT_FILL_BUFFER,
RGFX_OP_BLIT_GENERATE_MIPMAPS,
RGFX_OP_BLIT_SYNCHRONIZE_TEXTURE,
RGFX_OP_BLIT_WAIT_FOR_FENCE,
RGFX_OP_BLIT_UPDATE_FENCE, // the queue barrier fence
RGFX_OP_ENCODER_END,
};
const size_t want_n = sizeof(want) / sizeof(want[0]);
OpWalk walk(bytes.data() + RGFX_COMMAND_BUFFER_OPS_OFFSET, cbh.op_bytes);
int open = 0, begins = 0, ends = 0;
size_t i = 0;
while (!walk.done()) {
uint16_t tag = 0;
uint32_t len = 0;
const uint8_t *body = nullptr;
size_t body_len = 0;
CHECK(walk.next(&tag, &len, &body, &body_len));
CHECK(i < want_n);
CHECK(tag == want[i]);
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);
}
// Representative bodies across the three encoders, with the extracted handles.
if (tag == RGFX_OP_ENCODER_BEGIN_RENDER) {
CHECK(len == 8 + sizeof(RgfxRenderPassDesc) + sizeof(RgfxRenderPassColorAttachment));
RgfxRenderPassDesc pass;
std::memcpy(&pass, body, sizeof(pass));
CHECK(pass.color_count == 1);
CHECK(pass.flags == RGFX_PASS_FLAG_RT_SIZE);
CHECK(pass.render_target_width == 1920 && pass.render_target_height == 1080);
RgfxRenderPassColorAttachment col;
std::memcpy(&col, body + RGFX_RENDER_PASS_COLOR_OFFSET, sizeof(col));
CHECK(col.texture_obj_id == 42);
CHECK(col.load_action == MTLLoadActionClear);
CHECK(col.store_action == MTLStoreActionStore);
double a;
std::memcpy(&a, &col.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 == 10 && b.offset == 16 && b.index == 0);
} else if (tag == RGFX_OP_RENDER_SET_VERTEX_BUFFERS) {
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 == 10 && e0.offset == 0);
CHECK(e1.buffer_obj_id == 11 && e1.offset == 256);
} else if (tag == RGFX_OP_RENDER_SET_FRAGMENT_TEXTURE) {
RgfxOpSetFragmentTexture b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.texture_obj_id == 42 && b.index == 3);
} else if (tag == RGFX_OP_RENDER_USE_RESOURCES) {
RgfxOpUseResources head;
std::memcpy(&head, body, sizeof(head));
CHECK(head.count == 1 && head.usage == MTLResourceUsageRead);
RgfxResourceBinding e;
std::memcpy(&e, body + sizeof(head), sizeof(e));
CHECK(e.obj_id == 9 && e.kind == RGFX_RESOURCE_KIND_BUFFER);
} else if (tag == RGFX_OP_RENDER_DRAW_PRIMITIVES) {
RgfxOpDrawPrimitives b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.primitive_type == MTLPrimitiveTypeTriangle);
CHECK(b.vertex_start == 0 && b.vertex_count == 3);
} else if (tag == RGFX_OP_RENDER_DRAW_INDEXED_PRIMITIVES_INSTANCES) {
RgfxOpDrawIndexedPrimitivesInstances b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.index_count == 6 && b.index_buffer_obj_id == 12 && b.instance_count == 2);
} else if (tag == RGFX_OP_COMPUTE_SET_BUFFERS) {
RgfxComputeOpSetBuffers head;
std::memcpy(&head, body, sizeof(head));
CHECK(head.location == 0 && head.length == 1);
RgfxComputeBufferBinding e;
std::memcpy(&e, body + sizeof(head), sizeof(e));
CHECK(e.buffer_obj_id == 21 && e.offset == 64);
} else if (tag == RGFX_OP_COMPUTE_SET_TEXTURE) {
RgfxComputeOpSetTexture b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.texture_obj_id == 22 && b.index == 1);
} 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);
} else if (tag == RGFX_OP_COMPUTE_UPDATE_FENCE) {
// The app's fence, then the queue's barrier fence at the encoder's end.
RgfxComputeOpUpdateFence b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.fence_obj_id == 30 || (i + 1 < want_n && want[i + 1] == RGFX_OP_ENCODER_END));
} else if (tag == RGFX_OP_BLIT_COPY_BUFFER_TO_BUFFER) {
RgfxBlitOpCopyBufferToBuffer b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.source_buffer_obj_id == 40 && b.destination_buffer_obj_id == 41);
CHECK(b.source_offset == 16 && b.destination_offset == 32 && b.size == 4096);
} else if (tag == RGFX_OP_BLIT_FILL_BUFFER) {
RgfxBlitOpFillBuffer b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.buffer_obj_id == 40 && b.range_length == 256 && b.value == 0xab);
} else if (tag == RGFX_OP_BLIT_SYNCHRONIZE_TEXTURE) {
RgfxBlitOpSynchronizeTexture b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.texture_obj_id == 51 && b.slice == 0 && b.level == 1);
} else if (tag == RGFX_OP_BLIT_WAIT_FOR_FENCE) {
RgfxBlitOpWaitForFence b;
std::memcpy(&b, body, sizeof(b));
CHECK(b.fence_obj_id == 60);
}
i++;
}
CHECK(i == want_n);
CHECK(open == 0);
CHECK(begins == 3 && ends == 3);
CHECK(walk.pos == cbh.op_bytes && cbh.op_bytes % 8 == 0);
// commit is once: a second commit posts nothing more.
[cb commit];
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!submit.next(&extra, &extraBytes));
}
// A parallel render encoder owns one render pass: its sub-encoders forward ops to the
// shared RgfxEncoder without their own framing, and the parallel encoder writes the
// single ENCODER_END.
void test_parallel_render_encoder()
{
// Never freed, as Fixture's: the queue and its buffers may go after the test.
TestRing &control = *new TestRing(0x8000);
control.setConsumerIdle(1);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
TestRing submit(0x8000);
submit.setConsumerIdle(1);
RgfxRingWriter submitWriter(submit.base(), submit.dataSize, 1, TestRing::doorbell, nullptr);
RgfxCommandQueue *queue = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:&ser];
(void)expectQueueCreate(control);
id<MTLCommandBuffer> cb = [queue commandBuffer];
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = handle(42);
id<MTLParallelRenderCommandEncoder> penc =
[cb parallelRenderCommandEncoderWithDescriptor:rp];
CHECK(penc != nil);
id<MTLRenderCommandEncoder> sub1 = [penc renderCommandEncoder];
[sub1 setRenderPipelineState:handle(7)];
[sub1 drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:0 vertexCount:3];
[sub1 endEncoding]; // sub-encoder writes NO framing
id<MTLRenderCommandEncoder> sub2 = [penc renderCommandEncoder];
[sub2 drawPrimitives:MTLPrimitiveTypeTriangle vertexStart:3 vertexCount:3];
[sub2 endEncoding];
[penc endEncoding]; // the one ENCODER_END for the pass
[cb commit];
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(submit.next(&h, &bytes));
RgfxCommandBuffer cbh = {};
std::memcpy(&cbh, bytes.data(), sizeof(cbh));
const uint16_t want[] = {
RGFX_OP_ENCODER_BEGIN_RENDER, RGFX_OP_RENDER_SET_RENDER_PIPELINE_STATE,
RGFX_OP_RENDER_DRAW_PRIMITIVES, RGFX_OP_RENDER_DRAW_PRIMITIVES,
RGFX_OP_RENDER_UPDATE_FENCE, // the pass's queue barrier fence (QUEUE BARRIERS)
RGFX_OP_ENCODER_END,
};
const size_t want_n = sizeof(want) / sizeof(want[0]);
OpWalk walk(bytes.data() + RGFX_COMMAND_BUFFER_OPS_OFFSET, cbh.op_bytes);
size_t i = 0;
int begins = 0, ends = 0;
while (!walk.done()) {
uint16_t tag = 0;
uint32_t len = 0;
const uint8_t *body = nullptr;
size_t body_len = 0;
CHECK(walk.next(&tag, &len, &body, &body_len));
CHECK(i < want_n && tag == want[i]);
if (tag == RGFX_OP_ENCODER_BEGIN_RENDER)
begins++;
if (tag == RGFX_OP_ENCODER_END)
ends++;
i++;
}
CHECK(i == want_n);
CHECK(begins == 1 && ends == 1); // one pass, one begin/end though two sub-encoders
}
// A queue must have a route, an id space and a ring.
void test_queue_guards()
{
// Never freed, as Fixture's: the queue and its buffers may go after the test.
TestRing &control = *new TestRing(0x8000);
control.setConsumerIdle(1);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
TestRing submit(0x8000);
RgfxRingWriter submitWriter(submit.base(), submit.dataSize, 1, TestRing::doorbell, nullptr);
CHECK([RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:nullptr] == nil);
CHECK([RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:nullptr
maxCount:0
device:nil
serializer:&ser] == nil);
CHECK([RgfxCommandQueue queueWithSubmitRing:nullptr
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:&ser] == nil);
}
// =============================================================================
// The transport layer: the region allocator and the reply reader
// =============================================================================
// The region allocator hands out aligned, non-overlapping blocks past the floor
// (RGFX_ALLOCATIONS_OFFSET), never touching the host-reserved control rings / caps
// page below it, and places ring pairs with power-of-two byte rings.
void test_region_allocator()
{
std::vector<uint8_t> mem(0x800000, 0xff); // 8 MiB, pre-dirtied like BAR memory
RgfxRegion region(mem.data(), mem.size());
CHECK(region.floor() == RGFX_ALLOCATIONS_OFFSET);
CHECK(region.size() == mem.size());
RgfxRegion::Block a = region.allocate(0x1000);
CHECK(a.ok);
CHECK(a.offset >= RGFX_ALLOCATIONS_OFFSET); // never below the floor
CHECK(a.offset % 0x1000 == 0); // aligned (default page)
CHECK(a.ptr == region.base() + a.offset);
CHECK(a.size == 0x1000);
RgfxRegion::Block b = region.allocate(0x800, 256);
CHECK(b.ok);
CHECK(b.offset % 256 == 0);
CHECK(a.offset + a.size <= b.offset); // non-overlap with a
RgfxRegion::Block c = region.allocate(0x1234, 64);
CHECK(c.ok);
CHECK(b.offset + b.size <= c.offset); // non-overlap with b
CHECK(region.used() >= (c.offset - region.floor()) + c.size);
// A non-power-of-two alignment, and a request past the region's end, both fail.
CHECK(!region.allocate(16, 3).ok);
CHECK(!region.allocate(mem.size(), 0x1000).ok);
// A submission + completion ring pair: both offsets past the floor, non-overlapping,
// each a ring header plus a power-of-two byte ring.
RgfxRegion::RingPair rings = region.allocateRingPair(0x8000, 0x8000);
CHECK(rings.ok);
CHECK(rings.submit_offset >= RGFX_ALLOCATIONS_OFFSET);
CHECK(rings.submit_data_size == 0x8000);
CHECK(rings.complete_data_size == 0x8000);
CHECK(rings.complete_offset >= rings.submit_offset + RGFX_RING_HEADER_SIZE + 0x8000);
// A completion ring of 0 places none (the single-ring model).
RgfxRegion::RingPair submitOnly = region.allocateRingPair(0x1000, 0);
CHECK(submitOnly.ok);
CHECK(submitOnly.complete_offset == 0);
// A non-power-of-two byte ring is refused.
CHECK(!region.allocateRingPair(0x7000, 0).ok);
// contains / offsetOf: inside the allocable region, below the floor is out.
CHECK(region.contains(mem.data() + RGFX_ALLOCATIONS_OFFSET, 16));
CHECK(!region.contains(mem.data(), 16)); // below the floor
CHECK(!region.contains(mem.data() + mem.size() - 8, 16)); // runs off the end
CHECK(region.offsetOf(mem.data() + a.offset) == a.offset);
}
// newCommandQueue's path: a queue built over a ring pair the region allocator placed
// carries those offsets in its RGFX_CMD_QUEUE_CREATE (the device category does the same
// with its region; here the factory is driven directly with a fixture region).
void test_queue_carries_allocated_offsets()
{
// Never freed, as Fixture's: the queue and its buffers may go after the test.
TestRing &control = *new TestRing(0x8000);
control.setConsumerIdle(1);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
std::vector<uint8_t> mem(0x800000, 0);
RgfxRegion region(mem.data(), mem.size());
RgfxRegion::RingPair rings = region.allocateRingPair(0x8000, 0x8000);
CHECK(rings.ok);
// The submission ring's writer over the region at the allocated submit offset.
RgfxRingWriter submitWriter(region.base() + rings.submit_offset, rings.submit_data_size, 1,
TestRing::doorbell, nullptr);
RgfxCommandQueue *queue = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:rings.submit_offset
completeOffset:rings.complete_offset
completeDataSize:rings.complete_data_size
ids:&ids
maxCount:0
device:nil
serializer:&ser];
CHECK(queue != nil);
RgfxQueueCreate qc = expectQueueCreate(control);
CHECK(qc.submit_offset == rings.submit_offset);
CHECK(qc.complete_offset == rings.complete_offset);
CHECK(qc.submit_data_size == rings.submit_data_size);
CHECK(qc.complete_data_size == rings.complete_data_size);
CHECK(qc.submit_offset >= RGFX_ALLOCATIONS_OFFSET);
}
// A host command-buffer completion the reader dispatches: the CB's completed handler
// fires with the buffer, its status flips, and an error completion carries the error.
void test_reply_reader_completion()
{
// Never freed, as Fixture's: the queue and its buffers may go after the test.
TestRing &control = *new TestRing(0x8000);
control.setConsumerIdle(1);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
TestRing submit(0x8000);
submit.setConsumerIdle(1);
RgfxRingWriter submitWriter(submit.base(), submit.dataSize, 1, TestRing::doorbell, nullptr);
TestRing completion(0x8000);
RgfxReplyReader reader(completion.base(), completion.dataSize);
RgfxCommandQueue *queue = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:&ser];
queue.replyReader = &reader;
(void)expectQueueCreate(control);
// --- a clean completion ---
__block int fired = 0;
__block id<MTLCommandBuffer> handlerGot = nil;
id<MTLCommandBuffer> cb = [queue commandBuffer];
uint64_t cbObjId = ((RgfxResource *)cb).rgfxObjId;
[cb addCompletedHandler:^(id<MTLCommandBuffer> done) {
fired++;
handlerGot = done;
}];
// No time is known before the commit, and the GPU's none before the completion.
CHECK(cb.kernelStartTime == 0 && cb.kernelEndTime == 0);
CHECK(cb.GPUStartTime == 0 && cb.GPUEndTime == 0);
[cb commit];
CHECK(cb.status == MTLCommandBufferStatusCommitted);
CHECK(cb.kernelStartTime > 0 && cb.kernelEndTime >= cb.kernelStartTime);
CHECK(cb.GPUStartTime == 0 && cb.GPUEndTime == 0);
// Read the submission seqno the host's completion must carry.
RgfxMsgHeader submitHdr = {};
std::vector<uint8_t> submitBytes;
CHECK(submit.next(&submitHdr, &submitBytes));
CHECK(submitHdr.type == RGFX_CMD_COMMAND_BUFFER);
uint64_t seqno = submitHdr.seqno;
// Nothing has arrived: no dispatch, handler unfired.
CHECK(reader.pump() == 0);
CHECK(fired == 0);
CHECK(reader.awaitingCompletion(seqno));
RgfxCbComplete done = {};
done.header.type = RGFX_EVT_CB_COMPLETE;
done.header.size = sizeof(done);
done.header.seqno = seqno;
done.cb_obj_id = cbObjId;
done.status = RGFX_CB_OK;
// A 2 ms run on the device's clock.
done.gpu_start_ns = 5'000'000'000;
done.gpu_end_ns = 5'002'000'000;
CHECK(completion.postFromHost(&done, sizeof(done)));
CHECK(reader.pump() == 1);
CHECK(fired == 1);
CHECK(handlerGot == cb);
CHECK(cb.status == MTLCommandBufferStatusCompleted);
CHECK(cb.error == nil);
// The run ends at the delivery, in the guest's time, and lasts what the device measured,
// starting no earlier than the CPU posted the buffer.
CHECK(cb.GPUEndTime >= cb.GPUStartTime && cb.GPUStartTime >= cb.kernelEndTime);
CHECK(cb.GPUEndTime - cb.GPUStartTime <= 0.002 + 1e-9);
CHECK(!reader.awaitingCompletion(seqno)); // the one-shot was removed
// --- an error completion on a second buffer, waited on ---
id<MTLCommandBuffer> cb2 = [queue commandBuffer];
uint64_t cb2ObjId = ((RgfxResource *)cb2).rgfxObjId;
[cb2 commit];
RgfxMsgHeader submitHdr2 = {};
std::vector<uint8_t> submitBytes2;
CHECK(submit.next(&submitHdr2, &submitBytes2));
uint64_t seqno2 = submitHdr2.seqno;
RgfxCbComplete failed = {};
failed.header.type = RGFX_EVT_CB_COMPLETE;
failed.header.size = sizeof(failed);
failed.header.seqno = seqno2;
failed.cb_obj_id = cb2ObjId;
failed.status = RGFX_CB_TIMEOUT;
failed.error_code = 2; // MTLCommandBufferErrorTimeout
CHECK(completion.postFromHost(&failed, sizeof(failed)));
[cb2 waitUntilCompleted]; // pumps until the completion lands
CHECK(cb2.status == MTLCommandBufferStatusError);
CHECK(cb2.error != nil);
CHECK(cb2.error.code == 2);
// No run length known: the run starts as it ends.
CHECK(cb2.GPUEndTime > 0 && cb2.GPUStartTime == cb2.GPUEndTime);
// A descriptor's error options are kept for the buffer to answer, and no buffer has logs.
MTLCommandBufferDescriptor *desc = [[MTLCommandBufferDescriptor alloc] init];
desc.errorOptions = MTLCommandBufferErrorOptionEncoderExecutionStatus;
id<MTLCommandBuffer> cb3 = [queue commandBufferWithDescriptor:desc];
CHECK(cb3.errorOptions == MTLCommandBufferErrorOptionEncoderExecutionStatus);
// The content protection asked of a buffer is answered as set.
id<MTLCommandBufferSPI> spi = (id<MTLCommandBufferSPI>)cb3;
CHECK([spi protectionOptions] == 0);
[spi setProtectionOptions:0x5];
CHECK([spi protectionOptions] == 0x5);
CHECK(cb.errorOptions == MTLCommandBufferErrorOptionNone);
NSUInteger logs = 0;
for (id log in cb3.logs) {
(void)log;
logs++;
}
CHECK(logs == 0);
}
// A host pipeline reflection the reader dispatches fills the pipeline-state wrapper, so
// its reflection getters report the host's values instead of placeholders.
void test_reply_reader_reflection()
{
Fixture fx; // control ring + serialiser
const uint8_t libBytes[] = { 1, 2, 3, 4 };
uint32_t libStatus = 0;
RgfxLibrary *lib = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&libStatus];
(void)nextMessage(fx.ring, RGFX_CMD_LIBRARY_CREATE);
id<MTLFunction> cfn = [lib newFunctionWithName:@"kmain"];
NSError *err = nil;
RgfxComputePipelineState *ps =
[RgfxComputePipelineState computePipelineStateWithFunction:cfn
device:nil
serializer:&fx.ser
error:&err];
CHECK(ps != nil);
(void)nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
TestRing completion(0x8000);
RgfxReplyReader reader(completion.base(), completion.dataSize);
[ps rgfxRegisterWithReplyReader:&reader];
CHECK(reader.awaitingReflection(ps.rgfxSeqno));
// Before the reply the getters answer placeholders.
CHECK([ps maxTotalThreadsPerThreadgroup] == 1024);
CHECK(ps.gpuResourceID._impl == 0);
RgfxPipelineReflection refl = {};
refl.header.type = RGFX_EVT_PIPELINE_REFLECTION;
refl.header.size = sizeof(refl);
refl.header.seqno = ps.rgfxSeqno;
refl.obj_id = ps.rgfxObjId;
refl.gpu_resource_id = 0xABCDEF;
refl.max_total_threads_per_threadgroup = 512;
refl.static_threadgroup_memory_length = 2048;
refl.thread_execution_width = 64;
refl.status = RGFX_PIPELINE_OK;
refl.kind = RGFX_PIPELINE_KIND_COMPUTE;
CHECK(completion.postFromHost(&refl, sizeof(refl)));
CHECK(reader.pump() == 1);
CHECK([ps maxTotalThreadsPerThreadgroup] == 512);
CHECK([ps threadExecutionWidth] == 64);
CHECK([ps staticThreadgroupMemoryLength] == 2048);
CHECK(ps.gpuResourceID._impl == 0xABCDEF);
CHECK(!reader.awaitingReflection(ps.rgfxSeqno)); // one-shot removed
CHECK(![ps rgfxRefused]);
// A refused create: the state reports the refusal, which the device's creators answer as
// nil and an NSError.
RgfxComputePipelineState *refusedPs =
[RgfxComputePipelineState computePipelineStateWithFunction:cfn
device:nil
serializer:&fx.ser
error:&err];
CHECK(refusedPs != nil);
(void)nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
[refusedPs rgfxRegisterWithReplyReader:&reader];
CHECK(![refusedPs rgfxRefused]);
RgfxPipelineReflection no = {};
no.header.type = RGFX_EVT_PIPELINE_REFLECTION;
no.header.size = sizeof(no);
no.header.seqno = refusedPs.rgfxSeqno;
no.obj_id = refusedPs.rgfxObjId;
no.status = RGFX_PIPELINE_REFUSED;
no.kind = RGFX_PIPELINE_KIND_COMPUTE;
CHECK(completion.postFromHost(&no, sizeof(no)));
CHECK(reader.pump() == 1);
CHECK([refusedPs rgfxRefused]);
}
// A host event-signalled message raises the shared event's value and fires the
// notifyListener blocks it reached, on their listener's queue, with the value each was
// registered at, as Metal's do (measured on the M3 Max). The host posts it on the queue's
// completion ring, whose reader hands it to the device's, where the event listens. A lower
// value leaves the value; a block registered at a value reached fires at once, on its queue.
void test_reply_reader_event()
{
// The readers are declared before the inner pool so they outlive the autoreleased
// event, whose dealloc deregisters its listener from the device's reader (as the
// device's reader outlives its events in the guest).
RgfxReplyReader device;
TestRing completion(0x8000);
RgfxReplyReader queue(completion.base(), completion.dataSize);
queue.setEventsTo(&device);
@autoreleasepool {
Fixture fx;
const uint64_t initial = 5;
RgfxSharedEvent *ev = [RgfxSharedEvent sharedEventWithInitialValue:initial
device:nil
serializer:&fx.ser];
CHECK(ev != nil);
(void)expectMessage<RgfxSharedEventCreate>(fx.ring, RGFX_CMD_SHARED_EVENT_CREATE);
[ev rgfxRegisterWithReplyReader:&device];
CHECK(ev.signaledValue == initial);
// A listener on a queue of its own, which fires once the value reaches 45.
dispatch_queue_t lq = dispatch_queue_create("rgfx.test.listener", DISPATCH_QUEUE_SERIAL);
static char onListener;
dispatch_queue_set_specific(lq, &onListener, &onListener, nullptr);
MTLSharedEventListener *listener = [[MTLSharedEventListener alloc] initWithDispatchQueue:lq];
dispatch_semaphore_t fired = dispatch_semaphore_create(0);
__block uint64_t notified = 0;
__block bool onItsQueue = false;
[ev notifyListener:listener
atValue:45
block:^(id<MTLSharedEvent> e, uint64_t v) {
(void)e;
notified = v;
onItsQueue = dispatch_get_specific(&onListener) == &onListener;
dispatch_semaphore_signal(fired);
}];
auto signal = [&](uint64_t value) {
RgfxEventSignalled sig = {};
sig.header.type = RGFX_EVT_EVENT_SIGNALLED;
sig.header.size = sizeof(sig);
sig.obj_id = ev.rgfxObjId;
sig.value = value;
CHECK(completion.postFromHost(&sig, sizeof(sig)));
CHECK(queue.pump() == 1);
};
// The host raises the event to 42: the value rises, the 45-listener holds.
signal(42);
CHECK(ev.signaledValue == 42);
dispatch_sync(lq, ^{
});
CHECK(notified == 0);
// The host raises it to 50: the value rises and the listener fires on its queue, with 45.
signal(50);
CHECK(ev.signaledValue == 50);
CHECK(dispatch_semaphore_wait(fired, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
CHECK(notified == 45);
CHECK(onItsQueue);
// A lower value leaves it.
signal(30);
CHECK(ev.signaledValue == 50);
// One registered at a value reached fires at once, on its queue, with its value.
onItsQueue = false;
[ev notifyListener:listener
atValue:10
block:^(id<MTLSharedEvent> e, uint64_t v) {
(void)e;
notified = v;
onItsQueue = dispatch_get_specific(&onListener) == &onListener;
dispatch_semaphore_signal(fired);
}];
CHECK(dispatch_semaphore_wait(fired, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
CHECK(notified == 10);
CHECK(onItsQueue);
// A CPU set reaches a listener too.
[ev notifyListener:listener
atValue:60
block:^(id<MTLSharedEvent> e, uint64_t v) {
(void)e;
notified = v;
dispatch_semaphore_signal(fired);
}];
ev.signaledValue = 61;
CHECK(dispatch_semaphore_wait(fired, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
CHECK(notified == 60);
(void)expectMessage<RgfxSharedEventSetValue>(fx.ring, RGFX_CMD_SHARED_EVENT_SET_VALUE);
dispatch_sync(lq, ^{
});
} // @autoreleasepool: ev drains here, while the readers still live
}
// --- the completion thread ---------------------------------------------------
// The kext's side of the completion thread, in user space: the wake count the thread
// sleeps on (kRgfxAccelMethodWaitCompletions), and the host's post, which raises the
// vector where the ring is armed and so wakes the thread (queueInterrupt).
struct FakeKext {
std::mutex lock;
std::condition_variable changed;
uint64_t count = 0;
bool closed = false;
int waits = 0;
void wake()
{
std::lock_guard<std::mutex> hold(lock);
count++;
changed.notify_all();
}
void close()
{
std::lock_guard<std::mutex> hold(lock);
closed = true;
changed.notify_all();
}
int waitCount()
{
std::lock_guard<std::mutex> hold(lock);
return waits;
}
static RgfxCompletionThread::WaitResult wait(void *context, uint64_t last, uint64_t *now)
{
FakeKext *k = static_cast<FakeKext *>(context);
std::unique_lock<std::mutex> hold(k->lock);
k->waits++;
k->changed.wait(hold, [&] { return k->count != last || k->closed; });
*now = k->count;
return k->closed ? RgfxCompletionThread::kStop : RgfxCompletionThread::kWoke;
}
};
uint32_t ringArmed(TestRing &ring)
{
return __atomic_load_n(reinterpret_cast<uint32_t *>(ring.mem.data() +
__builtin_offsetof(RgfxRingHeader, armed)),
__ATOMIC_SEQ_CST);
}
// The host's post (ring.rs Producer::post): the record published, a full fence, then
// `armed` read and cleared, the vector raised where it was set.
void hostPost(TestRing &ring, FakeKext &kext, const void *msg, uint32_t size)
{
CHECK(ring.postFromHost(msg, size));
__atomic_thread_fence(__ATOMIC_SEQ_CST);
uint32_t *armed = reinterpret_cast<uint32_t *>(ring.mem.data() +
__builtin_offsetof(RgfxRingHeader, armed));
if (__atomic_exchange_n(armed, 0u, __ATOMIC_SEQ_CST) == 1)
kext.wake();
}
RgfxCbComplete cbComplete(uint64_t seqno, uint64_t cbObjId)
{
RgfxCbComplete done = {};
done.header.type = RGFX_EVT_CB_COMPLETE;
done.header.size = sizeof(done);
done.header.seqno = seqno;
done.cb_obj_id = cbObjId;
done.status = RGFX_CB_OK;
return done;
}
// Waits up to 5 s for `pred`, polling.
template <typename F> bool eventually(F pred)
{
for (int i = 0; i < 5000; i++) {
if (pred())
return true;
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
return pred();
}
// A queue over its own submission and completion rings, as the device makes one, with an
// owned reader the completion thread can drive.
// The rings and the serialiser are never freed, as Fixture's: the queue lives on while a
// command buffer the test let go holds it.
struct QueueFixture {
TestRing &control = *new TestRing(0x8000);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
TestRing &submit;
RgfxRingWriter &submitWriter;
TestRing &completion = *new TestRing(0x8000);
RgfxCommandQueue *queue = nil;
// A queue whose submission ring has `submitData` bytes, made with `maxCount`, its doorbell
// `doorbell` (with `doorbellContext`).
explicit QueueFixture(uint32_t submitData = 0x8000, NSUInteger maxCount = 0,
RgfxDoorbell doorbell = TestRing::doorbell, void *doorbellContext = nullptr)
: submit(*new TestRing(submitData)),
submitWriter(*new RgfxRingWriter(submit.base(), submit.dataSize, 1, doorbell,
doorbellContext))
{
control.setConsumerIdle(1);
submit.setConsumerIdle(1);
queue = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:maxCount
device:nil
serializer:&ser];
[queue adoptReplyReader:new RgfxReplyReader(completion.base(), completion.dataSize)];
}
// The submission seqno of the next command buffer committed on the queue.
uint64_t nextSeqno()
{
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(submit.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER);
return h.seqno;
}
};
// A command buffer's event ops go in its stream between its encoders, in order, each naming
// its event and value, an event and a shared event alike; one naming an event no device of
// ours made is not carried.
void test_command_buffer_event_ops()
{
QueueFixture f;
@autoreleasepool {
RgfxEvent *ev = [RgfxEvent eventWithDevice:nil serializer:&f.ser];
RgfxSharedEvent *sev = [RgfxSharedEvent sharedEventWithInitialValue:0
device:nil
serializer:&f.ser];
CHECK(ev != nil && sev != nil);
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
[cb encodeWaitForEvent:sev value:3];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit endEncoding];
[cb encodeSignalEvent:ev value:4];
[cb encodeSignalEvent:(id<MTLEvent>)[NSObject new] value:9];
[cb encodeSignalEvent:sev value:5];
[cb commit];
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(f.submit.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER);
RgfxCommandBuffer cbh = {};
std::memcpy(&cbh, bytes.data(), sizeof(cbh));
struct Want {
uint16_t tag;
uint64_t event;
uint64_t value;
};
const Want want[] = {
{ RGFX_OP_WAIT_EVENT, sev.rgfxObjId, 3 },
{ RGFX_OP_ENCODER_BEGIN_BLIT, 0, 0 },
{ RGFX_OP_ENCODER_END, 0, 0 },
{ RGFX_OP_SIGNAL_EVENT, ev.rgfxObjId, 4 },
{ RGFX_OP_SIGNAL_EVENT, sev.rgfxObjId, 5 },
};
size_t i = 0;
OpWalk walk(bytes.data() + RGFX_COMMAND_BUFFER_OPS_OFFSET, cbh.op_bytes);
while (!walk.done()) {
uint16_t tag = 0;
uint32_t len = 0;
const uint8_t *body = nullptr;
size_t bodyLen = 0;
CHECK(walk.next(&tag, &len, &body, &bodyLen));
if (opGroup(tag) != RGFX_OP_GROUP_FRAMING)
continue; // the queue's barrier fence
CHECK(i < sizeof(want) / sizeof(want[0]));
CHECK(tag == want[i].tag);
if (tag == RGFX_OP_SIGNAL_EVENT || tag == RGFX_OP_WAIT_EVENT) {
RgfxOpEvent op = {};
CHECK(bodyLen == sizeof(op));
std::memcpy(&op, body, sizeof(op));
CHECK(op.event_obj_id == want[i].event && op.value == want[i].value);
}
i++;
}
CHECK(i == sizeof(want) / sizeof(want[0]));
RgfxCbComplete done = cbComplete(h.seqno, ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
}
}
// armAndCheck sets the ring's `armed` and says whether records wait; a ringless reader
// has nothing to arm.
void test_reply_reader_arm()
{
RgfxReplyReader ringless;
CHECK(!ringless.armAndCheck());
TestRing ring(0x1000);
RgfxReplyReader reader(ring.base(), ring.dataSize);
CHECK(!reader.driven());
CHECK(!reader.armAndCheck());
CHECK(ringArmed(ring) == 1);
RgfxCbComplete done = cbComplete(7, 1);
CHECK(ring.postFromHost(&done, sizeof(done)));
CHECK(reader.armAndCheck()); // a record waits: pump before sleeping
reader.pump();
CHECK(!reader.armAndCheck());
reader.setDriven(true);
CHECK(reader.driven());
}
// With nobody waiting, the completion thread runs each command buffer's scheduled then
// completed handlers as the host posts its completion, in the ring's order, on its own
// thread, and leaves the ring drained and armed.
void test_completion_thread_runs_handlers()
{
@autoreleasepool {
QueueFixture f;
FakeKext *kext = new FakeKext(); // outlives the thread, which may sleep in it
RgfxCompletionThread thread(&FakeKext::wait, kext);
thread.add([f.queue sharedReplyReader]);
CHECK(![f.queue sharedReplyReader]->driven()); // not started: the waiters pump
CHECK(thread.start());
CHECK(thread.running());
CHECK([f.queue sharedReplyReader]->driven());
CHECK(ringArmed(f.completion) == 1);
CHECK(eventually([&] { return kext->waitCount() >= 1; })); // asleep in the kext
std::mutex lock;
std::vector<std::string> order;
__block std::mutex *orderLock = &lock;
__block std::vector<std::string> *orderLog = &order;
__block int offThread = 0;
dispatch_semaphore_t last = dispatch_semaphore_create(0);
NSMutableArray<id<MTLCommandBuffer>> *cbs = [NSMutableArray array];
std::vector<uint64_t> seqnos;
for (int i = 0; i < 3; i++) {
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
std::string n = std::to_string(i);
[cb addScheduledHandler:^(id<MTLCommandBuffer> done) {
(void)done;
std::lock_guard<std::mutex> hold(*orderLock);
orderLog->push_back("s" + n);
if (!RgfxCompletionThread::onCurrentThread())
offThread++;
}];
[cb addCompletedHandler:^(id<MTLCommandBuffer> done) {
std::lock_guard<std::mutex> hold(*orderLock);
orderLog->push_back("c" + n + (done.status == MTLCommandBufferStatusCompleted ? "" : "!"));
if (!RgfxCompletionThread::onCurrentThread())
offThread++;
if (n == "2")
dispatch_semaphore_signal(last);
}];
[cb commit];
[cbs addObject:cb];
seqnos.push_back(f.nextSeqno());
}
// The first completion wakes the thread; the next two land while it may be busy, and
// are taken by the same pass or the next.
for (int i = 0; i < 3; i++) {
RgfxCbComplete done = cbComplete(seqnos[i], ((RgfxResource *)cbs[i]).rgfxObjId);
hostPost(f.completion, *kext, &done, sizeof(done));
}
CHECK(dispatch_semaphore_wait(last, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
{
std::lock_guard<std::mutex> hold(lock);
std::vector<std::string> want = {"s0", "c0", "s1", "c1", "s2", "c2"};
CHECK(order == want);
CHECK(offThread == 0);
}
for (id<MTLCommandBuffer> cb in cbs)
CHECK(cb.status == MTLCommandBufferStatusCompleted);
CHECK(eventually([&] { return f.completion.consumerCount() == f.completion.produced; }));
CHECK(eventually([&] { return ringArmed(f.completion) == 1; })); // armed for the next
// A waiter after the fact returns at once; the handlers ran once.
[cbs[0] waitUntilCompleted];
{
std::lock_guard<std::mutex> hold(lock);
CHECK(order.size() == 6);
}
kext->close();
CHECK(eventually([&] { return !thread.running(); }));
}
}
// waitUntilCompleted on a driven reader blocks until the thread delivers, and the
// handlers run once, before the wait returns.
void test_wait_with_the_completion_thread()
{
@autoreleasepool {
QueueFixture f;
FakeKext *kext = new FakeKext();
RgfxCompletionThread thread(&FakeKext::wait, kext);
CHECK(thread.start());
thread.add([f.queue sharedReplyReader]);
CHECK([f.queue sharedReplyReader]->driven());
std::atomic<int> fired{0};
std::atomic<int> *firedp = &fired;
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
[cb addCompletedHandler:^(id<MTLCommandBuffer> done) {
(void)done;
std::this_thread::sleep_for(std::chrono::milliseconds(20)); // the waiter must outwait it
(*firedp)++;
}];
[cb commit];
uint64_t seqno = f.nextSeqno();
uint64_t cbObjId = ((RgfxResource *)cb).rgfxObjId;
TestRing *ring = &f.completion;
std::thread host([ring, kext, seqno, cbObjId] {
std::this_thread::sleep_for(std::chrono::milliseconds(50));
RgfxCbComplete done = cbComplete(seqno, cbObjId);
hostPost(*ring, *kext, &done, sizeof(done));
});
[cb waitUntilCompleted];
CHECK(fired.load() == 1); // the handler ran before the wait returned
CHECK(cb.status == MTLCommandBufferStatusCompleted);
host.join();
[cb waitUntilCompleted];
CHECK(fired.load() == 1); // and only once
// A handler waiting for a later buffer, on the completion thread: it takes the ring
// itself, so neither hangs.
id<MTLCommandBuffer> first = [f.queue commandBuffer];
id<MTLCommandBuffer> second = [f.queue commandBuffer];
std::atomic<int> nested{0};
std::atomic<int> *nestedp = &nested;
dispatch_semaphore_t both = dispatch_semaphore_create(0);
[first addCompletedHandler:^(id<MTLCommandBuffer> done) {
(void)done;
[second waitUntilCompleted];
*nestedp = second.status == MTLCommandBufferStatusCompleted ? 1 : 2;
dispatch_semaphore_signal(both);
}];
[first commit];
uint64_t s1 = f.nextSeqno();
[second commit];
uint64_t s2 = f.nextSeqno();
RgfxCbComplete d1 = cbComplete(s1, ((RgfxResource *)first).rgfxObjId);
hostPost(f.completion, *kext, &d1, sizeof(d1));
std::this_thread::sleep_for(std::chrono::milliseconds(20));
RgfxCbComplete d2 = cbComplete(s2, ((RgfxResource *)second).rgfxObjId);
hostPost(f.completion, *kext, &d2, sizeof(d2));
CHECK(dispatch_semaphore_wait(both, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
CHECK(nested.load() == 1);
[second waitUntilCompleted];
kext->close();
CHECK(eventually([&] { return !thread.running(); }));
}
}
// Once the kext ends the wait (the process's context is gone) or the thread is
// destroyed, the readers go undriven, and waitUntilCompleted takes the ring itself.
void test_completion_thread_stops()
{
@autoreleasepool {
QueueFixture f;
FakeKext *kext = new FakeKext();
RgfxCompletionThread thread(&FakeKext::wait, kext);
CHECK(thread.start());
thread.add([f.queue sharedReplyReader]);
CHECK([f.queue sharedReplyReader]->driven());
kext->close();
CHECK(eventually([&] { return !thread.running(); }));
CHECK(![f.queue sharedReplyReader]->driven());
__block int fired = 0;
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
[cb addCompletedHandler:^(id<MTLCommandBuffer> done) {
(void)done;
fired++;
}];
[cb commit];
RgfxCbComplete done = cbComplete(f.nextSeqno(), ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted]; // pumps: nothing else takes the ring
CHECK(fired == 1);
CHECK(cb.status == MTLCommandBufferStatusCompleted);
// A thread destroyed while it sleeps lets its readers go at once.
QueueFixture g;
FakeKext *kext2 = new FakeKext();
{
RgfxCompletionThread doomed(&FakeKext::wait, kext2);
CHECK(doomed.start());
doomed.add([g.queue sharedReplyReader]);
CHECK([g.queue sharedReplyReader]->driven());
CHECK(eventually([&] { return kext2->waitCount() >= 1; }));
}
CHECK(![g.queue sharedReplyReader]->driven());
kext2->wake(); // the detached thread wakes, sees it is stopping, and ends
}
}
// A command buffer too large for half its queue's ring puts its whole COMMAND_BUFFER message
// in a region block, which the ring names with a COMMAND_BUFFER_IN_REGION whose seqno the
// completion carries; the block goes back as the buffer completes.
struct BlockLog {
std::vector<uint64_t> allocated;
std::vector<uint64_t> released;
uint64_t next = RGFX_ALLOCATIONS_OFFSET + 0x10000;
static bool alloc(void *c, uint64_t size, uint64_t align, uint64_t *offset)
{
BlockLog *log = static_cast<BlockLog *>(c);
uint64_t at = (log->next + align - 1) & ~(align - 1);
log->next = at + size;
log->allocated.push_back(at);
*offset = at;
return true;
}
static void release(void *c, uint64_t offset)
{
static_cast<BlockLog *>(c)->released.push_back(offset);
}
};
void test_command_buffer_out_of_line()
{
// Outside the pool: the queue's pool of blocks goes back into the region as the queue goes,
// which the pool's drain may do.
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x100000, 0);
RgfxRegion region(mem.data(), mem.size());
BlockLog blocks;
region.setBlockSource(&BlockLog::alloc, &BlockLog::release, &blocks);
@autoreleasepool {
QueueFixture f(0x1000); // up to 2 KiB on the ring
f.queue.region = &region;
// A small buffer still rides the ring.
id<MTLCommandBuffer> small = [f.queue commandBuffer];
[small commit];
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(f.submit.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER);
CHECK(blocks.allocated.empty());
RgfxCbComplete smallDone = cbComplete(h.seqno, ((RgfxResource *)small).rgfxObjId);
CHECK(f.completion.postFromHost(&smallDone, sizeof(smallDone)));
[small waitUntilCompleted];
// 200 fills: far past half the ring.
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
for (int i = 0; i < 200; i++)
[blit fillBuffer:handle(40) range:NSMakeRange(4 * i, 4) value:(uint8_t)i];
[blit endEncoding];
__block int fired = 0;
[cb addCompletedHandler:^(id<MTLCommandBuffer> done) {
(void)done;
fired++;
}];
[cb commit];
CHECK(f.submit.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER_IN_REGION);
CHECK(h.size == sizeof(RgfxCommandBufferInRegion));
RgfxCommandBufferInRegion ref = {};
std::memcpy(&ref, bytes.data(), sizeof(ref));
CHECK(blocks.allocated.size() == 1 && ref.region_offset == blocks.allocated[0]);
CHECK(ref.byte_length > 2048 && ref.byte_length % 8 == 0);
// The block holds the whole message: a COMMAND_BUFFER of that length, seqno 0, its ops.
RgfxCommandBuffer body = {};
std::memcpy(&body, mem.data() + ref.region_offset, sizeof(body));
CHECK(body.header.type == RGFX_CMD_COMMAND_BUFFER);
CHECK(body.header.size == ref.byte_length);
CHECK(body.header.seqno == 0);
CHECK(body.cb_obj_id == ((RgfxResource *)cb).rgfxObjId);
CHECK(body.op_bytes == ref.byte_length - RGFX_COMMAND_BUFFER_OPS_OFFSET);
RgfxOpHeader first = {};
std::memcpy(&first, mem.data() + ref.region_offset + RGFX_COMMAND_BUFFER_OPS_OFFSET,
sizeof(first));
CHECK(first.tag == RGFX_OP_ENCODER_BEGIN_BLIT);
// Its completion carries the reference's seqno; the block goes back to the queue's pool
// then, still the process's, and the next buffer too large for the ring takes it again.
CHECK(blocks.released.empty());
RgfxCbComplete done = cbComplete(h.seqno, ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
CHECK(fired == 1);
CHECK(cb.status == MTLCommandBufferStatusCompleted);
CHECK(blocks.released.empty());
id<MTLCommandBuffer> next = [f.queue commandBuffer];
id<MTLBlitCommandEncoder> nextBlit = [next blitCommandEncoder];
for (int i = 0; i < 200; i++)
[nextBlit fillBuffer:handle(40) range:NSMakeRange(4 * i, 4) value:(uint8_t)i];
[nextBlit endEncoding];
[next commit];
CHECK(f.submit.next(&h, &bytes));
CHECK(h.type == RGFX_CMD_COMMAND_BUFFER_IN_REGION);
RgfxCommandBufferInRegion nextRef = {};
std::memcpy(&nextRef, bytes.data(), sizeof(nextRef));
CHECK(nextRef.region_offset == ref.region_offset && blocks.allocated.size() == 1);
RgfxCbComplete nextDone = cbComplete(h.seqno, ((RgfxResource *)next).rgfxObjId);
CHECK(f.completion.postFromHost(&nextDone, sizeof(nextDone)));
[next waitUntilCompleted];
CHECK(next.status == MTLCommandBufferStatusCompleted && blocks.released.empty());
// With no region, a buffer too large for the ring fails as out of memory, off the
// committing thread, and never reaches the ring.
QueueFixture g(0x1000);
id<MTLCommandBuffer> lost = [g.queue commandBuffer];
id<MTLBlitCommandEncoder> b2 = [lost blitCommandEncoder];
for (int i = 0; i < 200; i++)
[b2 fillBuffer:handle(40) range:NSMakeRange(4 * i, 4) value:1];
[b2 endEncoding];
dispatch_semaphore_t failed = dispatch_semaphore_create(0);
__block int failedOnMain = -1;
[lost addCompletedHandler:^(id<MTLCommandBuffer> d) {
failedOnMain = pthread_main_np();
(void)d;
dispatch_semaphore_signal(failed);
}];
[lost commit];
CHECK(dispatch_semaphore_wait(failed, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
CHECK(lost.status == MTLCommandBufferStatusError);
CHECK(lost.error.code == MTLCommandBufferErrorOutOfMemory);
CHECK(failedOnMain == 0);
CHECK(!g.submit.next(&h, &bytes));
f.queue.region = nullptr;
}
}
// A buffer's completion is expected before the host can see the buffer: at the doorbell that
// publishing it rings, the reader already awaits its seqno.
struct ExpectAtDoorbell {
TestRing *submit = nullptr;
RgfxReplyReader *reader = nullptr;
int rung = 0;
bool awaited = false;
uint64_t seqno = 0;
static void ring(void *c, uint32_t)
{
ExpectAtDoorbell *e = static_cast<ExpectAtDoorbell *>(c);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
if (e->submit->next(&h, &bytes)) {
e->rung++;
e->seqno = h.seqno;
e->awaited = e->reader->awaitingCompletion(h.seqno);
}
}
};
void test_completion_expected_before_publish()
{
@autoreleasepool {
ExpectAtDoorbell e;
QueueFixture f(0x8000, 0, &ExpectAtDoorbell::ring, &e);
e.submit = &f.submit;
e.reader = [f.queue sharedReplyReader].get();
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
[cb commit];
CHECK(e.rung == 1);
CHECK(e.awaited);
CHECK(cb.status == MTLCommandBufferStatusCommitted);
RgfxCbComplete done = cbComplete(e.seqno, ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
}
}
// -commandBuffer blocks while maxCommandBufferCount buffers of the queue are alive and not
// completed, as Metal's does; a buffer that completes, or one released uncommitted, gives its
// slot back; and a completed handler that makes the next buffer does not wait for its own.
void test_command_buffer_back_pressure()
{
@autoreleasepool {
QueueFixture f(0x8000, 2);
CHECK(f.queue.maxCommandBufferCount == 2);
QueueFixture d;
CHECK(d.queue.maxCommandBufferCount == 64);
FakeKext *kext = new FakeKext();
RgfxCompletionThread thread(&FakeKext::wait, kext);
CHECK(thread.start());
thread.add([f.queue sharedReplyReader]);
id<MTLCommandBuffer> a = [f.queue commandBuffer];
id<MTLCommandBuffer> b = [f.queue commandBuffer];
[a commit];
uint64_t sa = f.nextSeqno();
[b commit];
uint64_t sb = f.nextSeqno();
// A third waits for a's completion, posted 50 ms from now.
RgfxCommandQueue *queue = f.queue;
std::atomic<bool> got{false};
std::atomic<bool> *gotp = &got;
id<MTLCommandBuffer> third = nil;
id<MTLCommandBuffer> __strong *thirdp = &third;
dispatch_semaphore_t made = dispatch_semaphore_create(0);
std::thread maker([queue, gotp, made, thirdp] {
@autoreleasepool {
*thirdp = [queue commandBuffer];
gotp->store(true);
dispatch_semaphore_signal(made);
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(50));
CHECK(!got.load()); // still blocked: two in flight
RgfxCbComplete done = cbComplete(sa, ((RgfxResource *)a).rgfxObjId);
hostPost(f.completion, *kext, &done, sizeof(done));
CHECK(dispatch_semaphore_wait(made, dispatch_time(DISPATCH_TIME_NOW, 5 * NSEC_PER_SEC)) == 0);
maker.join();
CHECK(got.load() && third != nil);
// b and the third hold both slots. Released uncommitted, the third gives its slot back.
third = nil;
id<MTLCommandBuffer> fourth = nil;
@autoreleasepool {
fourth = [f.queue commandBuffer]; // did not block
}
CHECK(fourth != nil);
RgfxCbComplete bDone = cbComplete(sb, ((RgfxResource *)b).rgfxObjId);
hostPost(f.completion, *kext, &bDone, sizeof(bDone));
[b waitUntilCompleted];
kext->close();
CHECK(eventually([&] { return !thread.running(); }));
// With one slot, a completed handler that makes the next buffer has the slot back.
QueueFixture g(0x8000, 1);
id<MTLCommandBuffer> first = [g.queue commandBuffer];
__block id<MTLCommandBuffer> next = nil;
RgfxCommandQueue *gq = g.queue;
[first addCompletedHandler:^(id<MTLCommandBuffer> x) {
(void)x;
next = [gq commandBuffer];
}];
[first commit];
RgfxCbComplete d1 = cbComplete(g.nextSeqno(), ((RgfxResource *)first).rgfxObjId);
CHECK(g.completion.postFromHost(&d1, sizeof(d1)));
[first waitUntilCompleted]; // pumps: the handler runs here, and gets its buffer
CHECK(next != nil);
}
}
// A texture a command buffer names stays on the host while the buffer is in flight, though the
// app let it go, as Metal's buffer keeps what it encodes: its OBJECT_DESTROY comes after the
// buffer's handlers and before its waiter wakes, and its resource id goes to the next texture only
// after that. A texture the buffer never names goes at once meanwhile. A buffer made with
// unretained references keeps what it names too, though it answers retainedReferences NO.
void test_texture_destroy_waits_for_buffers()
{
@autoreleasepool {
QueueFixture f;
(void)expectQueueCreate(f.control);
int calls = 0;
f.ids.setResourceIdSource(&oneChunk, &calls);
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:8
height:8
mipmapped:NO];
auto texture = [&] {
RgfxTexture *t = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&f.ser];
CHECK(t != nil);
(void)expectMessage<RgfxTextureCreate>(f.control, RGFX_CMD_TEXTURE_CREATE);
return t;
};
uint64_t texObjId = 0, texResourceId = 0;
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
CHECK(cb.retainedReferences);
@autoreleasepool {
RgfxTexture *tex = texture();
texObjId = tex.rgfxObjId;
texResourceId = [tex gpuResourceID]._impl;
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit generateMipmapsForTexture:tex];
[blit endEncoding];
[cb commit];
} // the app lets the texture go while the buffer is in flight
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(!f.control.next(&h, &bytes)); // no destroy yet
// A texture made meanwhile gets another id: the first's is still the host's. It goes at once.
uint64_t otherObjId = 0;
@autoreleasepool {
RgfxTexture *other = texture();
otherObjId = other.rgfxObjId;
CHECK([other gpuResourceID]._impl != texResourceId);
}
CHECK(expectMessage<RgfxObjectDestroy>(f.control, RGFX_CMD_OBJECT_DESTROY).obj_id ==
otherObjId);
__block bool destroyedBeforeHandler = true;
TestRing *control = &f.control;
[cb addCompletedHandler:^(id<MTLCommandBuffer> d) {
(void)d;
RgfxMsgHeader hh = {};
std::vector<uint8_t> bb;
destroyedBeforeHandler = control->next(&hh, &bb);
}];
RgfxCbComplete done = cbComplete(f.nextSeqno(), ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
CHECK(!destroyedBeforeHandler);
CHECK(expectMessage<RgfxObjectDestroy>(f.control, RGFX_CMD_OBJECT_DESTROY).obj_id == texObjId);
CHECK(ringEmpty(f.control));
// Unretained references: kept all the same.
id<MTLCommandBuffer> unretained = [f.queue commandBufferWithUnretainedReferences];
CHECK(!unretained.retainedReferences);
@autoreleasepool {
RgfxTexture *tex = texture();
texObjId = tex.rgfxObjId;
id<MTLBlitCommandEncoder> blit = [unretained blitCommandEncoder];
[blit generateMipmapsForTexture:tex];
[blit endEncoding];
[unretained commit];
}
CHECK(ringEmpty(f.control));
done = cbComplete(f.nextSeqno(), ((RgfxResource *)unretained).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[unretained waitUntilCompleted];
CHECK(expectMessage<RgfxObjectDestroy>(f.control, RGFX_CMD_OBJECT_DESTROY).obj_id == texObjId);
}
}
// A buffer whose completion never comes holds back only what it names: a buffer it fills stays
// on the host until the command buffer goes, with its queue's reader, while one it never names
// goes at once. Its completion group is left at its dealloc.
void test_uncompleted_buffer_releases()
{
@autoreleasepool {
QueueFixture f;
(void)expectQueueCreate(f.control);
uint64_t namedId = 0, otherId = 0;
{
RgfxReplyReader reader(f.completion.base(), f.completion.dataSize);
f.queue.replyReader = &reader;
@autoreleasepool {
RgfxBuffer *named = [RgfxBuffer bufferWithLength:64
options:MTLResourceStorageModePrivate
device:nil
serializer:&f.ser];
RgfxBuffer *other = [RgfxBuffer bufferWithLength:64
options:MTLResourceStorageModePrivate
device:nil
serializer:&f.ser];
namedId = named.rgfxObjId;
otherId = other.rgfxObjId;
drainRing(f.control);
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit fillBuffer:named range:NSMakeRange(0, 64) value:1];
[blit endEncoding];
[cb commit];
(void)f.nextSeqno();
CHECK(cb.status == MTLCommandBufferStatusCommitted);
}
CHECK(nextDestroyed(f.control) == otherId && ringEmpty(f.control));
f.queue.replyReader = nullptr;
} // the reader goes, and with it its handler, the buffer's last hold
CHECK(nextDestroyed(f.control) == namedId && ringEmpty(f.control));
}
}
} // namespace
// The layout of a Managed texture's CPU copy, for the cases crates/reims-graphics/src/managed.rs
// holds too: a 2D RGBA8 texture with three levels, a BC1 one whose sides are no multiple of its
// blocks, a cube array, and a 3D one; and the blocks of a few formats.
void test_managed_layout()
{
auto desc = [](uint32_t type, uint32_t w, uint32_t h, uint32_t d, uint32_t levels,
uint32_t array) {
RgfxTextureDescriptor t = {};
t.pixel_format = 70;
t.texture_type = type;
t.width = w;
t.height = h;
t.depth = d;
t.mipmap_level_count = levels;
t.array_length = array;
t.sample_count = 1;
return t;
};
auto level = [](const RgfxManagedLayout &l, uint32_t i, uint64_t offset, uint64_t row,
uint64_t image, uint64_t slice) {
const RgfxManagedLevel &lv = l.level(i);
return lv.offset == offset && lv.bytesPerRow == row && lv.bytesPerImage == image &&
lv.bytesPerSlice == slice;
};
RgfxFormatBlock rgba = {}, bc1 = {}, astc = {}, none = {};
CHECK(rgfxPixelFormatBlock(MTLPixelFormatRGBA8Unorm, &rgba) && rgba.bytes == 4 &&
rgba.width == 1 && rgba.linear);
CHECK(rgfxPixelFormatBlock(MTLPixelFormatBC1_RGBA, &bc1) && bc1.bytes == 8 &&
bc1.width == 4 && bc1.height == 4 && !bc1.linear);
CHECK(rgfxPixelFormatBlock(MTLPixelFormatASTC_10x8_LDR, &astc) && astc.bytes == 16 &&
astc.width == 10 && astc.height == 8);
CHECK(!rgfxPixelFormatBlock(MTLPixelFormatDepth32Float, &none));
CHECK(!rgfxPixelFormatBlock(191, &none));
RgfxManagedLayout l;
CHECK(l.init(desc(2, 100, 60, 1, 3, 1), rgba));
CHECK(level(l, 0, 0, 512, 30720, 30720) && level(l, 1, 30720, 256, 7680, 7680) &&
level(l, 2, 38400, 256, 3840, 3840));
CHECK(l.size() == 42240 && l.slices() == 1);
CHECK(l.init(desc(2, 30, 30, 1, 2, 1), bc1));
CHECK(level(l, 0, 0, 256, 2048, 2048) && level(l, 1, 2048, 256, 1024, 1024));
uint64_t at = 0;
const uint64_t bcOrigin[3] = {4, 8, 0}, bcSize[3] = {26, 22, 1}, offBlock[3] = {2, 0, 0};
CHECK(l.region(0, 0, bcOrigin, bcSize, &at) && at == 512 + 8);
CHECK(!l.region(0, 0, offBlock, bcSize, &at));
CHECK(l.init(desc(6, 16, 16, 1, 2, 2), rgba));
CHECK(l.slices() == 12 && level(l, 0, 0, 256, 4096, 4096) &&
level(l, 1, 49152, 256, 2048, 2048) && l.size() == 49152 + 12 * 2048);
const uint64_t o[3] = {2, 1, 0}, sz[3] = {4, 3, 1};
CHECK(l.region(1, 3, o, sz, &at) && at == 49152 + 3 * 2048 + 256 + 8);
CHECK(!l.region(1, 12, o, sz, &at) && !l.region(2, 0, o, sz, &at));
CHECK(l.init(desc(7, 8, 8, 4, 2, 1), rgba));
CHECK(level(l, 0, 0, 256, 2048, 8192) && level(l, 1, 8192, 256, 1024, 2048));
CHECK(l.init(desc(2, 8, 8, 4, 1, 1), rgba) && l.size() == 2048);
CHECK(!l.init(desc(2, 8, 8, 1, 5, 1), rgba)); // more levels than 8 halves to
CHECK(!l.init(desc(2, 0, 8, 1, 1, 1), rgba));
}
// A Managed buffer's contents are a region block: didModifyRange: tells the host the range
// (BUFFER_DID_MODIFY_RANGE) and a Shared buffer's posts nothing.
void test_managed_buffer_range()
{
Fixture fx;
std::vector<uint8_t> mem(0x800000, 0);
RgfxRegion region(mem.data(), mem.size());
RgfxRegion::Block block = region.allocate(0x1000);
CHECK(block.ok);
const MTLResourceOptions managed = MTLResourceStorageModeManaged;
RgfxBuffer *buf = [RgfxBuffer
bufferOverHostMemoryWithContents:const_cast<uint8_t *>(block.ptr)
regionOffset:block.offset
length:0x1000
options:managed
deallocator:nil
device:nil
serializer:&fx.ser];
CHECK(buf != nil && [buf contents] == block.ptr);
CHECK([buf storageMode] == MTLStorageModeManaged &&
[buf cpuCacheMode] == MTLCPUCacheModeDefaultCache &&
[buf hazardTrackingMode] == MTLHazardTrackingModeTracked);
auto create =
expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(create.options == static_cast<uint32_t>(managed));
CHECK(create.region_offset == block.offset);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[buf didModifyRange:NSMakeRange(0x40, 0x20)];
[buf didModifyRange:NSMakeRange(0x40, 0)];
#pragma clang diagnostic pop
auto range =
expectMessage<RgfxBufferDidModifyRange>(fx.ring, RGFX_CMD_BUFFER_DID_MODIFY_RANGE);
CHECK(range.obj_id == buf.rgfxObjId && range.location == 0x40 && range.length == 0x20);
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes)); // an empty range posts nothing
RgfxBuffer *shared = [RgfxBuffer
bufferOverHostMemoryWithContents:const_cast<uint8_t *>(block.ptr)
regionOffset:block.offset
length:0x1000
options:MTLResourceStorageModeShared
deallocator:nil
device:nil
serializer:&fx.ser];
expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[shared didModifyRange:NSMakeRange(0, 0x10)];
#pragma clang diagnostic pop
CHECK(!fx.ring.next(&extra, &extraBytes));
}
// A Managed texture's CPU copy is a block of the region, made over a Shared buffer and named by
// its MANAGED_TEXTURE_CREATE: replaceRegion: writes it at the layout's rows and posts the region
// (TEXTURE_REPLACE_REGION); getBytes: reads it back with no message; a region past the level
// writes nothing and posts nothing. A format no CPU copy holds makes no Managed texture.
void test_managed_texture_cpu_copy()
{
Fixture fx;
std::vector<uint8_t> mem(0x800000, 0xff); // pre-dirtied, as BAR memory
RgfxRegion region(mem.data(), mem.size());
@autoreleasepool {
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:100
height:60
mipmapped:YES];
desc.mipmapLevelCount = 3;
desc.storageMode = MTLStorageModeManaged;
RgfxTexture *tex = [RgfxTexture managedTextureWithDescriptor:desc
region:&region
device:nil
serializer:&fx.ser];
CHECK(tex != nil);
CHECK([tex storageMode] == MTLStorageModeManaged);
auto cpu =
expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(cpu.length == 42240 && cpu.options == MTLResourceStorageModeShared);
auto create = expectMessage<RgfxManagedTextureCreate>(fx.ring,
RGFX_CMD_MANAGED_TEXTURE_CREATE);
CHECK(create.obj_id == tex.rgfxObjId && create.cpu_buffer_obj_id == cpu.obj_id);
CHECK(create.resource_id == [tex gpuResourceID]._impl && create.gpu_address != 0);
CHECK(create.bytes_per_block == 4 && create.block_width == 1 &&
create.block_height == 1 && create.flags == RGFX_MANAGED_TEXTURE_LINEAR);
CHECK(create.desc.mipmap_level_count == 3 &&
create.desc.options == static_cast<uint32_t>(desc.resourceOptions));
uint8_t *copy = mem.data() + cpu.region_offset;
CHECK(copy[0] == 0 && copy[42239] == 0); // a new Managed texture reads zero
// Level 1, a 4x3 region at (2, 1): its rows at the layout's 256-byte pitch.
uint8_t pixels[3][16];
for (int r = 0; r < 3; r++)
for (int i = 0; i < 16; i++)
pixels[r][i] = static_cast<uint8_t>(r * 16 + i + 1);
[tex replaceRegion:MTLRegionMake2D(2, 1, 4, 3)
mipmapLevel:1
withBytes:pixels
bytesPerRow:16];
for (int r = 0; r < 3; r++)
CHECK(std::memcmp(copy + 30720 + (1 + r) * 256 + 8, pixels[r], 16) == 0);
CHECK(copy[30720 + 256 + 7] == 0 && copy[30720 + 256 + 24] == 0);
auto replaced = expectMessage<RgfxTextureReplaceRegion>(fx.ring,
RGFX_CMD_TEXTURE_REPLACE_REGION);
CHECK(replaced.obj_id == tex.rgfxObjId && replaced.level == 1 && replaced.slice == 0);
CHECK(replaced.origin[0] == 2 && replaced.origin[1] == 1 && replaced.origin[2] == 0);
CHECK(replaced.size[0] == 4 && replaced.size[1] == 3 && replaced.size[2] == 1);
// getBytes: reads the copy, here as the GPU's synchronize would have left it.
copy[30720 + 2 * 256 + 16] = 0xab;
uint8_t back[2][8] = {};
[tex getBytes:back bytesPerRow:8 fromRegion:MTLRegionMake2D(3, 1, 2, 2) mipmapLevel:1];
CHECK(back[0][0] == pixels[0][4] && back[1][0] == pixels[1][4] && back[1][4] == 0xab);
RgfxMsgHeader extra = {};
std::vector<uint8_t> extraBytes;
CHECK(!fx.ring.next(&extra, &extraBytes)); // getBytes: posts nothing
// A region past the level writes nothing and posts nothing.
const uint8_t before = copy[30720 + 49 * 4];
[tex replaceRegion:MTLRegionMake2D(49, 0, 2, 1)
mipmapLevel:1
withBytes:pixels
bytesPerRow:16];
CHECK(copy[30720 + 49 * 4] == before);
CHECK(!fx.ring.next(&extra, &extraBytes));
// A depth texture keeps no CPU copy.
MTLTextureDescriptor *depth =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatDepth32Float
width:64
height:64
mipmapped:NO];
depth.storageMode = MTLStorageModeManaged;
CHECK([RgfxTexture managedTextureWithDescriptor:depth
region:&region
device:nil
serializer:&fx.ser] == nil);
CHECK(!fx.ring.next(&extra, &extraBytes));
}
}
// --- host objects go as the app lets them go ----------------------------------------------
// The obj_id of the OBJECT_DESTROY next on `ring`.
uint64_t nextDestroyed(TestRing &ring)
{
return expectMessage<RgfxObjectDestroy>(ring, RGFX_CMD_OBJECT_DESTROY).obj_id;
}
bool ringEmpty(TestRing &ring)
{
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
return !ring.next(&h, &bytes);
}
// Reads every message waiting on `ring` (the creates a test does not check).
void drainRing(TestRing &ring)
{
while (!ringEmpty(ring)) {
}
}
// newBufferWithBytesNoCopy: over app memory outside the region (RgfxBuffer.h): `contents` is the
// app's pointer and the buffer lies over a block of its own, seeded from the memory. A command
// buffer that uses it takes the CPU's writes into the block at its commit, and one that may write
// it gives the GPU's back at its completion, keeping the CPU's beside them; one that only reads
// it gives nothing back, nor does memory mapped read-only. A texture over it (CA's shape: offset
// 0x100, 1920-byte rows) writes through it. The deallocator gets the pointer and length once the
// host has dropped the buffer. Metal's refusals are nil: a length of 0, Private storage, a range
// not wholly mapped. A null pointer is contents of the buffer's own; bytes in the region are
// used in place.
void test_no_copy_buffers()
{
@autoreleasepool {
QueueFixture f;
(void)expectQueueCreate(f.control);
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x200000, 0xff);
RgfxRegion region(mem.data(), mem.size());
const MTLResourceOptions shared = MTLResourceStorageModeShared;
vm_address_t app = 0;
CHECK(vm_allocate(mach_task_self(), &app, 0x40000, VM_FLAGS_ANYWHERE) == KERN_SUCCESS);
uint8_t *p = reinterpret_cast<uint8_t *>(app);
std::memset(p, 0x11, 0x40000);
// What the deallocator got, which a block writes and a lambda reads.
struct Freed {
std::atomic<int> count{0};
void *at = nullptr;
NSUInteger length = 0;
} freedState;
Freed *freedLog = &freedState;
auto completeOn = [&](id<MTLCommandBuffer> cb) {
RgfxCbComplete done = cbComplete(f.nextSeqno(), ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
CHECK(cb.status == MTLCommandBufferStatusCompleted);
};
uint8_t *block = nullptr;
@autoreleasepool {
RgfxBuffer *b = [RgfxBuffer bufferWithBytesNoCopy:p
length:0x14000
options:shared
deallocator:^(void *q, NSUInteger l) {
freedLog->at = q;
freedLog->length = l;
freedLog->count++;
}
region:&region
device:nil
serializer:&f.ser];
CHECK(b != nil && [b contents] == p && b.length == 0x14000 && [b rgfxShadow] != nullptr);
auto create =
expectMessage<RgfxBufferOverHostMemory>(f.control, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(create.obj_id == b.rgfxObjId && create.length == 0x14000);
CHECK(create.region_offset >= region.floor());
block = mem.data() + create.region_offset;
CHECK(std::memcmp(block, p, 0x14000) == 0);
// A writing command buffer: the CPU's bytes go in at the commit.
p[0x10] = 0xa1;
p[0x13fff] = 0xa2;
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit fillBuffer:b range:NSMakeRange(0x8000, 0x100) value:0x77];
[blit endEncoding];
[cb commit];
CHECK(block[0x10] == 0xa1 && block[0x13fff] == 0xa2);
// The host fills; the CPU writes beside it meanwhile.
std::memset(block + 0x8000, 0x77, 0x100);
p[0x8100] = 0xa3;
CHECK(p[0x8000] == 0x11);
completeOn(cb);
CHECK(p[0x8000] == 0x77 && p[0x80ff] == 0x77 && p[0x8100] == 0xa3 && p[0x10] == 0xa1);
// One that only reads it gives nothing back.
RgfxRegion::Block other = region.allocate(0x1000);
RgfxBuffer *dst = [RgfxBuffer bufferOverHostMemoryWithContents:const_cast<uint8_t *>(other.ptr)
regionOffset:other.offset
length:0x1000
options:shared
deallocator:nil
device:nil
serializer:&f.ser];
id<MTLCommandBuffer> reads = [f.queue commandBuffer];
blit = [reads blitCommandEncoder];
[blit copyFromBuffer:b sourceOffset:0 toBuffer:dst destinationOffset:0 size:0x100];
[blit endEncoding];
[reads commit];
block[0x9000] = 0xb1; // not this buffer's to give back
completeOn(reads);
CHECK(p[0x9000] == 0x11);
block[0x9000] = 0x11;
// A texture over it, CA's shape, as a blit's destination.
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:468
height:36
mipmapped:NO];
td.storageMode = MTLStorageModeShared;
id<MTLTexture> tex = [b newTextureWithDescriptor:td offset:0x100 bytesPerRow:1920];
CHECK(tex != nil && tex.buffer == b);
id<MTLCommandBuffer> draws = [f.queue commandBuffer];
blit = [draws blitCommandEncoder];
[blit copyFromBuffer:dst
sourceOffset:0
sourceBytesPerRow:1920
sourceBytesPerImage:1920
sourceSize:MTLSizeMake(4, 1, 1)
toTexture:tex
destinationSlice:0
destinationLevel:0
destinationOrigin:MTLOriginMake(0, 0, 0)];
[blit endEncoding];
[draws commit];
block[0x100] = 0xc1;
completeOn(draws);
CHECK(p[0x100] == 0xc1);
tex = nil;
dst = nil;
CHECK(freedState.count == 0);
}
CHECK(eventually([&] { return freedState.count == 1; }));
CHECK(freedState.at == p && freedState.length == 0x14000);
drainRing(f.control);
// Metal's refusals.
auto noCopy = [&](void *ptr, NSUInteger length, MTLResourceOptions options) {
return [RgfxBuffer bufferWithBytesNoCopy:ptr
length:length
options:options
deallocator:nil
region:&region
device:nil
serializer:&f.ser];
};
CHECK(noCopy(p, 0, shared) == nil);
CHECK(noCopy(p, 0x1000, MTLResourceStorageModePrivate) == nil);
vm_address_t holed = 0;
CHECK(vm_allocate(mach_task_self(), &holed, 0x10000, VM_FLAGS_ANYWHERE) == KERN_SUCCESS);
CHECK(vm_deallocate(mach_task_self(), holed + 0x8000, 0x8000) == KERN_SUCCESS);
CHECK(noCopy(reinterpret_cast<void *>(holed + 0x10), 0x8000, shared) == nil);
@autoreleasepool {
// Any alignment, Managed too: its didModifyRange: takes the CPU's bytes first.
RgfxBuffer *odd = noCopy(reinterpret_cast<void *>(holed + 0x13), 0x100,
MTLResourceStorageModeManaged);
CHECK(odd != nil && [odd contents] == reinterpret_cast<void *>(holed + 0x13));
auto c = expectMessage<RgfxBufferOverHostMemory>(f.control, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
reinterpret_cast<uint8_t *>(holed)[0x14] = 0xd1;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
[odd didModifyRange:NSMakeRange(1, 1)];
#pragma clang diagnostic pop
CHECK(mem[c.region_offset + 1] == 0xd1);
auto range =
expectMessage<RgfxBufferDidModifyRange>(f.control, RGFX_CMD_BUFFER_DID_MODIFY_RANGE);
CHECK(range.obj_id == odd.rgfxObjId && range.location == 1 && range.length == 1);
// Read-only memory: made, never written back.
CHECK(vm_protect(mach_task_self(), holed, 0x4000, false, VM_PROT_READ) == KERN_SUCCESS);
RgfxBuffer *ro = noCopy(reinterpret_cast<void *>(holed), 0x4000, shared);
CHECK(ro != nil && [ro rgfxShadow] != nullptr && ![ro rgfxShadow]->writable());
// A null pointer: zeroed contents of its own, in the region, with no shadow. The
// deallocator gets null.
std::atomic<void *> nullFreedState{reinterpret_cast<void *>(1)};
std::atomic<void *> *nullFreed = &nullFreedState;
@autoreleasepool {
RgfxBuffer *own = [RgfxBuffer bufferWithBytesNoCopy:nullptr
length:0x2000
options:shared
deallocator:^(void *q, NSUInteger) {
nullFreed->store(q);
}
region:&region
device:nil
serializer:&f.ser];
CHECK(own != nil && [own rgfxShadow] == nullptr &&
region.contains([own contents], 0x2000));
CHECK(static_cast<uint8_t *>([own contents])[0x1fff] == 0);
}
CHECK(eventually([&] { return nullFreedState.load() == nullptr; }));
// Bytes already in the region: in place.
RgfxRegion::Block inRegion = region.allocate(0x1000);
RgfxBuffer *placed = noCopy(const_cast<uint8_t *>(inRegion.ptr), 0x1000, shared);
CHECK(placed != nil && [placed rgfxShadow] == nullptr);
drainRing(f.control);
(void)ro;
}
drainRing(f.control);
vm_deallocate(mach_task_self(), holed, 0x8000);
vm_deallocate(mach_task_self(), app, 0x40000);
}
CHECK(!RgfxMemoryShadow::anyLive());
}
// A Managed texture's CPU copy goes with it: the texture's destroy, then its copy's buffer's,
// then the copy's block goes back.
void test_managed_texture_copy_block_after_destroys()
{
Fixture fx;
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x100000, 0);
RgfxRegion region(mem.data(), mem.size());
struct Log {
BlockLog blocks;
TestRing *ring;
std::vector<uint64_t> seenAtRelease; // the objects destroyed on the ring by each release
static bool alloc(void *c, uint64_t size, uint64_t align, uint64_t *offset)
{
return BlockLog::alloc(&static_cast<Log *>(c)->blocks, size, align, offset);
}
static void release(void *c, uint64_t offset)
{
Log *log = static_cast<Log *>(c);
BlockLog::release(&log->blocks, offset);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (log->ring->next(&h, &bytes)) {
RgfxObjectDestroy d = {};
if (h.type == RGFX_CMD_OBJECT_DESTROY && bytes.size() >= sizeof(d)) {
std::memcpy(&d, bytes.data(), sizeof(d));
log->seenAtRelease.push_back(d.obj_id);
}
}
}
} log;
log.ring = &fx.ring;
region.setBlockSource(&Log::alloc, &Log::release, &log);
uint64_t texId = 0, bufId = 0;
@autoreleasepool {
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:64
height:64
mipmapped:NO];
td.storageMode = MTLStorageModeManaged;
RgfxTexture *t = [RgfxTexture managedTextureWithDescriptor:td
region:&region
device:nil
serializer:&fx.ser];
CHECK(t != nil);
texId = t.rgfxObjId;
bufId = expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY)
.obj_id;
drainRing(fx.ring);
CHECK(log.blocks.allocated.size() == 1 && log.blocks.released.empty());
}
CHECK(log.blocks.released == log.blocks.allocated);
CHECK(log.seenAtRelease == std::vector<uint64_t>({texId, bufId}));
CHECK(ringEmpty(fx.ring));
}
// A queue's ring carries only its command buffers: every create and destroy of the objects they
// use rides the control ring (ring 0), which the kext checks, and nothing else rides the queue's,
// whose host side refuses any other type. Objects of every kind are made, used by a command
// buffer committed on the queue, and let go.
void test_queue_ring_carries_only_command_buffers()
{
QueueFixture f;
int calls = 0;
f.ids.setResourceIdSource(&oneChunk, &calls);
id<MTLCommandBuffer> cb = nil;
@autoreleasepool {
MTLHeapDescriptor *hd = [MTLHeapDescriptor new];
hd.size = 0x10000;
hd.type = MTLHeapTypePlacement;
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:hd device:nil serializer:&f.ser];
id<MTLBuffer> placed = [heap newBufferWithLength:0x100
options:MTLResourceStorageModePrivate
offset:0];
RgfxBuffer *buffer = [RgfxBuffer bufferWithLength:0x1000
options:MTLResourceStorageModePrivate
device:nil
serializer:&f.ser];
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:8
height:8
mipmapped:NO];
RgfxTexture *texture = [RgfxTexture textureWithDescriptor:td
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&f.ser];
id<MTLSamplerState> sampler =
[RgfxSampler samplerWithDescriptor:[MTLSamplerDescriptor new] device:nil serializer:&f.ser];
id<MTLDepthStencilState> depth =
[RgfxDepthStencilState depthStencilStateWithDescriptor:[MTLDepthStencilDescriptor new]
device:nil
serializer:&f.ser];
id<MTLEvent> event = [RgfxEvent eventWithDevice:nil serializer:&f.ser];
id<MTLFence> fence = [RgfxFence fenceWithDevice:nil serializer:&f.ser];
CHECK(heap != nil && placed != nil && buffer != nil && texture != nil && sampler != nil &&
depth != nil && event != nil && fence != nil);
cb = [f.queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit fillBuffer:buffer range:NSMakeRange(0, 0x100) value:7];
[blit copyFromBuffer:buffer sourceOffset:0 toBuffer:placed destinationOffset:0 size:0x100];
[blit updateFence:fence];
[blit endEncoding];
[cb encodeSignalEvent:event value:1];
[cb commit];
}
const std::set<uint32_t> queueTypes = {RGFX_CMD_COMMAND_BUFFER,
RGFX_CMD_COMMAND_BUFFER_IN_REGION};
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
int buffers = 0;
uint64_t seqno = 0;
while (f.submit.next(&h, &bytes)) {
CHECK(queueTypes.count(h.type) == 1);
seqno = h.seqno;
buffers++;
}
CHECK(buffers == 1);
// The buffer completes, so the destroys of what it used, held back for it, go too.
RgfxCbComplete done = cbComplete(seqno, ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
@autoreleasepool {
cb = nil;
}
std::set<uint32_t> lifecycle;
while (f.control.next(&h, &bytes)) {
CHECK(queueTypes.count(h.type) == 0);
lifecycle.insert(h.type);
}
for (uint32_t type : {RGFX_CMD_HEAP_CREATE, RGFX_CMD_BUFFER_AT_OFFSET, RGFX_CMD_BUFFER_CREATE,
RGFX_CMD_TEXTURE_CREATE, RGFX_CMD_SAMPLER_CREATE,
RGFX_CMD_DEPTH_STENCIL_CREATE, RGFX_CMD_EVENT_CREATE,
RGFX_CMD_FENCE_CREATE, RGFX_CMD_OBJECT_DESTROY})
CHECK(lifecycle.count(type) == 1);
}
// A heap of no bytes is nil, as Metal answers one, and so is a heap or device buffer for which
// the context's range has no GPU address left: neither posts anything, so the host is never
// asked for an object the app does not hold.
void test_heaps_with_no_bytes_or_address_are_nil()
{
Fixture fx;
@autoreleasepool {
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = 0;
d.type = MTLHeapTypePlacement;
CHECK([RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser] == nil);
d.storageMode = MTLStorageModeShared;
CHECK([RgfxHeap heapOverHostMemoryWithDescriptor:d
regionOffset:RGFX_CONTEXT_ALLOCATIONS_OFFSET
contents:nullptr
deallocator:nil
device:nil
serializer:&fx.ser] == nil);
d.size = RGFX_CONTEXT_VA_SPAN;
d.storageMode = MTLStorageModePrivate;
CHECK([RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser] == nil);
CHECK([RgfxBuffer bufferWithLength:RGFX_CONTEXT_VA_SPAN
options:MTLResourceStorageModePrivate
device:nil
serializer:&fx.ser] == nil);
CHECK(ringEmpty(fx.ring));
d.size = 0x10000;
CHECK([RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser] != nil);
CHECK(expectMessage<RgfxHeapCreate>(fx.ring, RGFX_CMD_HEAP_CREATE).size_bytes == 0x10000);
}
drainRing(fx.ring);
}
// A Shared heap's placed buffers alias its bytes, as Metal's do: a buffer is the heap's bytes at
// its offset, two at one offset are the same bytes, and each is at the heap's GPU address plus
// its offset; one that runs past the heap is nil, and posts nothing. A Private heap's placed
// buffer is at its address plus the offset too.
void test_shared_heap_buffers_alias_its_bytes()
{
Fixture fx;
static uint8_t bytes[0x10000];
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = sizeof(bytes);
d.storageMode = MTLStorageModeShared;
d.type = MTLHeapTypePlacement;
@autoreleasepool {
RgfxHeap *heap = [RgfxHeap heapOverHostMemoryWithDescriptor:d
regionOffset:RGFX_CONTEXT_ALLOCATIONS_OFFSET
contents:bytes
deallocator:nil
device:nil
serializer:&fx.ser];
CHECK(heap != nil);
const uint64_t at =
expectMessage<RgfxHeapOverHostMemory>(fx.ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY)
.gpu_address;
CHECK(at != 0);
id<MTLBuffer> a = [heap newBufferWithLength:0x1000
options:MTLResourceStorageModeShared
offset:0x2000];
id<MTLBuffer> b = [heap newBufferWithLength:0x800
options:MTLResourceStorageModeShared
offset:0x2000];
CHECK(a != nil && b != nil);
auto placed = expectMessage<RgfxBufferAtOffset>(fx.ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(placed.heap_obj_id == heap.rgfxObjId && placed.offset == 0x2000 &&
placed.length == 0x1000);
drainRing(fx.ring);
CHECK([a contents] == bytes + 0x2000 && [b contents] == [a contents]);
CHECK(a.gpuAddress == at + 0x2000 && b.gpuAddress == at + 0x2000);
static_cast<uint8_t *>([a contents])[5] = 0xc3;
CHECK(static_cast<uint8_t *>([b contents])[5] == 0xc3 && bytes[0x2005] == 0xc3);
CHECK([heap newBufferWithLength:0x2000
options:MTLResourceStorageModeShared
offset:sizeof(bytes) - 0x1000] == nil);
CHECK([heap newBufferWithLength:1
options:MTLResourceStorageModeShared
offset:sizeof(bytes) + 1] == nil);
CHECK(ringEmpty(fx.ring));
MTLHeapDescriptor *pd = [MTLHeapDescriptor new];
pd.size = 0x10000;
pd.storageMode = MTLStorageModePrivate;
pd.type = MTLHeapTypePlacement;
RgfxHeap *priv = [RgfxHeap heapWithDescriptor:pd device:nil serializer:&fx.ser];
const uint64_t privAt =
expectMessage<RgfxHeapCreate>(fx.ring, RGFX_CMD_HEAP_CREATE).gpu_address;
id<MTLBuffer> c = [priv newBufferWithLength:0x100
options:MTLResourceStorageModePrivate
offset:0x4000];
CHECK(c != nil && c.gpuAddress == privAt + 0x4000);
drainRing(fx.ring);
}
drainRing(fx.ring);
}
// What a fake device answers a heap texture size query: 264192 bytes at 128, as Metal answers a
// 256 x 256 RGBA8Unorm texture (M3 Max, macOS 27).
bool askTextureSize(void *, const void *, uint32_t, void *reply, uint32_t capacity,
uint32_t *reply_size)
{
RgfxSizeAndAlign answer = {};
answer.header = {RGFX_EVT_SIZE_AND_ALIGN, sizeof(answer), 1};
answer.status = RGFX_STATUS_OK;
answer.size = 264192;
answer.align = 128;
CHECK(capacity >= sizeof(answer));
std::memcpy(reply, &answer, sizeof(answer));
*reply_size = sizeof(answer);
return true;
}
// An Automatic heap places what it makes as Metal's does, in the sequence measured on the M3
// Max under macOS 27 (RgfxHeapRanges.hpp): its size rounded up to the 16 KiB page, buffers at
// their length and textures at the device's size, each at the lowest free offset at its
// alignment, routed as a placement at that offset, and answering heapOffset 0; usedSize and
// maxAvailableSizeWithAlignment: follow, a resource gives its bytes back when freed or made
// aliasable (once), and one no free run holds is nil and posts nothing. A Placement heap
// answers 0 for both and places nothing itself.
void test_automatic_heap_places_as_metal()
{
Fixture fx;
fx.ser.setAsker(&askTextureSize, nullptr);
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = 1000000;
d.storageMode = MTLStorageModePrivate;
d.type = MTLHeapTypeAutomatic;
const MTLResourceOptions o = MTLResourceStorageModePrivate;
@autoreleasepool {
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser];
CHECK(heap != nil);
const RgfxHeapCreate made = expectMessage<RgfxHeapCreate>(fx.ring, RGFX_CMD_HEAP_CREATE);
CHECK(made.heap_type == MTLHeapTypeAutomatic && made.size_bytes == 1000000);
CHECK(heap.size == 1015808 && heap.currentAllocatedSize == 1015808);
CHECK(heap.usedSize == 0 && [heap maxAvailableSizeWithAlignment:65536] == 1015808);
auto placed = [&](uint64_t offset, uint64_t length) {
auto m = expectMessage<RgfxBufferAtOffset>(fx.ring, RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(m.heap_obj_id == heap.rgfxObjId && m.offset == offset && m.length == length);
};
id<MTLBuffer> b1 = [heap newBufferWithLength:100 options:o];
placed(0, 100);
CHECK(b1 != nil && b1.heap == heap && b1.heapOffset == 0 && b1.gpuAddress == made.gpu_address);
CHECK(heap.usedSize == 100 && [heap maxAvailableSizeWithAlignment:256] == 1015552);
id<MTLBuffer> b2 = [heap newBufferWithLength:100 options:o];
placed(256, 100);
id<MTLBuffer> b3 = [heap newBufferWithLength:70000 options:o];
placed(512, 70000);
CHECK(b3.gpuAddress == made.gpu_address + 512 && b3.heapOffset == 0);
CHECK(heap.usedSize == 70200 && [heap maxAvailableSizeWithAlignment:1] == 945296);
CHECK([heap maxAvailableSizeWithAlignment:4096] == 942080);
CHECK([heap maxAvailableSizeWithAlignment:65536] == 884736);
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:256
height:256
mipmapped:NO];
td.storageMode = MTLStorageModePrivate;
id<MTLTexture> t1 = [heap newTextureWithDescriptor:td];
auto tex = expectMessage<RgfxTextureCreate>(fx.ring, RGFX_CMD_TEXTURE_CREATE);
CHECK(t1 != nil && t1.heap == heap && t1.heapOffset == 0 && t1.allocatedSize == 264192);
CHECK(tex.heap_obj_id == heap.rgfxObjId && tex.heap_offset == 70528);
CHECK(heap.usedSize == 334392 && [heap maxAvailableSizeWithAlignment:256] == 680960);
CHECK(!RgfxUnsupportedWasLogged([RgfxHeap class], @selector(newTextureWithDescriptor:)));
b1 = nil; // no command buffer in flight: its bytes go back at once
CHECK(expectMessage<RgfxObjectDestroy>(fx.ring, RGFX_CMD_OBJECT_DESTROY).obj_id != 0);
CHECK(heap.usedSize == 334292);
id<MTLBuffer> b4 = [heap newBufferWithLength:50 options:o];
placed(0, 50);
CHECK(!b2.isAliasable);
[b2 makeAliasable];
CHECK(b2.isAliasable && heap.usedSize == 334242);
[b2 makeAliasable];
CHECK(heap.usedSize == 334242);
id<MTLBuffer> b5 = [heap newBufferWithLength:60 options:o];
placed(256, 60);
b2 = nil; // made aliasable, so its bytes went back already
drainRing(fx.ring);
CHECK(heap.usedSize == 334302);
const NSUInteger most = [heap maxAvailableSizeWithAlignment:256];
CHECK(most == 680960);
CHECK([heap newBufferWithLength:most + 1 options:o] == nil && ringEmpty(fx.ring));
id<MTLBuffer> b7 = [heap newBufferWithLength:most options:o];
placed(334848, most);
CHECK(heap.usedSize == 1015262 && [heap maxAvailableSizeWithAlignment:1] == 206);
CHECK([heap newBufferWithLength:16 options:o] == nil);
CHECK([heap newTextureWithDescriptor:td] == nil);
CHECK([heap newBufferWithLength:0 options:o] == nil && ringEmpty(fx.ring));
CHECK([heap maxAvailableSizeWithAlignment:3] == 0);
(void)b3, (void)b4, (void)b5, (void)b7, (void)t1;
}
drainRing(fx.ring);
// With no answer from the device, a texture takes the bound of Metal's size, logged.
@autoreleasepool {
Fixture bare;
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:d device:nil serializer:&bare.ser];
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:256
height:256
mipmapped:NO];
RgfxHeapSizeAlign bound = {};
CHECK(rgfxHeapTextureBound(MTLPixelFormatRGBA8Unorm, MTLTextureType2D, 256, 256, 1, 1, 1,
1, &bound));
id<MTLTexture> t = [heap newTextureWithDescriptor:td];
CHECK(t != nil && t.allocatedSize == bound.size && heap.usedSize == bound.size);
CHECK(RgfxUnsupportedWasLogged([RgfxHeap class], @selector(newTextureWithDescriptor:)));
drainRing(bare.ring);
}
// A Placement heap places nothing itself, and answers 0 used and 0 available.
@autoreleasepool {
Fixture px;
MTLHeapDescriptor *pd = [MTLHeapDescriptor new];
pd.size = 20000;
pd.type = MTLHeapTypePlacement;
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:pd device:nil serializer:&px.ser];
CHECK(heap.size == 32768 && heap.currentAllocatedSize == 32768);
id<MTLBuffer> b = [heap newBufferWithLength:4096 options:0 offset:0];
CHECK(b != nil && heap.usedSize == 0 && [heap maxAvailableSizeWithAlignment:256] == 0);
CHECK([heap newBufferWithLength:64 options:0] == nil);
drainRing(px.ring);
}
}
// An Automatic Shared heap's buffers are its bytes at the offsets it picks.
void test_automatic_shared_heap_buffers_are_its_bytes()
{
Fixture fx;
static uint8_t bytes[0x8000];
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = sizeof(bytes);
d.storageMode = MTLStorageModeShared;
d.type = MTLHeapTypeAutomatic;
@autoreleasepool {
RgfxHeap *heap = [RgfxHeap heapOverHostMemoryWithDescriptor:d
regionOffset:RGFX_CONTEXT_ALLOCATIONS_OFFSET
contents:bytes
deallocator:nil
device:nil
serializer:&fx.ser];
const uint64_t at =
expectMessage<RgfxHeapOverHostMemory>(fx.ring, RGFX_CMD_HEAP_OVER_HOST_MEMORY)
.gpu_address;
id<MTLBuffer> a = [heap newBufferWithLength:300 options:MTLResourceStorageModeShared];
id<MTLBuffer> b = [heap newBufferWithLength:300 options:MTLResourceStorageModeShared];
CHECK(a != nil && b != nil);
CHECK([a contents] == bytes && [b contents] == bytes + 512);
CHECK(a.gpuAddress == at && b.gpuAddress == at + 512);
CHECK([heap newBufferWithLength:sizeof(bytes) options:MTLResourceStorageModeShared] ==
nil);
drainRing(fx.ring);
}
drainRing(fx.ring);
}
// A heap's GPU address goes back once its destroy is retired: churned 1 GiB heaps, each made
// while the one before it lives, take spans that never meet a live one and are picked again
// once the picks have gone round the context's 64 GiB, so the churn never runs out. One a
// command buffer in flight holds back keeps its span till the buffer completes.
void test_addresses_reused_after_destroy()
{
Fixture fx;
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = uint64_t{1} << 30;
d.type = MTLHeapTypePlacement;
const uint64_t span = RgfxIdSpace::addressSpan(d.size);
auto heapAddress = [&] {
return expectMessage<RgfxHeapCreate>(fx.ring, RGFX_CMD_HEAP_CREATE).gpu_address;
};
std::set<uint64_t> seen;
RgfxHeap *held = nil;
uint64_t heldAt = 0;
bool reused = false;
for (int i = 0; i < 200; i++) {
@autoreleasepool {
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser];
uint64_t at = heapAddress();
CHECK(heap != nil && at != 0 && at % RgfxIdSpace::kAddressGranule == 0);
CHECK(at + span <= heldAt || heldAt + span <= at); // apart from the live one's span
reused |= !seen.insert(at).second;
held = heap; // the one before goes
heldAt = at;
drainRing(fx.ring);
}
}
CHECK(reused && seen.size() < 200 && held != nil);
@autoreleasepool {
held = nil;
}
drainRing(fx.ring);
// A heap a command buffer in flight keeps (its retained references), though the app let it
// go, keeps its span till the buffer lets it go: with every other span taken, only its own is
// picked once it has.
uint64_t keptAt = 0;
NSMutableArray *inFlight = [NSMutableArray array]; // what the command buffer keeps
@autoreleasepool {
RgfxHeap *kept = [RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser];
keptAt = heapAddress();
CHECK(kept != nil);
[inFlight addObject:kept];
kept = nil;
}
CHECK(ringEmpty(fx.ring)); // its destroy waits
int taken = 0;
for (uint64_t at; (at = fx.ids.allocAddress(d.size, 1)) != 0; taken++)
CHECK(at != keptAt);
CHECK(taken > 0);
@autoreleasepool {
[inFlight removeAllObjects];
}
CHECK(nextDestroyed(fx.ring) != 0 && ringEmpty(fx.ring));
CHECK(fx.ids.allocAddress(d.size, 1) == keptAt);
}
// Each host object the bundle makes is destroyed as the app lets it go, at once with no
// command buffer in flight: samplers, depth-stencil states, events, fences, shared events,
// buffers, heaps, libraries, and render and compute pipelines.
void test_objects_destroyed_as_let_go()
{
Fixture fx;
auto made = [&](id object) {
CHECK(object != nil);
uint64_t objId = ((RgfxResource *)object).rgfxObjId;
CHECK(objId != 0);
drainRing(fx.ring);
return objId;
};
uint64_t objId = 0;
@autoreleasepool {
objId = made([RgfxSampler samplerWithDescriptor:[MTLSamplerDescriptor new]
device:nil
serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
objId = made([RgfxDepthStencilState
depthStencilStateWithDescriptor:[MTLDepthStencilDescriptor new]
device:nil
serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
objId = made([RgfxEvent eventWithDevice:nil serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
objId = made([RgfxFence fenceWithDevice:nil serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
objId = made([RgfxSharedEvent sharedEventWithInitialValue:3 device:nil serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
objId = made([RgfxBuffer bufferWithLength:256 options:0 device:nil serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = 0x10000;
objId = made([RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
const uint8_t libBytes[] = {1, 2, 3, 4};
uint32_t status = 0;
uint64_t libId = 0;
@autoreleasepool {
libId = made([RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&status]);
}
CHECK(nextDestroyed(fx.ring) == libId && ringEmpty(fx.ring));
RgfxLibrary *lib = nil;
@autoreleasepool {
lib = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
drainRing(fx.ring);
}
@autoreleasepool {
MTLRenderPipelineDescriptor *desc = [MTLRenderPipelineDescriptor new];
desc.vertexFunction = [lib newFunctionWithName:@"vmain"];
desc.colorAttachments[0].pixelFormat = MTLPixelFormatBGRA8Unorm;
NSError *err = nil;
objId = made([RgfxRenderPipelineState renderPipelineStateWithDescriptor:desc
device:nil
serializer:&fx.ser
error:&err]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
@autoreleasepool {
NSError *err = nil;
objId = made([RgfxComputePipelineState
computePipelineStateWithFunction:[lib newFunctionWithName:@"kmain"]
device:nil
serializer:&fx.ser
error:&err]);
}
CHECK(nextDestroyed(fx.ring) == objId && ringEmpty(fx.ring));
libId = lib.rgfxObjId;
@autoreleasepool {
lib = nil;
}
CHECK(nextDestroyed(fx.ring) == libId && ringEmpty(fx.ring)); // with its last function
}
// A function keeps its library on the host, so a pipeline made from it after the app let the
// library go still names a library the host holds; the pipeline needs the library no more.
void test_function_keeps_its_library()
{
Fixture fx;
const uint8_t libBytes[] = {5, 6, 7};
uint32_t status = 0;
uint64_t libId = 0;
id<MTLFunction> fn = nil;
@autoreleasepool {
RgfxLibrary *lib = [RgfxLibrary libraryWithData:libBytes
length:sizeof(libBytes)
key:nullptr
device:nil
serializer:&fx.ser
status:&status];
libId = lib.rgfxObjId;
fn = [lib newFunctionWithName:@"kmain"];
drainRing(fx.ring);
}
CHECK(ringEmpty(fx.ring)); // the function keeps it
RgfxComputePipelineState *ps = nil;
@autoreleasepool {
NSError *err = nil;
ps = [RgfxComputePipelineState computePipelineStateWithFunction:fn
device:nil
serializer:&fx.ser
error:&err];
CHECK(ps != nil);
auto bytes = nextMessage(fx.ring, RGFX_CMD_COMPUTE_PIPELINE_CREATE);
RgfxComputePipelineCreate create;
std::memcpy(&create, bytes.data(), sizeof(create));
CHECK(create.function_library_obj_id == libId);
}
@autoreleasepool {
fn = nil;
}
CHECK(nextDestroyed(fx.ring) == libId && ringEmpty(fx.ring)); // with its last function
uint64_t pipeId = ps.rgfxObjId;
@autoreleasepool {
ps = nil;
}
CHECK(nextDestroyed(fx.ring) == pipeId && ringEmpty(fx.ring));
}
// A buffer or texture placed in a heap keeps the heap (its `heap`): the heap goes from the
// host only after the last of them.
void test_heap_outlives_its_resources()
{
Fixture fx;
int calls = 0;
fx.ids.setResourceIdSource(&oneChunk, &calls);
RgfxHeap *heap = nil;
id<MTLBuffer> buf = nil;
id<MTLTexture> tex = nil;
@autoreleasepool {
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = 0x100000;
d.type = MTLHeapTypePlacement; // only a Placement heap places at an offset
heap = [RgfxHeap heapWithDescriptor:d device:nil serializer:&fx.ser];
buf = [heap newBufferWithLength:256 options:0 offset:0];
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:8
height:8
mipmapped:NO];
tex = [heap newTextureWithDescriptor:td offset:0x10000];
CHECK(buf != nil && tex != nil);
drainRing(fx.ring);
}
uint64_t heapId = heap.rgfxObjId;
uint64_t bufId = ((RgfxResource *)buf).rgfxObjId;
uint64_t texId = ((RgfxResource *)tex).rgfxObjId;
@autoreleasepool {
CHECK(buf.heap == heap && tex.heap == heap);
heap = nil;
}
CHECK(ringEmpty(fx.ring)); // its resources keep it
@autoreleasepool {
buf = nil;
}
CHECK(nextDestroyed(fx.ring) == bufId && ringEmpty(fx.ring));
@autoreleasepool {
tex = nil;
}
CHECK(nextDestroyed(fx.ring) == texId);
CHECK(nextDestroyed(fx.ring) == heapId && ringEmpty(fx.ring));
}
// A texture's views (RGFX_CMD_TEXTURE_VIEW): each form posts its view of the texture with the
// fields it names, and the view answers its own shape and its texture's memory, as Metal's do
// (measured on the M3 Max under macOS 27.0.1). A view Metal makes none of, or asserts at,
// answers nil and posts nothing.
void test_texture_views()
{
Fixture fx;
@autoreleasepool {
// A Private 2D array of four slices and seven levels, of usage 0x17.
MTLTextureDescriptor *desc =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
width:64
height:32
mipmapped:YES];
desc.textureType = MTLTextureType2DArray;
desc.arrayLength = 4;
desc.usage = MTLTextureUsageShaderRead | MTLTextureUsageShaderWrite |
MTLTextureUsageRenderTarget | MTLTextureUsagePixelFormatView;
desc.storageMode = MTLStorageModePrivate;
RgfxTexture *tex = [RgfxTexture textureWithDescriptor:desc
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
CHECK(tex != nil && tex.mipmapLevelCount == 7);
drainRing(fx.ring);
// In a format alone: the whole texture in its type.
id<MTLTexture> srgb = [tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm_sRGB];
CHECK(srgb != nil && srgb.parentTexture == tex);
CHECK(srgb.pixelFormat == MTLPixelFormatRGBA8Unorm_sRGB);
CHECK(srgb.textureType == MTLTextureType2DArray && srgb.width == 64 && srgb.height == 32);
CHECK(srgb.mipmapLevelCount == 7 && srgb.arrayLength == 4 && srgb.usage == 0x17);
CHECK(srgb.parentRelativeLevel == 0 && srgb.parentRelativeSlice == 0);
CHECK(srgb.storageMode == MTLStorageModePrivate);
CHECK(srgb.gpuResourceID._impl != 0 && srgb.gpuResourceID._impl != tex.gpuResourceID._impl);
auto m = expectMessage<RgfxTextureView>(fx.ring, RGFX_CMD_TEXTURE_VIEW);
CHECK(m.obj_id == ((RgfxResource *)srgb).rgfxObjId && m.parent_obj_id == tex.rgfxObjId);
CHECK(m.resource_id == srgb.gpuResourceID._impl && m.pixel_format == 71 && m.flags == 0);
CHECK(m.texture_type == 0 && m.level_count == 0 && m.slice_count == 0 && m.swizzle == 0);
// Of a type, levels and slices: the texture's size at the view's first level.
id<MTLTexture> face = [tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(1, 2)
slices:NSMakeRange(2, 1)];
CHECK(face != nil && face.textureType == MTLTextureType2D);
CHECK(face.width == 32 && face.height == 16 && face.mipmapLevelCount == 2);
CHECK(face.arrayLength == 1 && face.parentRelativeLevel == 1 && face.parentRelativeSlice == 2);
m = expectMessage<RgfxTextureView>(fx.ring, RGFX_CMD_TEXTURE_VIEW);
CHECK(m.flags == RGFX_TEXTURE_VIEW_SUBRANGE && m.texture_type == MTLTextureType2D);
CHECK(m.level_start == 1 && m.level_count == 2 && m.slice_start == 2 && m.slice_count == 1);
CHECK(m.swizzle == 0);
// Of a swizzle other than the default: it keeps only ShaderRead and PixelFormatView of the
// usage; of the default swizzle, all of it.
MTLTextureSwizzleChannels rrr1 = MTLTextureSwizzleChannelsMake(
MTLTextureSwizzleRed, MTLTextureSwizzleRed, MTLTextureSwizzleRed, MTLTextureSwizzleOne);
id<MTLTexture> red = [tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2DArray
levels:NSMakeRange(0, 7)
slices:NSMakeRange(1, 3)
swizzle:rrr1];
CHECK(red != nil && red.usage == 0x11 && red.arrayLength == 3);
CHECK(red.swizzle.red == MTLTextureSwizzleRed && red.swizzle.alpha == MTLTextureSwizzleOne);
m = expectMessage<RgfxTextureView>(fx.ring, RGFX_CMD_TEXTURE_VIEW);
CHECK(m.flags == (RGFX_TEXTURE_VIEW_SUBRANGE | RGFX_TEXTURE_VIEW_SWIZZLE));
CHECK(m.swizzle == 0x01020202 && m.slice_start == 1 && m.slice_count == 3);
id<MTLTexture> plain = [tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(0, 1)
slices:NSMakeRange(0, 1)
swizzle:MTLTextureSwizzleChannelsDefault];
CHECK(plain != nil && plain.usage == 0x17);
m = expectMessage<RgfxTextureView>(fx.ring, RGFX_CMD_TEXTURE_VIEW);
CHECK(m.swizzle == 0x05040302);
// By a descriptor: made as the longest form.
MTLTextureViewDescriptor *vd = [MTLTextureViewDescriptor new];
vd.pixelFormat = MTLPixelFormatRGBA8Unorm;
vd.textureType = MTLTextureType2D;
vd.levelRange = NSMakeRange(3, 1);
vd.sliceRange = NSMakeRange(3, 1);
id<MTLTexture> byDesc = [tex newTextureViewWithDescriptor:vd];
CHECK(byDesc != nil && byDesc.width == 8 && byDesc.parentRelativeSlice == 3);
m = expectMessage<RgfxTextureView>(fx.ring, RGFX_CMD_TEXTURE_VIEW);
CHECK(m.flags == (RGFX_TEXTURE_VIEW_SUBRANGE | RGFX_TEXTURE_VIEW_SWIZZLE));
CHECK(m.level_start == 3 && m.slice_start == 3 && m.swizzle == 0x05040302);
CHECK(byDesc.minLOD == 0.0f);
if ([vd respondsToSelector:@selector(minLOD)]) {
vd.minLOD = 1.5f; // a lowest level of detail the device carries not
CHECK([tex newTextureViewWithDescriptor:vd] == nil && ringEmpty(fx.ring));
}
// A view of a view: of it, at levels and slices relative to it.
id<MTLTexture> inner = [red newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(1, 1)
slices:NSMakeRange(1, 1)];
CHECK(inner.parentTexture == red && inner.parentRelativeLevel == 1);
CHECK(inner.parentRelativeSlice == 1 && inner.width == 32);
// It keeps the swizzle of the view it is made of, as it names none.
CHECK(inner.swizzle.alpha == MTLTextureSwizzleOne);
m = expectMessage<RgfxTextureView>(fx.ring, RGFX_CMD_TEXTURE_VIEW);
CHECK(m.parent_obj_id == ((RgfxResource *)red).rgfxObjId);
// Views Metal makes none of, or asserts at: nil, and nothing posted.
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatInvalid] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRG8Unorm] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatBC1_RGBA] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(6, 3)
slices:NSMakeRange(0, 1)] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(0, 0)
slices:NSMakeRange(0, 1)] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2DArray
levels:NSMakeRange(0, 1)
slices:NSMakeRange(3, 2)] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(0, 1)
slices:NSMakeRange(0, 2)] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType3D
levels:NSMakeRange(0, 1)
slices:NSMakeRange(0, 1)] == nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureTypeCube
levels:NSMakeRange(0, 1)
slices:NSMakeRange(0, 5)] == nil);
CHECK(ringEmpty(fx.ring));
// A format the bundle cannot size is the host's to refuse: posted.
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatR32Float] != nil);
CHECK([tex newTextureViewWithPixelFormat:MTLPixelFormatDepth32Float] != nil);
drainRing(fx.ring);
// Cube and 3D views.
MTLTextureDescriptor *cd =
[MTLTextureDescriptor textureCubeDescriptorWithPixelFormat:MTLPixelFormatRGBA8Unorm
size:16
mipmapped:YES];
RgfxTexture *cube = [RgfxTexture textureWithDescriptor:cd
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
id<MTLTexture> faces = [cube newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2DArray
levels:NSMakeRange(0, 2)
slices:NSMakeRange(0, 6)];
CHECK(faces != nil && faces.arrayLength == 6 && faces.mipmapLevelCount == 2);
id<MTLTexture> face3 = [cube newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(1, 1)
slices:NSMakeRange(3, 1)];
CHECK(face3 != nil && face3.width == 8 && face3.parentRelativeSlice == 3);
MTLTextureDescriptor *dd = [MTLTextureDescriptor new];
dd.textureType = MTLTextureType3D;
dd.pixelFormat = MTLPixelFormatRGBA8Unorm;
dd.width = 16;
dd.height = 8;
dd.depth = 4;
dd.mipmapLevelCount = 3;
RgfxTexture *vol = [RgfxTexture textureWithDescriptor:dd
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
id<MTLTexture> level1 = [vol newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType3D
levels:NSMakeRange(1, 2)
slices:NSMakeRange(0, 1)];
CHECK(level1 != nil && level1.width == 8 && level1.height == 4 && level1.depth == 2);
CHECK([vol newTextureViewWithPixelFormat:MTLPixelFormatRGBA8Unorm
textureType:MTLTextureType2D
levels:NSMakeRange(0, 1)
slices:NSMakeRange(0, 1)] == nil);
drainRing(fx.ring);
// A view of a texture over a buffer: the buffer's, and its CPU copies are the texture's.
std::vector<uint8_t> memory(16 + 32 * 3, 0xee);
RgfxBuffer *buf = [RgfxBuffer bufferOverHostMemoryWithContents:memory.data()
regionOffset:0x10000
length:memory.size()
options:MTLResourceStorageModeShared
deallocator:nil
device:nil
serializer:&fx.ser];
MTLTextureDescriptor *bd =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:4
height:3
mipmapped:NO];
bd.storageMode = MTLStorageModeShared;
RgfxTexture *over = [RgfxTexture textureWithDescriptor:bd
buffer:buf
offset:16
bytesPerRow:32
device:nil
serializer:&fx.ser];
id<MTLTexture> asWords = [over newTextureViewWithPixelFormat:MTLPixelFormatR32Uint];
CHECK(asWords.buffer == buf && asWords.bufferOffset == 16 && asWords.bufferBytesPerRow == 32);
CHECK(asWords.allocatedSize == over.allocatedSize);
CHECK(over.allocatedSize == buf.allocatedSize); // the buffer's, as Metal answers
const uint32_t words[2] = {0x11223344, 0x55667788};
[asWords replaceRegion:MTLRegionMake2D(1, 2, 2, 1) mipmapLevel:0 withBytes:words bytesPerRow:8];
CHECK(std::memcmp(&memory[16 + 32 * 2 + 4], words, 8) == 0);
uint32_t back[2] = {};
[asWords getBytes:back bytesPerRow:8 fromRegion:MTLRegionMake2D(1, 2, 2, 1) mipmapLevel:0];
CHECK(back[0] == words[0] && back[1] == words[1]);
// A level the view lacks: nothing copied.
[asWords replaceRegion:MTLRegionMake2D(0, 0, 1, 1) mipmapLevel:1 withBytes:words bytesPerRow:4];
CHECK(memory[16] == 0xee);
drainRing(fx.ring);
// A view of a heap texture: the heap's, at the texture's offset, aliased as the texture
// is; making the view aliasable changes nothing, and its purgeable state stays NonVolatile.
MTLHeapDescriptor *hd = [MTLHeapDescriptor new];
hd.size = 0x100000;
hd.type = MTLHeapTypePlacement;
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:hd device:nil serializer:&fx.ser];
id<MTLTexture> placed = [heap newTextureWithDescriptor:bd offset:0x10000];
id<MTLTexture> placedView = [placed newTextureViewWithPixelFormat:MTLPixelFormatBGRA8Unorm_sRGB];
CHECK(placedView.heap == heap && placedView.heapOffset == 0x10000);
CHECK(placed.isAliasable && placedView.isAliasable); // a Placement heap's
CHECK([placedView setPurgeableState:MTLPurgeableStateVolatile] == MTLPurgeableStateNonVolatile);
CHECK([placed setPurgeableState:MTLPurgeableStateKeepCurrent] == MTLPurgeableStateNonVolatile);
drainRing(fx.ring);
}
}
// A view keeps its texture: the texture's destroy is posted only after the view's.
void test_view_keeps_its_texture()
{
Fixture fx;
RgfxTexture *tex = nil;
id<MTLTexture> view = nil;
@autoreleasepool {
MTLTextureDescriptor *d =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:8
height:8
mipmapped:NO];
tex = [RgfxTexture textureWithDescriptor:d
heap:RGFX_OBJ_NONE
heapOffset:0
device:nil
serializer:&fx.ser];
view = [tex newTextureViewWithPixelFormat:MTLPixelFormatBGRA8Unorm_sRGB];
CHECK(view != nil);
drainRing(fx.ring);
}
uint64_t texId = tex.rgfxObjId;
uint64_t viewId = ((RgfxResource *)view).rgfxObjId;
@autoreleasepool {
tex = nil;
}
CHECK(ringEmpty(fx.ring)); // the view keeps it
@autoreleasepool {
view = nil;
}
CHECK(nextDestroyed(fx.ring) == viewId);
CHECK(nextDestroyed(fx.ring) == texId && ringEmpty(fx.ring));
}
// The region memory under a buffer or heap over host memory goes back only once the host has
// dropped the object, after any command buffer in flight that keeps it has let it go.
void test_region_memory_given_back_after_destroy()
{
Fixture fx;
TestRing *ring = &fx.ring;
__block int released = 0;
__block bool destroyedFirst = false;
void (^deallocator)(void) = ^{
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
destroyedFirst = ring->next(&h, &bytes) && h.type == RGFX_CMD_OBJECT_DESTROY;
released++;
};
static uint8_t page[0x1000];
NSMutableArray *inFlight = [NSMutableArray array]; // what a command buffer in flight keeps
@autoreleasepool {
RgfxBuffer *b = [RgfxBuffer bufferOverHostMemoryWithContents:page
regionOffset:RGFX_CONTEXT_ALLOCATIONS_OFFSET
length:sizeof(page)
options:MTLResourceStorageModeShared
deallocator:deallocator
device:nil
serializer:&fx.ser];
CHECK(b != nil);
MTLHeapDescriptor *d = [MTLHeapDescriptor new];
d.size = 0x10000;
d.storageMode = MTLStorageModeShared;
RgfxHeap *h = [RgfxHeap heapOverHostMemoryWithDescriptor:d
regionOffset:RGFX_CONTEXT_ALLOCATIONS_OFFSET + 0x1000
contents:nullptr
deallocator:deallocator
device:nil
serializer:&fx.ser];
CHECK(h != nil);
[inFlight addObject:b];
[inFlight addObject:h];
drainRing(fx.ring);
}
CHECK(released == 0 && ringEmpty(fx.ring)); // the buffer in flight keeps them
@autoreleasepool {
[inFlight removeAllObjects];
}
CHECK(released == 2 && destroyedFirst);
CHECK(ringEmpty(fx.ring));
}
// An IOSurface texture's copy goes as the texture goes: the texture, then the copy's buffer,
// from the host, and only then the copy's block back to the region.
void test_iosurface_copy_block_after_destroys()
{
Fixture fx;
int calls = 0;
fx.ids.setResourceIdSource(&oneChunk, &calls);
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x100000, 0);
RgfxRegion region(mem.data(), mem.size());
struct Log {
BlockLog blocks;
TestRing *ring;
std::vector<uint64_t> seenAtRelease; // the objects destroyed on the ring by each release
static bool alloc(void *c, uint64_t size, uint64_t align, uint64_t *offset)
{
return BlockLog::alloc(&static_cast<Log *>(c)->blocks, size, align, offset);
}
static void release(void *c, uint64_t offset)
{
Log *log = static_cast<Log *>(c);
BlockLog::release(&log->blocks, offset);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
while (log->ring->next(&h, &bytes)) {
RgfxObjectDestroy d = {};
if (h.type == RGFX_CMD_OBJECT_DESTROY && bytes.size() >= sizeof(d)) {
std::memcpy(&d, bytes.data(), sizeof(d));
log->seenAtRelease.push_back(d.obj_id);
}
}
}
} log;
log.ring = &fx.ring;
region.setBlockSource(&Log::alloc, &Log::release, &log);
NSDictionary *props = @{
(id)kIOSurfaceWidth : @16,
(id)kIOSurfaceHeight : @16,
(id)kIOSurfaceBytesPerElement : @4,
(id)kIOSurfacePixelFormat : @(static_cast<uint32_t>('BGRA')),
};
IOSurfaceRef surface = IOSurfaceCreate((__bridge CFDictionaryRef)props);
CHECK(surface != nullptr);
uint64_t texId = 0, bufId = 0;
@autoreleasepool {
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:16
height:16
mipmapped:NO];
RgfxIOSurfaceTexture *t = [RgfxIOSurfaceTexture textureWithDescriptor:td
iosurface:surface
plane:0
region:&region
device:nil
serializer:&fx.ser];
CHECK(t != nil);
texId = t.rgfxObjId;
bufId = expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY)
.obj_id;
drainRing(fx.ring);
CHECK(log.blocks.allocated.size() == 1);
}
CHECK(log.blocks.released == log.blocks.allocated);
CHECK(log.seenAtRelease == std::vector<uint64_t>({texId, bufId}));
CHECK(ringEmpty(fx.ring));
CFRelease(surface);
}
// A surface plane's GPU view is the plane's shared block where the kext gives one: synced from
// the pages only where no holder has synced it since their last CPU write (its header names the
// block and the seed), let go through the surface source as the texture goes; and the process's
// own block where the kext gives none.
void test_iosurface_shared_block()
{
Fixture fx;
int calls = 0;
fx.ids.setResourceIdSource(&oneChunk, &calls);
std::vector<uint8_t> mem(RGFX_ALLOCATIONS_OFFSET + 0x100000, 0);
RgfxRegion region(mem.data(), mem.size());
BlockLog blocks;
region.setBlockSource(&BlockLog::alloc, &BlockLog::release, &blocks);
struct Source {
uint64_t offset = RGFX_ALLOCATIONS_OFFSET + 0x40000;
uint64_t serial = 0;
bool fresh = true;
bool give = true;
const void *plane = nullptr;
uint64_t length = 0, size = 0;
int acquired = 0;
std::vector<uint64_t> released;
static bool acquire(void *c, const void *plane, uint64_t length, uint64_t size,
uint64_t *offset, uint64_t *serial, bool *fresh)
{
Source *src = static_cast<Source *>(c);
src->plane = plane;
src->length = length;
src->size = size;
src->acquired++;
*offset = src->offset;
*serial = src->serial;
*fresh = src->fresh;
return src->give;
}
static void release(void *c, uint64_t offset)
{
static_cast<Source *>(c)->released.push_back(offset);
}
} src;
region.setSurfaceSource(&Source::acquire, &Source::release, &src);
// 16 x 16 BGRA: rows 256 bytes apart in the block, its header at 4096, the block 8192 bytes.
const uint64_t kPitch = 256, kHeader = 4096;
auto fill = [](IOSurfaceRef s, uint32_t v) {
IOSurfaceLock(s, 0, nullptr);
auto *base = static_cast<uint8_t *>(IOSurfaceGetBaseAddress(s));
for (int y = 0; y < 16; y++)
for (int x = 0; x < 16; x++)
reinterpret_cast<uint32_t *>(base + y * IOSurfaceGetBytesPerRow(s))[x] = v;
IOSurfaceUnlock(s, 0, nullptr);
};
auto made = [&](uint32_t v) {
NSDictionary *props = @{
(id)kIOSurfaceWidth : @16,
(id)kIOSurfaceHeight : @16,
(id)kIOSurfaceBytesPerElement : @4,
(id)kIOSurfacePixelFormat : @(static_cast<uint32_t>('BGRA')),
};
IOSurfaceRef s = IOSurfaceCreate((__bridge CFDictionaryRef)props);
fill(s, v);
return s;
};
uint8_t *block = mem.data() + src.offset;
auto blockIs = [&](uint32_t v) {
for (int y = 0; y < 16; y++)
for (int x = 0; x < 16; x++)
if (reinterpret_cast<uint32_t *>(block + y * kPitch)[x] != v)
return false;
return true;
};
auto header = [&]() { return reinterpret_cast<uint64_t *>(block + kHeader); };
auto headerSeed = [&]() { return *reinterpret_cast<uint32_t *>(block + kHeader + 8); };
auto texture = [&](IOSurfaceRef s) {
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:16
height:16
mipmapped:NO];
return [RgfxIOSurfaceTexture textureWithDescriptor:td
iosurface:s
plane:0
region:&region
device:nil
serializer:&fx.ser];
};
// The first holder: a fresh block, synced from the pages, its header its own.
src.serial = 41;
IOSurfaceRef first = made(0x11223344);
@autoreleasepool {
RgfxIOSurfaceTexture *t = texture(first);
CHECK(t != nil && src.acquired == 1 && blocks.allocated.empty());
CHECK(src.plane == IOSurfaceGetBaseAddress(first) &&
src.length == IOSurfaceGetBytesPerRow(first) * 16 && src.size == 8192);
auto create =
expectMessage<RgfxBufferOverHostMemory>(fx.ring, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
CHECK(create.region_offset == src.offset && create.length == 8192);
CHECK(blockIs(0x11223344));
CHECK(*header() == 41 && headerSeed() == IOSurfaceGetSeed(first));
drainRing(fx.ring);
}
CHECK(src.released == std::vector<uint64_t>({src.offset}));
// Another process synced it with the pages already: no copy, until a CPU writes them.
src.serial = 42;
src.fresh = false;
src.released.clear();
IOSurfaceRef second = made(0x55555555);
std::memset(block, 0xaa, kHeader);
*header() = 42;
*reinterpret_cast<uint32_t *>(block + kHeader + 8) = IOSurfaceGetSeed(second);
@autoreleasepool {
RgfxIOSurfaceTexture *t = texture(second);
CHECK(t != nil && blockIs(0xaaaaaaaa));
rgfxIOSurfaceSyncBeforeCommit();
CHECK(blockIs(0xaaaaaaaa));
fill(second, 0x66666666);
rgfxIOSurfaceSyncBeforeCommit();
CHECK(blockIs(0x66666666) && headerSeed() == IOSurfaceGetSeed(second));
drainRing(fx.ring);
}
CHECK(src.released.size() == 1);
// A block made again holds an older block's header: synced from the pages.
src.serial = 43;
IOSurfaceRef third = made(0x77777777);
@autoreleasepool {
RgfxIOSurfaceTexture *t = texture(third);
CHECK(t != nil && blockIs(0x77777777) && *header() == 43);
drainRing(fx.ring);
}
// No shared block: the process's own.
src.give = false;
IOSurfaceRef fourth = made(0x12121212);
@autoreleasepool {
RgfxIOSurfaceTexture *t = texture(fourth);
CHECK(t != nil && blocks.allocated.size() == 1);
drainRing(fx.ring);
}
CHECK(blocks.released == blocks.allocated && src.released.size() == 2);
drainRing(fx.ring); // the textures' and buffers' destroys
for (IOSurfaceRef s : {first, second, third, fourth})
CFRelease(s);
}
// A surface copy's writers (RgfxIOSurface.h): a block made for this process starts with none
// whatever it held, and its texture names them to the host; each commit of a buffer that draws
// the copy names its queue and seqno there, in the queue's own slot, raised; another queue takes
// an empty slot, never one another process holds, or one of ours whose queue is gone; with none
// left, nothing is named; and the slots of ours go empty as the copy goes.
void test_iosurface_writers()
{
// Never freed, as Fixture's: the queues and their buffers may go after the test.
TestRing &control = *new TestRing(0x8000);
control.setConsumerIdle(1);
RgfxRingWriter &controlWriter = *new RgfxRingWriter(
control.base(), control.dataSize, RGFX_CONTROL_RING_ID, TestRing::doorbell, nullptr);
RgfxIdSpace &ids = *new RgfxIdSpace();
int &calls = *new int(0);
ids.setResourceIdSource(&oneChunk, &calls);
RgfxSerializer &ser = *new RgfxSerializer(controlWriter, ids);
TestRing &submit = *new TestRing(0x8000);
submit.setConsumerIdle(1);
RgfxRingWriter &submitWriter =
*new RgfxRingWriter(submit.base(), submit.dataSize, 1, TestRing::doorbell, nullptr);
std::vector<uint8_t> &mem = *new std::vector<uint8_t>(RGFX_ALLOCATIONS_OFFSET + 0x100000, 0);
RgfxRegion &region = *new RgfxRegion(mem.data(), mem.size());
struct Source {
uint64_t offset = RGFX_ALLOCATIONS_OFFSET + 0x40000;
static bool acquire(void *c, const void *, uint64_t, uint64_t, uint64_t *offset,
uint64_t *serial, bool *fresh)
{
*offset = static_cast<Source *>(c)->offset;
*serial = 7;
*fresh = true;
return true;
}
static void release(void *, uint64_t) {}
} &src = *new Source();
region.setSurfaceSource(&Source::acquire, &Source::release, &src);
auto queueMade = [&]() {
drainRing(control); // a queue let go before has its destroys there
RgfxCommandQueue *q = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:&ser];
CHECK(q != nil);
(void)expectQueueCreate(control);
return q;
};
// 16 x 16 BGRA: rows 256 bytes apart, the header at 4096, the writers after it.
const uint64_t kWriters = 4096 + 16;
auto *writers = reinterpret_cast<RgfxSurfaceWriters *>(mem.data() + src.offset + kWriters);
// The block held an older one's writers.
for (auto &w : writers->writers)
w = {0x5000000000 + 9, 77};
NSDictionary *props = @{
(id)kIOSurfaceWidth : @16,
(id)kIOSurfaceHeight : @16,
(id)kIOSurfaceBytesPerElement : @4,
(id)kIOSurfacePixelFormat : @(static_cast<uint32_t>('BGRA')),
};
IOSurfaceRef surface = IOSurfaceCreate((__bridge CFDictionaryRef)props);
CHECK(surface != nullptr);
// A buffer drawing the texture, committed on `q`: the seqno it was posted at.
auto draw = [&](RgfxCommandQueue *q, id<MTLTexture> t) {
id<MTLCommandBuffer> cb = [q commandBuffer];
MTLRenderPassDescriptor *rp = [MTLRenderPassDescriptor renderPassDescriptor];
rp.colorAttachments[0].texture = t;
rp.colorAttachments[0].loadAction = MTLLoadActionClear;
rp.colorAttachments[0].storeAction = MTLStoreActionStore;
[[cb renderCommandEncoderWithDescriptor:rp] endEncoding];
[cb commit];
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(submit.next(&h, &bytes) && h.type == RGFX_CMD_COMMAND_BUFFER);
return h.seqno;
};
auto slot = [&](int i) {
return std::make_pair(writers->writers[i].queue_obj_id, writers->writers[i].seqno);
};
using Slot = std::pair<uint64_t, uint64_t>;
const Slot kEmpty = {0, 0}, kOther = {0x6000000000 + 3, 12};
RgfxCommandQueue *first = queueMade();
@autoreleasepool {
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:16
height:16
mipmapped:NO];
td.usage = MTLTextureUsageRenderTarget;
RgfxIOSurfaceTexture *t = [RgfxIOSurfaceTexture textureWithDescriptor:td
iosurface:surface
plane:0
region:&region
device:nil
serializer:&ser];
CHECK(t != nil);
(void)expectMessage<RgfxBufferOverHostMemory>(control, RGFX_CMD_BUFFER_OVER_HOST_MEMORY);
auto made = expectMessage<RgfxTextureFromIOSurface>(control,
RGFX_CMD_TEXTURE_FROM_IOSURFACE);
CHECK(made.writers_offset == kWriters && made.iosurface_id == IOSurfaceGetID(surface));
for (int i = 0; i < RGFX_SURFACE_WRITER_SLOTS; i++)
CHECK(slot(i) == kEmpty);
// The first queue's buffers: its slot, raised.
uint64_t a = draw(first, t);
CHECK(slot(0) == Slot(first.rgfxObjId, a));
uint64_t b = draw(first, t);
CHECK(b > a && slot(0) == Slot(first.rgfxObjId, b));
// Another process holds slot 1: a second queue takes slot 2.
writers->writers[1] = {kOther.first, kOther.second};
@autoreleasepool {
RgfxCommandQueue *second = queueMade();
uint64_t c = draw(second, t);
CHECK(slot(1) == kOther && slot(2) == Slot(second.rgfxObjId, c));
second = nil;
}
// Once the second queue is gone, a third takes its slot again.
RgfxCommandQueue *third = queueMade();
uint64_t d = draw(third, t);
CHECK(slot(2) == Slot(third.rgfxObjId, d) && slot(3) == kEmpty);
// Another process takes the last; a fourth queue finds none, and names nothing.
writers->writers[3] = {kOther.first + 1, kOther.second};
RgfxCommandQueue *fourth = queueMade();
(void)draw(fourth, t);
CHECK(slot(0) == Slot(first.rgfxObjId, b) && slot(1) == kOther &&
slot(2) == Slot(third.rgfxObjId, d) && slot(3) == Slot(kOther.first + 1, 12));
drainRing(control);
}
// The copy goes: our slots empty, the other process's kept.
CHECK(slot(0) == kEmpty && slot(1) == kOther && slot(2) == kEmpty &&
slot(3) == Slot(kOther.first + 1, 12));
drainRing(control);
CFRelease(surface);
}
// A queue's command buffers keep it alive; once they are gone it ends on the device, its
// completion ring read no more, and only then does what it holds go back.
void test_queue_ends_after_its_buffers()
{
@autoreleasepool {
// Made in a pool of its own, so no autorelease keeps the queue past the test's let-go.
QueueFixture *made = nullptr;
@autoreleasepool {
made = new QueueFixture();
}
QueueFixture &f = *made;
(void)expectQueueCreate(f.control);
uint64_t queueId = f.queue.rgfxObjId;
std::shared_ptr<RgfxReplyReader> reader = [f.queue sharedReplyReader];
int released = 0;
bool endedFirst = false;
TestRing *control = &f.control;
[f.queue rgfxSetRelease:[&released, &endedFirst, control] {
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
endedFirst = control->next(&h, &bytes) && h.type == RGFX_CMD_OBJECT_DESTROY;
released++;
}];
id<MTLCommandBuffer> cb = nil;
@autoreleasepool {
cb = [f.queue commandBuffer];
[cb commit];
f.queue = nil;
}
@autoreleasepool {
CHECK(cb.commandQueue != nil); // the buffer keeps it
}
CHECK(ringEmpty(f.control) && released == 0);
RgfxCbComplete done = cbComplete(f.nextSeqno(), ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
CHECK(ringEmpty(f.control) && released == 0);
@autoreleasepool {
cb = nil;
}
CHECK(released == 1 && endedFirst);
CHECK(queueId != 0);
// Its completion ring is read no more.
uint64_t consumer = f.completion.consumerCount();
RgfxCbComplete late = cbComplete(99, 1);
CHECK(f.completion.postFromHost(&late, sizeof(late)));
CHECK(reader->pump() == 0 && !reader->armAndCheck());
CHECK(f.completion.consumerCount() == consumer);
}
}
// Where a closer is set the queue ends through it (the kext's QUEUE_DESTROY) and nothing is
// posted on the ring; without one, an OBJECT_DESTROY ends it.
void test_serializer_destroys_queues()
{
struct Closed {
std::vector<uint64_t> ids;
static void close(void *c, RgfxObjId objId) { static_cast<Closed *>(c)->ids.push_back(objId); }
} closed;
Fixture fx;
fx.ser.destroyQueue(7);
CHECK(nextDestroyed(fx.ring) == 7 && ringEmpty(fx.ring));
fx.ser.setQueueCloser(&Closed::close, &closed);
fx.ser.destroyQueue(8);
CHECK(closed.ids == std::vector<uint64_t>({8}) && ringEmpty(fx.ring));
}
// An object a command buffer encodes stays on the host though the app let it go: until the
// buffer completes, where it is committed, and until it goes, where it never is. One it never
// encodes goes at once, whether made before the buffer or after.
void test_objects_outlive_an_uncommitted_buffer()
{
@autoreleasepool {
QueueFixture f;
drainRing(f.control);
auto sampler = [&](uint64_t *objId) {
RgfxSampler *s = [RgfxSampler samplerWithDescriptor:[MTLSamplerDescriptor new]
device:nil
serializer:&f.ser];
*objId = s.rgfxObjId;
drainRing(f.control);
return s;
};
auto encode = [](id<MTLCommandBuffer> cb, id<MTLSamplerState> s) {
id<MTLComputeCommandEncoder> enc = [cb computeCommandEncoder];
[enc setSamplerState:s atIndex:0];
[enc endEncoding];
};
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
uint64_t samplerId = 0, unnamed = 0;
@autoreleasepool {
encode(cb, sampler(&samplerId));
(void)sampler(&unnamed);
}
CHECK(nextDestroyed(f.control) == unnamed && ringEmpty(f.control));
[cb commit];
CHECK(ringEmpty(f.control));
RgfxCbComplete done = cbComplete(f.nextSeqno(), ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
CHECK(nextDestroyed(f.control) == samplerId && ringEmpty(f.control));
uint64_t other = 0;
@autoreleasepool {
id<MTLCommandBuffer> idle = [f.queue commandBuffer];
@autoreleasepool {
encode(idle, sampler(&other));
}
CHECK(ringEmpty(f.control)); // the buffer that encodes it keeps it
}
CHECK(nextDestroyed(f.control) == other && ringEmpty(f.control));
}
}
// A closed reader takes nothing more off its ring: no handler runs, the consumer stays, and
// the ring is not armed.
void test_reply_reader_close()
{
TestRing ring(0x1000);
RgfxReplyReader reader(ring.base(), ring.dataSize);
int fired = 0;
reader.expectCompletion(7, [&](const RgfxCbComplete &) { fired++; });
reader.close();
RgfxCbComplete done = cbComplete(7, 1);
CHECK(ring.postFromHost(&done, sizeof(done)));
CHECK(reader.pump() == 0 && fired == 0);
CHECK(!reader.armAndCheck());
CHECK(ringArmed(ring) == 0);
CHECK(ring.consumerCount() == 0);
}
void rgfxProtocolTests();
void rgfxArchiveTests();
void rgfxResourceTests();
int main()
{
@autoreleasepool {
test_buffer_routing();
test_private_buffer_has_no_contents();
test_device_buffers_answer_as_metal();
test_second_buffer_is_monotonic();
test_wrapper_guards_and_base();
test_event_routing();
test_fence_routing();
test_shared_event_routing();
test_texture_routing();
test_texture_cpu_copies();
test_tiled_texture_over_backing();
test_texture_views();
test_view_keeps_its_texture();
test_texture_resource_ids();
test_sampler_routing();
test_depth_stencil_routing();
test_heap_routing_and_suballoc();
test_resource_guards();
test_library_and_function_routing();
test_render_pipeline_routing();
test_compute_pipeline_routing();
test_function_constants_resolve_as_metal();
test_linked_function_specialised_on_the_wire();
test_core_image_extern_functions();
test_stitched_library_over_shadows();
test_stitched_dag_over_shadows();
test_stitched_libraries_in_archives();
test_function_members_from_shadow();
test_library_members_as_metal();
test_command_graph();
test_parallel_render_encoder();
test_queue_guards();
test_region_allocator();
test_queue_carries_allocated_offsets();
test_reply_reader_completion();
test_reply_reader_reflection();
test_reply_reader_event();
test_command_buffer_event_ops();
test_reply_reader_arm();
test_completion_thread_runs_handlers();
test_wait_with_the_completion_thread();
test_completion_thread_stops();
test_uncompleted_buffer_releases();
test_command_buffer_out_of_line();
test_completion_expected_before_publish();
test_command_buffer_back_pressure();
test_texture_destroy_waits_for_buffers();
test_managed_layout();
test_managed_buffer_range();
test_managed_texture_cpu_copy();
test_objects_destroyed_as_let_go();
test_function_keeps_its_library();
test_heap_outlives_its_resources();
test_region_memory_given_back_after_destroy();
test_iosurface_copy_block_after_destroys();
test_iosurface_shared_block();
test_iosurface_writers();
test_queue_ends_after_its_buffers();
test_serializer_destroys_queues();
test_objects_outlive_an_uncommitted_buffer();
test_reply_reader_close();
test_addresses_reused_after_destroy();
test_heaps_with_no_bytes_or_address_are_nil();
test_queue_ring_carries_only_command_buffers();
test_shared_heap_buffers_alias_its_bytes();
test_automatic_heap_places_as_metal();
test_automatic_shared_heap_buffers_are_its_bytes();
test_managed_texture_copy_block_after_destroys();
test_no_copy_buffers();
rgfxProtocolTests(); // tests/protocol_tests.mm
rgfxArchiveTests(); // tests/archive_tests.mm
rgfxResourceTests(); // tests/resource_tests.mm
}
std::printf("shell_tests: OK (%d checks)\n", g_checks);
return 0;
}