🐎 Hold heap-placed buffers with the destroys around them

A heap's buffer at an offset (BUFFER_AT_OFFSET, each small buffer of a slab) is
a create no one waits for, and cost its own kext call: 3079 a Vision process,
12 to 15 us each, 40 to 48 ms a process on the RTX 3090 host, between the
destroys, which broke each held run of destroys into one call of about 11.
SubmitBatch now takes BUFFER_AT_OFFSET too, of its one size, checked as Submit
checks it, and a buffer made for a context that closed since its check is
destroyed behind it, as Submit does (RgfxSubmitGate's rgfxSubmitBatchSize;
spans_test checks no message the batch takes names a block). The bundle holds
each buffer with the destroys, in their order, and a command buffer's commit
posts what is held before the buffer goes on its ring, as the host reads a
command buffer after the control ring's messages posted before it.

This changes what the guest sees under transport exhaustion only (the control
ring full for 5 s, or the device stopped):
- before, the buffer's create was refused there and the buffer was nil; now
  it is answered as made, held, as Metal makes objects on a GPU that is gone;
- before, a command buffer committed on a stopped device was never answered,
  and the run hung at its wait; now a commit that finds a buffer still held
  fails the command buffer, unposted, with MTLCommandBufferErrorInternal
  ("Discarded (victim of GPU error/recovery)"), the host's own recovery error,
  as the buffer may name it;
- the next post retries what is held and is refused where it is refused
  again, and a buffer that needs the held gone to make room is refused at
  once, holding nothing more.
Tested by serializer_tests' test_held_buffers and protocol_tests'
test_commit_behind_an_untaken_buffer_fails.


Measured, Vision cold request, RTX 3090 host (rts2, the destroys held,
against rts4, this commit and the next two; load 3.4 and 3.0): destroys and
heap-placed buffers together 62.0 -> 17.6 ms in the first process (3079
buffers and 294 destroy calls become 688 SubmitBatch calls), 51.6 -> 16.1 ms
in the second.
This commit is contained in:
Anees Iqbal committed 2026-11-13 04:02:30 -08:00
1 parent 7e8ea3c46f
commit 628b03fb37
17 files changed
+499 -116

No files matched your search

+34 -21
View File
@@ -1909,20 +1909,25 @@ library the app let go names a library the host still holds. The host makes the
pipeline from the library before the library's destroy, and the pipeline needs
it no more.
**Destroys go together.** Each call into the kext costs the guest its trip
through the kernel, and a post that finds the host's control thread asleep a
doorbell's exit too: 14 us a destroy in a Vision request on the RTX 3090 host
(9 to 10 us without the doorbell), 3415 destroys and 68 to 70 ms a process,
in runs of about 70 an app lets go back to back. So where the kext carries
`SubmitBatch` (selector 5), the bundle holds each destroy
**Destroys and heap-placed buffers go together.** Each call into the kext
costs the guest its trip through the kernel, and a post that finds the host's
control thread asleep a doorbell's exit too: 14 us a destroy in a Vision
request on the RTX 3090 host (9 to 10 us without the doorbell), 3415 destroys
and 68 to 70 ms a process, in runs of about 70 an app lets go back to back,
and 12 to 15 us a `BUFFER_AT_OFFSET`, the buffer a heap places (each small
buffer of a slab), 3079 and 40 to 48 ms a process, between them. So where the
kext carries `SubmitBatch` (selector 5), the bundle holds each of the two
(`RgfxRingWriter::postLater`) and posts what it holds in one call, at most
4096 bytes (170 destroys), before anything else the process posts or asks
of the kext (every `IOConnectCall` of the device's goes through
`rgfxKextConn`, which posts the held first), once the held fill a call, or
1 ms after the first held. The kext checks each as `Submit` checks one, all
before it posts any, puts the runs on the ring under one hold of its lock with
one doorbell at most, and ends a queue's as `Submit` does, after the destroys
before it. What an object lay over goes back as its destroy is held, as it
4096 bytes (170 destroys, 73 buffers), before anything else the process posts
or asks of the kext (every `IOConnectCall` of the device's goes through
`rgfxKextConn`, which posts the held first) and before any command buffer it
commits (the host reads a command buffer after the control ring's messages
posted before it), once the held fill a call, or 1 ms after the first held.
The kext checks each as `Submit` checks one, all before it posts any, puts
the runs on the ring under one hold of its lock with one doorbell at most,
ends a queue's as `Submit` does, after the messages before it, and follows a
buffer made for a context that closed since its check with its destroy, as
`Submit` does. What an object lay over goes back as its destroy is held, as it
went back once its destroy was posted: whatever takes it again, a create over
the bytes or with the id, or a block's free, is posted after the destroy, so
the host has dropped the object first, and every answer the guest reads (a
@@ -1930,13 +1935,21 @@ heap's `usedSize`, a new object's GPU address and resource id) is the one it
read before. A texture over an IOSurface goes at once: a present of the surface
shows the newest live texture the host names it by, and waits for its destroy.
Where the kext stops taking them (its ring stayed full 5 s, or the device
stopped), the rest stay held, first, and the process's next post is refused as
the ring's full ring refuses it; what the held lay over has gone back by then,
which a guest reading a heap's `usedSize` through a 5 s stall of the control
ring sees lower than it did. Tested by `serializer_tests`' `test_held_destroys`
and `shell_tests`' `test_held_destroys_change_nothing_seen` and
`test_surface_texture_destroys_go_at_once`, and the kext's by
`submit_gate_test` and `user_client_words_test`.
stopped), the rest stay held, first: the process's next post retries them,
under its own post's bound, and is refused only where they are refused again,
as the full ring refuses it; a commit that finds a buffer still held fails the
command buffer, unposted, with `MTLCommandBufferErrorInternal`, as a GPU
recovery's victim fails, as the buffer may name it. Two answers differ from
an unbatched post's then, and only then: a buffer held when the kext stopped
taking them was answered as made, where its refused post answered nil (as
Metal makes objects on a GPU that is gone, and fails the work at commit); and
what the held destroys lay over has gone back, which a guest reading a heap's
`usedSize` through a 5 s stall of the control ring sees lower than it did.
Tested by `serializer_tests`' `test_held_destroys` and
`test_held_buffers`, `shell_tests`' `test_held_destroys_change_nothing_seen`,
`test_surface_texture_destroys_go_at_once` and
`test_commit_behind_an_untaken_buffer_fails`, and the kext's by
`submit_gate_test`, `spans_test` and `user_client_words_test`.
**Rings.** A 256-byte header, then a byte ring whose size is a power of two
(64 KiB minus the header for the control rings). Each header field sits in its
@@ -3987,7 +4000,7 @@ Map 1:
| 2 | | | given to none: the IOGPU base's device-info call on its own client type, so a trace names one call per number |
| 3 | `Features` | | the device's feature word, the kext's and the selector map; at 3 in every map |
| 4 | `PagesBlock` | 1 << 0 `PagesBlock` | a block of the runs of a process's own pages, wired, for its no-copy buffers |
| 5 | `SubmitBatch` | 1 << 1 `SubmitBatch` | a process's destroys onto ring 0 in one call ("Destroys go together") |
| 5 | `SubmitBatch` | 1 << 1 `SubmitBatch` | a process's destroys and heap-placed buffers onto ring 0 in one call ("Destroys and heap-placed buffers go together") |
| 6 | `WakeCompletions` | 1 << 2 `WakeCompletions` | reserved: wakes the client's completion waiters |
| 7 | `TakeAnswers` | 1 << 4 `DeferredAnswers` | hands a process its held pipeline-create answers ("Known pipeline creates") |
| 8 | `SurfaceBlockRelease` | | lets go of a shared block |
+20 -7
View File
@@ -2239,8 +2239,13 @@ enum RgfxStage : unsigned {
// host carries out before any later command buffer of the process: the buffer sees every
// encode made before its commit, as on every Mac.
// So do the destroys the kext refused before (RgfxSerializer::destroy), which free what their
// objects lay over once posted.
// objects lay over once posted, and the messages held to go together before them
// (RgfxSerializer::postHeldCreates): the buffer may name an object one of them makes, which
// the host has only where the kext took it, so a buffer behind a create it never took fails
// here, unposted, as Metal's work fails at commit on a GPU that is gone.
bool heldPosted = true;
if (RgfxSerializer *serializer = [queue serializer]) {
heldPosted = serializer->postHeldCreates();
const RgfxIcbFlush flush = serializer->flushIcbWrites();
if (flush.messages != 0)
rgfxNoteIcbFlush(flush);
@@ -2255,7 +2260,8 @@ enum RgfxStage : unsigned {
const bool held = [queue rgfxHeldBuffers] > 0 || ![self rgfxWaitsMet];
if (held)
[queue rgfxNoteHeld];
const bool posted = _encoder->finish(&_seqno, whileWaiting, expect, outOfLine ? &_body : nullptr);
const bool posted =
heldPosted && _encoder->finish(&_seqno, whileWaiting, expect, outOfLine ? &_body : nullptr);
// On its ring: the posts of other queues from here name it (RgfxCommitOrder::posted).
if (posted)
[queue rgfxNotePosted:_seqno];
@@ -2296,10 +2302,16 @@ enum RgfxStage : unsigned {
(_scheduledAsk.fetch_or(kRgfxAskPosted, std::memory_order_acq_rel) & kRgfxAskWanted) != 0)
[self rgfxPostScheduledAsk];
if (!posted) {
// No block for it: the buffer fails as Metal's does when memory runs out, and its
// handlers run off the committing thread.
static char site;
if (rgfxLogFirst(&site))
// No block for it: the buffer fails as Metal's does when memory runs out. Behind a
// create the kext never took (its control ring stayed full, or the device stopped): it
// fails as a GPU recovery's victim does. Either way its handlers run off the committing
// thread.
static char site, heldSite;
if (!heldPosted && rgfxLogFirst(&heldSite))
NSLog(@"RGFX: command buffer 0x%llx: an object made before it never reached the "
@"device: it fails with MTLCommandBufferErrorInternal",
(unsigned long long)[self rgfxObjId]);
else if (heldPosted && rgfxLogFirst(&site))
NSLog(@"RGFX: command buffer 0x%llx: no region block for its %llu bytes: it fails "
@"with MTLCommandBufferErrorOutOfMemory",
(unsigned long long)[self rgfxObjId], (unsigned long long)messageBytes);
@@ -2307,7 +2319,8 @@ enum RgfxStage : unsigned {
failed.header.type = RGFX_EVT_CB_COMPLETE;
failed.cb_obj_id = [self rgfxObjId];
failed.status = RGFX_CB_INTERNAL;
failed.error_code = MTLCommandBufferErrorOutOfMemory;
failed.error_code =
heldPosted ? MTLCommandBufferErrorOutOfMemory : MTLCommandBufferErrorInternal;
RgfxCmdBuffer *strongSelf = self;
[self rgfxHostDone:&failed];
[queue rgfxDeliver:^{
+20 -3
View File
@@ -223,9 +223,10 @@ bool RgfxRingWriter::postLater(uint32_t type, const void *message, uint32_t size
bool arm = false;
{
std::lock_guard<std::mutex> hold(later->lock);
// A call takes at most maxBytes: the held go first where this one would not fit with them.
if (later->held.size() + size > later->maxBytes)
later->flush();
// A call takes at most maxBytes: the held go first where this one would not fit with them,
// and it is refused where they do not, as a post behind them would be.
if (later->held.size() + size > later->maxBytes && !later->flush())
return false;
const size_t at = later->held.size();
later->held.resize(at + size);
std::memcpy(later->held.data() + at, message, size);
@@ -251,6 +252,22 @@ bool RgfxRingWriter::flushLater()
return later->flush();
}
bool RgfxRingWriter::holdsBut(uint32_t type)
{
RgfxRingLater *later = m_later.get();
if (later == nullptr || !later->any.load(std::memory_order_acquire))
return false;
std::lock_guard<std::mutex> hold(later->lock);
for (size_t at = 0; at < later->held.size();) {
RgfxMsgHeader header;
std::memcpy(&header, later->held.data() + at, sizeof(header));
if (header.type != type)
return true;
at += header.size;
}
return false;
}
bool RgfxRingWriter::tryPostKnown(uint32_t type, const void *message, uint32_t size,
uint64_t *out_seqno, bool *out_deferred)
{
+11 -7
View File
@@ -147,19 +147,23 @@ public:
/// Whether postLater() holds messages to go together (setBatch).
bool batches() const { return m_later != nullptr; }
/// Posts a message no one waits for (a destroy) together with others where the writer
/// batches (setBatch): held, to go in the order held before anything the writer posts after
/// it (each tryPost, tryPostKnown and tryPostShared posts the held first), at flushLater(),
/// once the held reach the batch's bytes, or setBatch's time after the first held. Else, or for
/// a message larger than a batch, posted as tryPost() posts it. True once held or posted. A
/// held message the route refuses stays held, first, and the writer posts nothing else until
/// it goes.
/// Posts a message no one waits for (a destroy, a heap-placed buffer) together with others
/// where the writer batches (setBatch): held, to go in the order held before anything the
/// writer posts after it (each tryPost, tryPostKnown and tryPostShared posts the held first),
/// at flushLater(), once the held reach the batch's bytes, or setBatch's time after the first
/// held. Else, or for a message larger than a batch, posted as tryPost() posts it. True once
/// held or posted; false, holding nothing more, where the held had to go first to make room
/// and the route refused them. A held message the route refuses stays held, first, and the
/// writer posts nothing else until it goes.
bool postLater(uint32_t type, const void *message, uint32_t size);
/// Posts what postLater() holds, in its order: whether none is held now. One atomic load
/// where none is.
bool flushLater();
/// Whether postLater() holds a message of a type other than `type`.
bool holdsBut(uint32_t type);
/// Whether the route keeps answers for later (setDeferred), so a known pipeline create need
/// not wait.
bool defers() const { return m_forward != nullptr && m_deferredPost != nullptr; }
+37 -15
View File
@@ -448,7 +448,9 @@ RgfxCreated RgfxSerializer::createBufferAtOffset(RgfxObjId heap, uint64_t offset
msg.offset = offset;
msg.length = length;
msg.options = RgfxHostResourceOptions(options);
out.posted = m_control.tryPost(RGFX_CMD_BUFFER_AT_OFFSET, &msg, sizeof(msg), &out.seqno);
out.posted = m_control.batches()
? m_control.postLater(RGFX_CMD_BUFFER_AT_OFFSET, &msg, sizeof(msg))
: m_control.tryPost(RGFX_CMD_BUFFER_AT_OFFSET, &msg, sizeof(msg), &out.seqno);
return out;
}
@@ -1613,20 +1615,41 @@ bool RgfxSerializer::destroy(RgfxObjId obj_id, std::function<void()> after, bool
// A waiting record may name the object (a pipeline or a buffer the app lets go after
// encoding it), so the records go first.
flushIcbWrites();
// Refused just now: it waits for the next destroy or commit.
auto noteRefused = [obj_id] {
static std::atomic<bool> logged{false};
if (!logged.exchange(true))
std::fprintf(stderr,
"RGFX: the destroy of 0x%llx was not posted: it waits, and what the "
"object lies over stays the host's, until a later destroy or commit posts "
"it\n",
static_cast<unsigned long long>(obj_id));
};
// Held to go with others, before anything the process posts after it: what it lay over goes
// back now, as anything that takes it again is posted after the destroy.
// back now, as anything that takes it again is posted after the destroy. Behind the destroys
// refused before, which go first; refused (they or the held before it were), it waits behind
// them.
if (m_control.batches()) {
RgfxObjectDestroy msg = {};
msg.obj_id = obj_id;
const uint32_t type = RGFX_CMD_OBJECT_DESTROY;
const bool posted = atOnce ? m_control.tryPost(type, &msg, sizeof(msg), nullptr)
: m_control.postLater(type, &msg, sizeof(msg));
bool posted = postWaitingDestroys();
if (posted) {
RgfxObjectDestroy msg = {};
msg.obj_id = obj_id;
const uint32_t type = RGFX_CMD_OBJECT_DESTROY;
posted = atOnce ? m_control.tryPost(type, &msg, sizeof(msg), nullptr)
: m_control.postLater(type, &msg, sizeof(msg));
}
if (posted) {
if (after)
after();
return true;
}
// Refused at once (the held before it were too): it waits as below.
{
std::lock_guard<std::mutex> lock(m_destroyLock);
m_destroys.push_back({obj_id, std::move(after)});
m_destroysWaiting.store(true, std::memory_order_release);
}
noteRefused();
return false;
}
// With none waiting, it goes at once; else behind those waiting, which go first.
const bool behind = m_destroysWaiting.load(std::memory_order_acquire);
@@ -1642,16 +1665,15 @@ bool RgfxSerializer::destroy(RgfxObjId obj_id, std::function<void()> after, bool
}
if (behind)
return postWaitingDestroys();
// Refused just now: it waits for the next destroy or commit.
static std::atomic<bool> logged{false};
if (!logged.exchange(true))
std::fprintf(stderr,
"RGFX: the destroy of 0x%llx was not posted: it waits, and what the object "
"lies over stays the host's, until a later destroy or commit posts it\n",
static_cast<unsigned long long>(obj_id));
noteRefused();
return false;
}
bool RgfxSerializer::postHeldCreates()
{
return m_control.flushLater() || !m_control.holdsBut(RGFX_CMD_OBJECT_DESTROY);
}
bool RgfxSerializer::postWaitingDestroys()
{
if (!m_destroysWaiting.load(std::memory_order_acquire))
+12 -2
View File
@@ -432,7 +432,10 @@ public:
RgfxCreated createBufferOverPages(uint64_t length, uint32_t options, uint64_t block_offset,
uint64_t block_size, uint64_t offset);
/// A buffer at `offset` in the heap `heap`.
/// A buffer at `offset` in the heap `heap`. No one waits for it: where the control ring
/// batches (RgfxRingWriter::postLater), it is held to go with the messages around it, before
/// anything posted after it and before any command buffer committed after it
/// (postHeldCreates), and `seqno` is 0.
RgfxCreated createBufferAtOffset(RgfxObjId heap, uint64_t offset, uint64_t length,
uint32_t options);
@@ -725,7 +728,8 @@ public:
/// whatever reuses what it gives back, a create or a block's free, is posted after the held
/// destroys, so the host still drops the object first. A destroy the host orders other
/// contexts' messages by goes `atOnce`: a texture over an IOSurface, which a present of the
/// surface waits for (docs/graphics-kext/design.md, "Destroys go together").
/// surface waits for (docs/graphics-kext/design.md, "Destroys and heap-placed buffers go
/// together").
bool destroy(RgfxObjId obj_id, std::function<void()> after = {}, bool atOnce = false);
/// Posts the destroys waiting (destroy()), in the order they were made, each one's `after`
@@ -733,6 +737,12 @@ public:
/// Returns whether none waits now.
bool postWaitingDestroys();
/// Posts what the control ring holds to go together (RgfxRingWriter::postLater), as a command
/// buffer's commit does before the buffer goes on its ring, which the host reads after the
/// control ring's messages posted before it: whether no create stays held, which the buffer
/// may name. Destroys left held wait for a later post, as refused ones do.
bool postHeldCreates();
/// The default alignment for a picked GPU address when the caller names none.
/// The caller passes a caps-derived alignment where Metal demands one; this
/// is a safe floor for the first slice.
+126
View File
@@ -55,6 +55,7 @@
#include "rgfx_test_ring.hpp" // CHECK, g_checks, TestRing, expectMessage
void rgfxProtocolTests();
void drainRing(TestRing &ring); // shell_tests.mm
namespace {
@@ -477,6 +478,130 @@ void test_inline_bytes_without_region()
} // @autoreleasepool
}
// A control route as the kext's, which holds destroys and heap-placed buffers to go together
// (RgfxRingWriter::setBatch), over `direct`'s ring; while `refuse` is set it takes nothing, as the
// kext where its control ring stays full or the device stopped.
struct RefusingKext {
RgfxRingWriter *direct;
bool refuse = false;
static bool submit(void *context, const void *message, uint32_t size, uint64_t *out_seqno,
uint32_t *out_status)
{
RefusingKext *kext = static_cast<RefusingKext *>(context);
RgfxMsgHeader header;
std::memcpy(&header, message, sizeof(header));
if (out_status)
*out_status = kRgfxNoAnswer;
return !kext->refuse && kext->direct->tryPost(header.type, message, size, out_seqno);
}
static uint32_t batch(void *context, const void *messages, uint32_t bytes)
{
RefusingKext *kext = static_cast<RefusingKext *>(context);
const uint8_t *m = static_cast<const uint8_t *>(messages);
uint32_t posted = 0;
for (uint32_t at = 0; at < bytes && !kext->refuse; posted++) {
RgfxMsgHeader header;
std::memcpy(&header, m + at, sizeof(header));
if (!kext->direct->tryPost(header.type, m + at, header.size, nullptr))
break;
at += header.size;
}
return posted;
}
};
// A heap-placed buffer the kext never took when it was made (RgfxSerializer::createBufferAtOffset
// holds it to go with others) fails the next command buffer committed, unposted, with
// MTLCommandBufferErrorInternal, as the buffer may name it, and the next post is refused, as a
// full control ring refuses it; once the kext takes them again, the buffer goes before the next
// command buffer, which goes on its ring.
void test_commit_behind_an_untaken_buffer_fails()
{
TestRing control(0x8000);
RgfxRingWriter direct(control.base(), control.dataSize, RGFX_CONTROL_RING_ID,
TestRing::doorbell, nullptr);
RefusingKext kext{&direct};
RgfxRingWriter writer(&RefusingKext::submit, &kext, 0x4000);
writer.setBatch(&RefusingKext::batch, 4096, 600ull * 1000000000);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
TestRing submit(0x8000);
RgfxRingWriter submitWriter(submit.base(), submit.dataSize, 1, TestRing::doorbell, nullptr);
TestRing completion(0x8000);
RgfxReplyReader reader(completion.base(), completion.dataSize);
std::vector<uint8_t> mem(0x800000, 0);
RgfxRegion region(mem.data(), mem.size());
control.setConsumerIdle(1);
submit.setConsumerIdle(1);
@autoreleasepool {
RgfxCommandQueue *queue = nil;
@autoreleasepool {
queue = [RgfxCommandQueue queueWithSubmitRing:&submitWriter
submitOffset:0
completeOffset:0
completeDataSize:0
ids:&ids
maxCount:0
device:nil
serializer:&ser];
}
CHECK(queue != nil);
queue.replyReader = &reader;
queue.region = &region;
(void)expectQueueCreate(control);
MTLHeapDescriptor *hd = [[MTLHeapDescriptor alloc] init];
hd.size = 0x100000;
hd.storageMode = MTLStorageModePrivate;
RgfxHeap *heap = [RgfxHeap heapWithDescriptor:hd device:nil serializer:&ser];
CHECK(heap != nil);
drainRing(control);
// Made while the kext takes nothing: answered as made, held.
kext.refuse = true;
id<MTLBuffer> buffer = [heap newBufferWithLength:256 options:MTLResourceStorageModePrivate];
CHECK(buffer != nil);
id<MTLCommandBuffer> cb = [queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit fillBuffer:buffer range:NSMakeRange(0, 256) value:0];
[blit endEncoding];
[cb commit];
[cb waitUntilCompleted];
CHECK(cb.status == MTLCommandBufferStatusError);
CHECK(cb.error != nil && [cb.error.domain isEqualToString:MTLCommandBufferErrorDomain] &&
cb.error.code == MTLCommandBufferErrorInternal);
RgfxMsgHeader h = {};
std::vector<uint8_t> bytes;
CHECK(!submit.next(&h, &bytes));
CHECK(!control.next(&h, &bytes));
// The next post is refused: the held go first, and the kext takes none of them.
CHECK(!ser.createEvent().posted);
// The kext takes them again: the buffer goes, then the next command buffer is posted.
kext.refuse = false;
id<MTLCommandBuffer> next = [queue commandBuffer];
id<MTLBlitCommandEncoder> blit2 = [next blitCommandEncoder];
[blit2 fillBuffer:buffer range:NSMakeRange(0, 256) value:1];
[blit2 endEncoding];
[next commit];
CHECK(control.next(&h, &bytes) && h.type == RGFX_CMD_BUFFER_AT_OFFSET);
uint64_t obj = 0;
std::memcpy(&obj, bytes.data() + sizeof(h), sizeof(obj));
CHECK(obj == [(RgfxResource *)buffer rgfxObjId]);
CHECK(submit.next(&h, &bytes) && h.type == RGFX_CMD_COMMAND_BUFFER);
RgfxCbComplete done = {};
done.header.type = RGFX_EVT_CB_COMPLETE;
done.header.size = sizeof(done);
done.header.seqno = h.seqno;
done.cb_obj_id = ((RgfxResource *)next).rgfxObjId;
done.status = RGFX_CB_OK;
CHECK(completion.postFromHost(&done, sizeof(done)));
[next waitUntilCompleted];
CHECK(next.status == MTLCommandBufferStatusCompleted);
}
}
// The render barriers: the scope barrier as given; a resource barrier as the scope of the
// resources' kinds; the texture barrier as the render targets' fragment barrier.
void test_render_barriers()
@@ -2742,6 +2867,7 @@ void rgfxProtocolTests()
test_inline_bytes();
test_inline_bytes_parallel();
test_inline_bytes_without_region();
test_commit_behind_an_untaken_buffer_fails();
test_render_barriers();
test_compute_dispatch_type();
test_compute_function_table_bindings();
+1 -1
View File
@@ -1497,7 +1497,7 @@ struct KextRing {
for (uint32_t at = 0; at < bytes; posted++) {
RgfxMsgHeader header;
std::memcpy(&header, m + at, sizeof(header));
CHECK(header.type == RGFX_CMD_OBJECT_DESTROY);
CHECK(header.type == RGFX_CMD_OBJECT_DESTROY || header.type == RGFX_CMD_BUFFER_AT_OFFSET);
if (!kext->direct.tryPost(header.type, m + at, header.size, nullptr))
break;
at += header.size;
+86 -1
View File
@@ -2457,7 +2457,10 @@ uint32_t kextSubmitBatch(void *context, const void *messages, uint32_t bytes)
for (uint32_t at = 0; at < bytes && taken < log->batchTakes; taken++) {
RgfxMsgHeader header;
std::memcpy(&header, m + at, sizeof(header));
CHECK(header.size == sizeof(RgfxObjectDestroy) && header.seqno == 0);
CHECK(header.seqno == 0);
CHECK(header.type == RGFX_CMD_OBJECT_DESTROY ? header.size == sizeof(RgfxObjectDestroy)
: header.type == RGFX_CMD_BUFFER_AT_OFFSET &&
header.size == sizeof(RgfxBufferAtOffset));
call.objs.push_back(KextLog::objOf(m + at));
call.types.push_back(header.type);
at += header.size;
@@ -2571,6 +2574,87 @@ void test_held_destroys()
CHECK(ending.calls.size() == 1);
}
// Heap-placed buffers held to go together with the destroys around them
// (RgfxSerializer::createBufferAtOffset): each answered as made and held, in their order with the
// destroys, before anything posted after them; a commit's postHeldCreates() answers whether none
// stays held, destroys left aside; a buffer that needs the held to go first to make room is
// refused at once where they are refused, holding nothing more; a writer that does not batch
// posts each at once, as before.
void test_held_buffers()
{
constexpr uint64_t kNever = 600ull * 1000000000;
KextLog log;
RgfxRingWriter writer(&kextSubmit, &log, 4096);
writer.setBatch(&kextSubmitBatch, 4096, kNever);
RgfxIdSpace ids;
RgfxSerializer ser(writer, ids);
RgfxCreated a = ser.createBufferAtOffset(0x10, 0, 256, 0);
CHECK(a.posted && a.obj_id != 0 && a.seqno == 0);
CHECK(ser.destroy(0x101));
RgfxCreated b = ser.createBufferAtOffset(0x10, 256, 256, 0);
CHECK(b.posted);
CHECK(log.calls.empty());
CHECK(ser.postHeldCreates());
CHECK(log.calls.size() == 1 && log.calls[0].batch);
CHECK(log.calls[0].objs == std::vector<RgfxObjId>({a.obj_id, 0x101, b.obj_id}));
CHECK(log.calls[0].types == std::vector<uint32_t>({RGFX_CMD_BUFFER_AT_OFFSET,
RGFX_CMD_OBJECT_DESTROY,
RGFX_CMD_BUFFER_AT_OFFSET}));
// Before what is posted after them.
log.calls.clear();
RgfxCreated c = ser.createBufferAtOffset(0x10, 512, 256, 0);
RgfxCreated ev = ser.createEvent();
CHECK(c.posted && ev.posted);
CHECK(log.ring() == std::vector<RgfxObjId>({c.obj_id, ev.obj_id}));
// The kext takes none: a held buffer leaves the commit's answer false, held destroys alone
// do not; once it takes them they go, in order.
log.calls.clear();
log.batchTakes = 0;
CHECK(ser.destroy(0x201));
CHECK(ser.postHeldCreates());
RgfxCreated d = ser.createBufferAtOffset(0x10, 768, 256, 0);
CHECK(d.posted);
CHECK(!ser.postHeldCreates());
CHECK(!ser.postHeldCreates());
CHECK(log.calls.empty());
// So is the next post refused, posting nothing.
CHECK(!ser.createEvent().posted);
CHECK(log.calls.empty());
log.batchTakes = UINT32_MAX;
CHECK(ser.postHeldCreates());
CHECK(log.ring() == std::vector<RgfxObjId>({0x201, d.obj_id}));
// 73 buffers fill a call (56 bytes each): with the kext taking none, the 74th, which needs
// them gone to make room, is refused, and nothing more is held; once the kext takes them,
// the 73 go in one call.
log.calls.clear();
std::vector<RgfxObjId> held;
for (int i = 0; i < 73; i++) {
RgfxCreated m = ser.createBufferAtOffset(0x10, 4096u * i, 64, 0);
CHECK(m.posted);
held.push_back(m.obj_id);
}
CHECK(log.calls.empty());
log.batchTakes = 0;
CHECK(!ser.createBufferAtOffset(0x10, 0, 64, 0).posted);
log.batchTakes = UINT32_MAX;
CHECK(writer.flushLater());
CHECK(log.calls.size() == 1 && log.calls[0].batch && log.calls[0].objs == held);
// A writer that does not batch posts each at once.
KextLog plain;
RgfxRingWriter direct(&kextSubmit, &plain, 4096);
RgfxSerializer pser(direct, ids);
RgfxCreated p = pser.createBufferAtOffset(0x10, 0, 64, 0);
CHECK(p.posted && p.seqno != 0);
CHECK(plain.calls.size() == 1 && !plain.calls[0].batch &&
plain.calls[0].types[0] == RGFX_CMD_BUFFER_AT_OFFSET);
CHECK(pser.postHeldCreates());
}
// A synthetic .metallib: its header (the bitcode section at 0x60, 16 bytes), a stand-in for the
// function list, the bitcode, and a tail.
std::vector<uint8_t> syntheticMetallib()
@@ -3864,6 +3948,7 @@ int main()
test_render_pass_visibility();
test_forwarded_lifecycle();
test_held_destroys();
test_held_buffers();
test_library_key();
test_library_key_of_file();
test_keyed_library_messages();
+33 -8
View File
@@ -2580,20 +2580,43 @@ IOReturn ReimsGraphics::postRun(UInt32 type, const void *messages, UInt32 size,
UInt64 *const *waiterSeqnos, UInt32 *posted)
{
*posted = 0;
if (size < kHeaderBytes || size % kMsgAlign || size > kLifecycleMessageMax)
return kIOReturnBadArgument;
const UInt8 *bytes = static_cast<const UInt8 *>(messages);
// Each message's type and size, the run's or, with `type` 0, its own header's.
auto at = [&](size_t offset, UInt32 *t, UInt32 *n) {
*t = type;
*n = size;
if (type == 0) {
RgfxMsgHeader h;
memcpy(&h, bytes + offset, sizeof(h));
*t = h.type;
*n = h.size;
}
};
size_t length = 0;
for (UInt32 i = 0; i < count; i++) {
UInt32 t = 0, n = 0;
at(length, &t, &n);
if (n < kHeaderBytes || n % kMsgAlign || n > kLifecycleMessageMax)
return kIOReturnBadArgument;
length += n;
}
uint64_t deadline = 0;
clock_interval_to_deadline(kPostTimeoutMs, kMillisecondScale, &deadline);
// As many as fit, under one hold of the ring's lock and with one doorbell at most: whether
// all are posted.
// all are posted. `next` is where the first not yet posted lies.
size_t next = 0;
auto look = [&]() {
UInt32 n = 0;
IOSimpleLockLock(submitLock);
while (*posted + n < count &&
writeLocked(type, bytes + static_cast<size_t>(*posted + n) * size, size, nullptr,
waiterSeqnos ? waiterSeqnos[*posted + n] : nullptr))
while (*posted + n < count) {
UInt32 t = 0, m = 0;
at(next, &t, &m);
if (!writeLocked(t, bytes + next, m, nullptr,
waiterSeqnos ? waiterSeqnos[*posted + n] : nullptr))
break;
next += m;
n++;
}
if (n)
publishLocked();
IOSimpleLockUnlock(submitLock);
@@ -2607,9 +2630,11 @@ IOReturn ReimsGraphics::postRun(UInt32 type, const void *messages, UInt32 size,
if (look() || (askForRoom() && look()))
break;
if (!waitForRoom(mark, deadline)) {
UInt32 t = 0, m = 0;
at(next, &t, &m);
static char site;
if (rgfxFirstCalls(&site, type, 1))
IOLog("ReimsGraphics: command %u: the control ring stayed full\n", type);
if (rgfxFirstCalls(&site, t, 1))
IOLog("ReimsGraphics: command %u: the control ring stayed full\n", t);
return ready ? kIOReturnTimeout : kIOReturnNotReady;
}
}
+5 -4
View File
@@ -296,10 +296,11 @@ public:
void setReleaseAnswer(OSObject *target, ReleaseAnswerHook hook);
IOReturn postReleases(const RgfxBlockRelease *releases, UInt32 count,
UInt64 *const *waiterSeqnos, UInt32 *posted);
// `count` messages of `type`, each `size` bytes at `messages` back to back, which no thread
// waits for: on the control ring in order as postReleases puts its releases (each one's seqno
// into *waiterSeqnos[i] where `waiterSeqnos` is not null), *posted those posted. A process's
// destroys in one call (kRgfxAccelMethodSubmitBatch) and the block releases go so.
// `count` messages of `type`, each `size` bytes at `messages` back to back, or, with `type`
// 0 (the pad's, never a command's), each of the type and size its own header names, which no
// thread waits for: on the control ring in order as postReleases puts its releases (each
// one's seqno into *waiterSeqnos[i] where `waiterSeqnos` is not null), *posted those posted.
// A process's batch (kRgfxAccelMethodSubmitBatch) and the block releases go so.
IOReturn postRun(UInt32 type, const void *messages, UInt32 size, UInt32 count,
UInt64 *const *waiterSeqnos, UInt32 *posted);
// A lifecycle message (a CONTEXT_CLOSE) no thread waits for here, its COMPLETE handed to the
+3 -2
View File
@@ -521,8 +521,9 @@ public:
IOReturn postLifecycle(UInt32 type, const void *message, UInt32 size, UInt32 replyType,
void *reply, UInt32 replyCapacity, UInt32 *replyLength, UInt64 *seqno,
UInt32 timeoutMs);
// `count` lifecycle messages of `type` no thread waits for, `size` bytes each, in one hold of
// the control ring (ReimsGraphics::postRun): *posted those posted.
// `count` lifecycle messages of `type` no thread waits for, `size` bytes each (with `type` 0,
// each its own header's type and size), in one hold of the control ring
// (ReimsGraphics::postRun): *posted those posted.
IOReturn postRun(UInt32 type, const void *messages, UInt32 size, UInt32 count,
UInt32 *posted);
// The deferred pipeline creates (ReimsGraphics::postDeferred, takeDeferred, dropDeferred,
@@ -636,62 +636,101 @@ IOReturn RgfxAcceleratorUserClient::submitMethod(IOExternalMethodArguments *a)
return kIOReturnSuccess;
}
// kRgfxAccelMethodSubmitBatch (RgfxUserClientABI.hpp): the client's destroys of its own objects
// onto the control ring in one call, each checked as submitMethod checks one, all before any is
// posted, then posted in their order: the runs between its queues' destroys under one hold of the
// ring each (RgfxAccelerator::postRun), and each queue's destroy routed as submitMethod routes it
// (destroyQueueIfTracked) after the run before it. The count out says how many went: all of them,
// but where a run met a ring that stayed full or a device that stopped.
// kRgfxAccelMethodSubmitBatch (RgfxUserClientABI.hpp): the client's destroys and heap-placed
// buffers of its own objects onto the control ring in one call, each checked as submitMethod
// checks one, all before any is posted, then posted in their order: the runs between its queues'
// destroys under one hold of the ring each (RgfxAccelerator::postRun), and each queue's destroy
// routed as submitMethod routes it (destroyQueueIfTracked) after the run before it. A buffer
// made for a context that closed since the check is destroyed behind it, as submitMethod does
// (rgfxSubmitDestroysBehind). The count out says how many went: all of them, but where a run met
// a ring that stayed full or a device that stopped.
IOReturn RgfxAcceleratorUserClient::submitBatchMethod(IOExternalMethodArguments *a)
{
IOLockLock(listLock);
const bool open = hasContext;
const UInt32 ctx = context;
IOLockUnlock(listLock);
// An inline struct in, in kernel memory already: a whole number of destroys.
constexpr UInt32 kSize = sizeof(RgfxObjectDestroy);
// An inline struct in, in kernel memory already: whole messages back to back.
const UInt64 size = a->structureInputSize;
if (!open || a->scalarInputCount != 0 || a->scalarOutputCount != 1 ||
a->structureInputDescriptor || !a->structureInput || size == 0 || size % kSize ||
a->structureInputDescriptor || !a->structureInput || size == 0 ||
size > kRgfxSubmitBatchBytes)
return kIOReturnBadArgument;
const UInt8 *messages = static_cast<const UInt8 *>(a->structureInput);
const UInt32 count = static_cast<UInt32>(size / kSize);
auto objIdAt = [&](UInt32 i) {
// Each message of a type the batch takes, of that type's size, its obj_id the context's.
UInt32 count = 0;
for (UInt64 at = 0; at < size; count++) {
RgfxMsgHeader header;
if (size - at < sizeof(header))
return kIOReturnBadArgument;
memcpy(&header, messages + at, sizeof(header));
UInt64 objId = 0;
memcpy(&objId, messages + static_cast<size_t>(i) * kSize + kObjIdOffset, sizeof(objId));
if (header.size == 0 || header.size != rgfxSubmitBatchSize(header.type) ||
header.size > size - at)
return kIOReturnBadArgument;
memcpy(&objId, messages + at + kObjIdOffset, sizeof(objId));
if ((objId >> RGFX_CONTEXT_OBJ_ID_SHIFT) != ctx)
return kIOReturnBadArgument;
at += header.size;
}
auto typeAt = [&](UInt64 at) {
UInt32 type = 0;
memcpy(&type, messages + at, sizeof(type));
return type;
};
auto sizeAt = [&](UInt64 at) {
RgfxMsgHeader header;
memcpy(&header, messages + at, sizeof(header));
return header.size;
};
auto objIdAt = [&](UInt64 at) {
UInt64 objId = 0;
memcpy(&objId, messages + at + kObjIdOffset, sizeof(objId));
return objId;
};
for (UInt32 i = 0; i < count; i++) {
UInt32 type = 0;
memcpy(&type, messages + static_cast<size_t>(i) * kSize, sizeof(type));
if (!rgfxSubmitBatchAdmitted(type) || (objIdAt(i) >> RGFX_CONTEXT_OBJ_ID_SHIFT) != ctx)
return kIOReturnBadArgument;
}
UInt32 done = 0, from = 0;
UInt64 fromAt = 0, at = 0;
IOReturn r = kIOReturnSuccess;
for (UInt32 i = 0; i <= count && r == kIOReturnSuccess; i++) {
if (i < count && !queueListed(objIdAt(i)))
if (i < count && !(rgfxSubmitRoutesQueueDestroy(typeAt(at)) && queueListed(objIdAt(at)))) {
at += sizeAt(at);
continue;
}
UInt32 posted = 0;
if (i > from)
r = owner->postRun(RGFX_CMD_OBJECT_DESTROY,
messages + static_cast<size_t>(from) * kSize, kSize, i - from,
&posted);
r = owner->postRun(0, messages + fromAt, 0, i - from, &posted);
done += posted;
if (r == kIOReturnSuccess && i < count) {
// A queue's, ended as Submit ends it; where another thread ended the queue since the
// look, posted as it is, as Submit posts it then.
if (!destroyQueueIfTracked(objIdAt(i))) {
if (!destroyQueueIfTracked(objIdAt(at))) {
UInt32 one = 0;
r = owner->postRun(RGFX_CMD_OBJECT_DESTROY,
messages + static_cast<size_t>(i) * kSize, kSize, 1, &one);
r = owner->postRun(0, messages + at, 0, 1, &one);
done += one;
} else {
done++;
}
}
if (i < count)
at += sizeAt(at);
from = i + 1;
fromAt = at;
}
// The creates posted for a context that closed since the check: its CONTEXT_CLOSE may have
// gone before them, which the device's close then never dropped.
IOLockLock(listLock);
const bool closedSince = !hasContext || context != ctx;
IOLockUnlock(listLock);
at = 0;
for (UInt32 i = 0; i < done && closedSince; i++) {
if (rgfxSubmitDestroysBehind(typeAt(at), true, false, true)) {
RgfxObjectDestroy destroy = {};
destroy.header.type = RGFX_CMD_OBJECT_DESTROY;
destroy.obj_id = objIdAt(at);
owner->postLifecycle(RGFX_CMD_OBJECT_DESTROY, &destroy, sizeof(destroy), 0, nullptr,
0, nullptr, nullptr, 0);
}
at += sizeAt(at);
}
a->scalarOutput[0] = done;
return kIOReturnSuccess;
+15 -5
View File
@@ -56,12 +56,22 @@ inline bool rgfxSubmitRoutesQueueDestroy(uint32_t type)
return type == RGFX_CMD_OBJECT_DESTROY;
}
// Whether kRgfxAccelMethodSubmitBatch takes a message of `type`: an OBJECT_DESTROY alone, which no
// one waits for, names no block and makes nothing (the caller also checks its obj_id lies in the
// sender's context, and routes a queue's as rgfxSubmitRoutesQueueDestroy says).
inline bool rgfxSubmitBatchAdmitted(uint32_t type)
// The size of a message of `type` kRgfxAccelMethodSubmitBatch takes, 0 for a type it does not
// take: an OBJECT_DESTROY, and a BUFFER_AT_OFFSET, the buffer a heap places at an offset. Neither
// is waited for nor names a block (rgfxRegionSpans), and each is of one size, which its header
// must name. The caller also checks each obj_id lies in the sender's context, routes a queue's
// destroy as rgfxSubmitRoutesQueueDestroy says, and follows a create with its destroy as
// rgfxSubmitDestroysBehind says.
inline uint32_t rgfxSubmitBatchSize(uint32_t type)
{
return type == RGFX_CMD_OBJECT_DESTROY;
switch (type) {
case RGFX_CMD_OBJECT_DESTROY:
return sizeof(RgfxObjectDestroy);
case RGFX_CMD_BUFFER_AT_OFFSET:
return sizeof(RgfxBufferAtOffset);
default:
return 0;
}
}
// Whether an accepted `type` is a pipeline create: a render, mesh render or compute pipeline's,
+12 -10
View File
@@ -71,15 +71,17 @@ enum {
// kIOReturnNoSpace or kIOReturnNoResources where the region or the kext's table has no room
// for the block.
kRgfxAccelMethodPagesBlock = 4,
// Posts the client's destroys of its own objects on the control ring in one call
// (kRgfxKextFeatureSubmitBatch): struct in, inline, OBJECT_DESTROY messages back to back,
// each whole (its header's type set; the kext stamps its size and seqno) and of an object in
// the client's context, at most kRgfxSubmitBatchBytes in all; out: how many were posted, in
// their order, each as kRgfxAccelMethodSubmit posts it (a destroy of one of the client's
// command queues ends the queue as Submit's does, after the destroys before it). None is
// posted where any is not such a destroy (kIOReturnBadArgument). Succeeds with fewer than
// all only where the control ring stayed full or the device stopped: the rest were not
// posted, and go in a later call, before anything else of the client's.
// Posts the client's destroys and heap-placed buffers of its own objects on the control ring
// in one call (kRgfxKextFeatureSubmitBatch): struct in, inline, OBJECT_DESTROY and
// BUFFER_AT_OFFSET messages back to back, each whole (its header's type and size set, the
// size its type's; the kext stamps its seqno) and of an object in the client's context, at
// most kRgfxSubmitBatchBytes in all; out: how many were posted, in their order, each as
// kRgfxAccelMethodSubmit posts it (a destroy of one of the client's command queues ends the
// queue as Submit's does, after the messages before it; a buffer of a context closed since is
// destroyed behind it). None is posted where any is not such a message
// (kIOReturnBadArgument). Succeeds with fewer than all only where the control ring stayed full
// or the device stopped: the rest were not posted, and go in a later call, before anything
// else of the client's.
kRgfxAccelMethodSubmitBatch = 5,
// 6 is kept for WakeCompletions (kRgfxKextFeatureWakeCompletions).
// The answers to the client's deferred pipeline creates (Submit's kRgfxSubmitDeferred) the
@@ -288,7 +290,7 @@ enum {
};
// The most bytes of messages one kRgfxAccelMethodSubmitBatch takes: an inline struct in, 170
// destroys.
// destroys or 73 heap-placed buffers.
enum {
kRgfxSubmitBatchBytes = 4096,
};
+9
View File
@@ -4,6 +4,7 @@
#include <cstring>
#include "RgfxRegionSpans.hpp"
#include "RgfxSubmitGate.hpp"
static int g_checks = 0, g_failed = 0;
#define CHECK(e) \
@@ -80,6 +81,14 @@ int main()
CHECK(spansOf(RGFX_CMD_BUFFER_AT_OFFSET, atOffset, sizeof(atOffset), s) == 0);
RgfxLibraryCreate library = {};
CHECK(spansOf(RGFX_CMD_LIBRARY_CREATE, library, 8, s) == 0);
// Nor does any message SubmitBatch takes, which it posts with no block pinned.
uint8_t batched[256] = {};
for (uint32_t type = 0; type <= RGFX_CMD_CONTEXT_CLOSE + 64; type++) {
const uint32_t size = rgfxSubmitBatchSize(type);
CHECK(size <= sizeof(batched));
if (size != 0 && size <= sizeof(batched))
CHECK(rgfxRegionSpans(type, batched, size, s) == 0);
}
if (g_failed) {
std::fprintf(stderr, "spans_test: %d of %d checks failed\n", g_failed, g_checks);
+11 -5
View File
@@ -60,16 +60,22 @@ int main()
check(!rgfxSubmitRoutesQueueDestroy(RGFX_CMD_QUEUE_CREATE), "QUEUE_CREATE does not route");
check(!rgfxSubmitRoutesQueueDestroy(RGFX_CMD_BLOCK_RELEASE), "BLOCK_RELEASE does not route");
// SubmitBatch takes destroys alone: a message no one waits for, which names no block and
// makes nothing, so the batch needs neither answers, pins nor destroys behind it. Every
// SubmitBatch takes destroys and heap-placed buffers, each of its one size: messages no one
// waits for, which name no block (spans_test), so the batch needs neither answers nor pins;
// the buffer is a create, which a close since the check follows with its destroy. Every
// other type, accepted by Submit or not, goes one call at a time.
check(rgfxSubmitBatchAdmitted(RGFX_CMD_OBJECT_DESTROY), "SubmitBatch takes OBJECT_DESTROY");
check(rgfxSubmitBatchSize(RGFX_CMD_OBJECT_DESTROY) == sizeof(RgfxObjectDestroy),
"SubmitBatch takes OBJECT_DESTROY, of its size");
check(rgfxSubmitBatchSize(RGFX_CMD_BUFFER_AT_OFFSET) == sizeof(RgfxBufferAtOffset),
"SubmitBatch takes BUFFER_AT_OFFSET, of its size");
check(rgfxSubmitAdmitted(RGFX_CMD_OBJECT_DESTROY) && !rgfxSubmitMakes(RGFX_CMD_OBJECT_DESTROY),
"a batched destroy is one Submit takes, and makes nothing");
check(rgfxSubmitAdmitted(RGFX_CMD_BUFFER_AT_OFFSET) && rgfxSubmitMakes(RGFX_CMD_BUFFER_AT_OFFSET),
"a batched heap-placed buffer is one Submit takes, and makes one");
for (uint32_t type = 0; type <= RGFX_CMD_CONTEXT_CLOSE + 64; type++) {
if (type == RGFX_CMD_OBJECT_DESTROY)
if (type == RGFX_CMD_OBJECT_DESTROY || type == RGFX_CMD_BUFFER_AT_OFFSET)
continue;
check(!rgfxSubmitBatchAdmitted(type), "SubmitBatch takes no other type");
check(rgfxSubmitBatchSize(type) == 0, "SubmitBatch takes no other type");
}
// Which accepted types make an object a destroy then drops: every type of the accepted