From ecf693f1bfdd5ee73b0d51efbd7026746d0f73da Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Thu, 12 Nov 2026 15:39:50 -0800 Subject: [PATCH] :racehorse: Build a large command buffer's message off its block A message too large for half its queue's ring was built in a block of the queue's pool once it outgrew the ring, and grew from block to block. The block is write-combined where the kext maps it so, and on an AMD host, which applies the guest's memory type, a write-combined store still pending stalls the encoding thread's next locked instruction until it drains. Every retain and release on that thread, the app's and ours, paid it: on a 26.7.2 guest of a Ryzen host (RTX 3090), encode_probe's setRenderPipelineState took 108 ns a call in a 10000-call buffer against 21.6 ns in a 400-call one, which stays on the builder's heap, and a setVertexBuffer between a CFRetain and a CFRelease 103 ns against 17.1 ns. Growing from block to block also read the old block back, uncached. The message is now built in the builder's own buffer whatever its size, which grows to the queue's guess as it outgrows the ring, and the commit copies it once, whole, into a block from the block's start. The host reads the same COMMAND_BUFFER bytes; only where the message lies in its block changes. The tests that held the old placement change with it. --- docs/graphics-kext/design.md | 14 ++-- guest/bundle/src/RgfxCommandObjects.mm | 4 +- guest/bundle/src/RgfxEncoder.cpp | 93 +++++++------------------ guest/bundle/src/RgfxEncoder.hpp | 56 ++++++++------- guest/bundle/src/RgfxUploads.h | 6 +- guest/bundle/tests/queue_tests.mm | 11 +-- guest/bundle/tests/serializer_tests.cpp | 47 ++++++++----- guest/bundle/tests/shell_tests.mm | 6 +- 8 files changed, 109 insertions(+), 128 deletions(-) diff --git a/docs/graphics-kext/design.md b/docs/graphics-kext/design.md index 3e5240b3e..33ade1791 100644 --- a/docs/graphics-kext/design.md +++ b/docs/graphics-kext/design.md @@ -2780,11 +2780,17 @@ A command buffer too large for half its queue's submission ring goes out of line: the whole `COMMAND_BUFFER` message lies in a block of the process's own, from its queue's pool, and the ring carries a `COMMAND_BUFFER_IN_REGION` (region offset and length). -- The bundle builds the message on its own heap while it fits half the ring. -- When it outgrows that, the message moves once into a block as large as the - queue's recent largest message, and doubles from block to block after that. +- The bundle builds the message on its own heap, write-back memory, whatever + its size. When it outgrows half the ring, its buffer grows at once to the + queue's recent largest message, and doubles after that. - The header and the commit's `SURFACE_USE` ops go into room kept before the - ops, so the commit posts the block with no copy. + ops, so they move nothing. +- At the commit, the whole message is copied once into a block of the pool, + from the block's start. It is not built there: the block is write-combined + where the kext maps it so, and on an AMD host, which applies the guest's + memory type, a write-combined store still pending stalls the encoding + thread's next locked instruction (an app's retain or release among them) by + about 90 ns (`RgfxEncoder.hpp`). The queue's service thread copies the message out of the block once, as it does a ring's, with the reference's seqno, and the host walks and commits the diff --git a/guest/bundle/src/RgfxCommandObjects.mm b/guest/bundle/src/RgfxCommandObjects.mm index c48d3e670..c8c6ea58f 100644 --- a/guest/bundle/src/RgfxCommandObjects.mm +++ b/guest/bundle/src/RgfxCommandObjects.mm @@ -1841,8 +1841,8 @@ enum RgfxStage : unsigned { cb->_profilingEnabled.store([queue isProfilingEnabled]); const uint32_t reserve = queue.rgfxMessageReserve; cb->_encoder = new RgfxEncoder(*ring, queue.rgfxObjId, cbObjId, reserve); - // Past its ring, the message is built in a block of the queue's pool, the size of the - // queue's recent largest first. + // Past its ring, the message grows to the size of the queue's recent largest at once, and + // goes into a block of the queue's pool at the commit. cb->_encoder->setMessageBlocks([queue rgfxBodyPool], reserve); // One with unretained references keeps them too, though it answers retainedReferences // NO: the host must not drop an object before a buffer that names it has run. diff --git a/guest/bundle/src/RgfxEncoder.cpp b/guest/bundle/src/RgfxEncoder.cpp index 9a797f2de..f40252ff9 100644 --- a/guest/bundle/src/RgfxEncoder.cpp +++ b/guest/bundle/src/RgfxEncoder.cpp @@ -98,72 +98,27 @@ void RgfxEncoder::giveBackBlock() m_block = {}; } -bool RgfxEncoder::moveToBlock(size_t size) -{ - RgfxMessageBlock block = {}; - if (m_blocks == nullptr || !m_blocks->take(size, &block)) - return false; - uint8_t *to = const_cast(block.ptr); - const size_t used = static_cast(m_cur - m_store); - std::memcpy(to, m_store, used); - if (m_inBlock) - giveBackBlock(); // never posted: no host reads it - else - std::free(m_store); - m_ops = to + (m_ops - m_store); - m_cur = to + used; - m_store = to; - m_end = to + block.size; - m_block = block; - m_inBlock = true; - return true; -} - -void RgfxEncoder::moveToHeap(size_t size) +void RgfxEncoder::grow(size_t n) { const size_t used = static_cast(m_cur - m_store); - uint8_t *to; - if (m_inBlock) { - to = static_cast(std::malloc(size)); - if (to != nullptr) - std::memcpy(to, m_store, used); - } else { - to = static_cast(std::realloc(m_store, size)); + size_t size = std::max(used + n, 2 * static_cast(m_end - m_store)); + // A message that outgrows its ring grows to its queue's guess at once (setMessageBlocks), so + // a large one is not copied again at each doubling. + if (m_ring != nullptr) { + const uint64_t message = RGFX_COMMAND_BUFFER_OPS_OFFSET + m_prefix + + static_cast(m_cur - m_ops) + n; + if (message > UINT32_MAX || !m_ring->fits(static_cast(message))) + size = std::max(size, kHeadroom + RGFX_COMMAND_BUFFER_OPS_OFFSET + m_sizeHint); } + uint8_t *to = static_cast(std::realloc(m_store, size)); if (to == nullptr) std::abort(); // as std::vector's growth ends the process where memory runs out - if (m_inBlock) { - giveBackBlock(); - m_inBlock = false; - } m_ops = to + (m_ops - m_store); m_cur = to + used; m_store = to; m_end = to + size; } -void RgfxEncoder::grow(size_t n) -{ - const size_t used = static_cast(m_cur - m_store); - const size_t need = used + n; - const size_t doubled = std::max(need, 2 * static_cast(m_end - m_store)); - // A message too large for its ring goes in a block: once it outgrows the ring it moves - // there, to a block as large as its queue's guess, and grows from block to block. - if (m_ring != nullptr && m_blocks != nullptr) { - const uint64_t message = RGFX_COMMAND_BUFFER_OPS_OFFSET + m_prefix + - static_cast(m_cur - m_ops) + n; - if (m_inBlock || message > UINT32_MAX || !m_ring->fits(static_cast(message))) { - const size_t first = m_inBlock ? doubled - : std::max(doubled, kHeadroom + - RGFX_COMMAND_BUFFER_OPS_OFFSET + - m_blockHint); - if (moveToBlock(first)) - return; - } - } - moveToHeap(doubled); -} - void RgfxEncoder::prependSurfaceUses(const RgfxOpSurfaceUse *uses, size_t count) { const size_t len = RGFX_OP_BODY_OFFSET + sizeof(RgfxOpSurfaceUse); @@ -228,26 +183,32 @@ bool RgfxEncoder::finish(uint64_t *out_seqno, const std::function &while return false; uint8_t *message = m_ops - m_prefix - RGFX_COMMAND_BUFFER_OPS_OFFSET; m_head.op_bytes = opBytes(); - if (!m_inBlock && m_ring->fits(static_cast(size))) { + if (m_ring->fits(static_cast(size))) { std::memcpy(message, &m_head, sizeof(m_head)); return m_ring->post(RGFX_CMD_COMMAND_BUFFER, message, static_cast(size), out_seqno, whileWaiting, beforePublish); } - // Out of line: the block the message was built in, else one it is copied to now. + // Out of line: the whole message copied once into a block of the pool, from its start. The + // host reads the block once the reference's `producer` is published, which the ring writer + // orders after these stores, write-combined ones among them (RgfxRingWriter's storeFence). m_head.header.type = RGFX_CMD_COMMAND_BUFFER; m_head.header.size = static_cast(size); m_head.header.seqno = 0; std::memcpy(message, &m_head, sizeof(m_head)); - if (!m_inBlock) { - const size_t at = static_cast(message - m_store); - if (!moveToBlock(static_cast(m_cur - m_store))) - return false; - message = m_store + at; - } - // Write-back memory the host reads once the reference's `producer` is published (a - // release store), so the message's writes are ordered before it. + RgfxMessageBlock block = {}; + if (m_blocks == nullptr || !m_blocks->take(size, &block)) + return false; + uint8_t *to = const_cast(block.ptr); + std::memcpy(to, message, static_cast(size)); + std::free(m_store); + m_store = to; + m_ops = to + RGFX_COMMAND_BUFFER_OPS_OFFSET + m_prefix; + m_cur = to + size; + m_end = to + block.size; + m_block = block; + m_inBlock = true; RgfxCommandBufferInRegion ref = {}; - ref.region_offset = m_block.offset + static_cast(message - m_store); + ref.region_offset = block.offset; ref.byte_length = size; if (held != nullptr) { // The holder has it before the host can see the message, as the completion may come diff --git a/guest/bundle/src/RgfxEncoder.hpp b/guest/bundle/src/RgfxEncoder.hpp index a43164ae1..93e5ef451 100644 --- a/guest/bundle/src/RgfxEncoder.hpp +++ b/guest/bundle/src/RgfxEncoder.hpp @@ -112,12 +112,18 @@ struct RgfxRenderTargetSize { /// at a time, between a `begin*` and `endEncoder`; the op methods are called while /// the matching encoder is open, as the host's walk expects (`decode::cmdbuf`). /// -/// The message is written once, where it is posted from: a buffer of the builder's own while -/// it fits its queue's ring, else, once it outgrows the ring, a block of the queue's region -/// pool (setMessageBlocks), where it grows by doubling and from which the host reads it with no -/// copy of the guest's. Each op takes its whole length at once (a pointer bump) and is stored -/// with fixed-size copies. Room before the header takes the SURFACE_USE ops a commit puts -/// first (prependSurfaceUses), so they move nothing. +/// The message is built in a buffer of the builder's own, write-back memory, and posted from +/// there on its queue's ring where it fits, else copied once, whole, into a block of the queue's +/// region pool (setMessageBlocks), which the ring names. It is not built in the block: the +/// block is write-combined where the kext maps it so, and on an AMD host, which applies the +/// guest's memory type, a write-combined store still pending stalls the thread's next locked +/// instruction until it drains, about 90 ns: measured with encode_probe on a 26.7.2 guest of a +/// Ryzen host (RTX 3090), a message built in its block cost setRenderPipelineState 108 ns a call +/// and a setVertexBuffer between a CFRetain and a CFRelease 103 ns, against 21.6 and 17.1 ns +/// built in the builder's buffer; and a block is read back as it grows, uncached. Each op takes +/// its whole length at once (a pointer bump) and is stored with fixed-size copies. Room before +/// the header takes the SURFACE_USE ops a commit puts first (prependSurfaceUses), so they move +/// nothing. /// /// A segment (SegmentOf) is a stream of ops alone, with no header: a parallel render pass's /// sub-encoder writes one of its own, on its own thread, and the pass joins them into its @@ -147,14 +153,15 @@ public: RgfxEncoder(const RgfxEncoder &) = delete; RgfxEncoder &operator=(const RgfxEncoder &) = delete; - /// Where the message moves once it no longer fits the ring: `blocks`, taking a block of at - /// least `hint` bytes first (the queue's guess of the message's size). A message starts in - /// a buffer of the builder's own whatever the guess, so one that fits the ring rides it; it - /// is copied once, when it outgrows the ring, at most the ring's half. + /// Where the message is copied at the commit where it does not fit the ring: a block of + /// `blocks`. The builder's buffer grows to `hint` bytes (the queue's guess of the message's + /// size) as the message outgrows the ring, so a large one is not copied at each doubling; it + /// starts no larger than the ring's half whatever the guess, so one that fits the ring rides + /// it. void setMessageBlocks(std::shared_ptr blocks, uint64_t hint) { m_blocks = std::move(blocks); - m_blockHint = hint; + m_sizeHint = hint; } // --- framing -------------------------------------------------------------- @@ -526,8 +533,8 @@ public: /// Sets `op_bytes` and posts the command buffer, waiting for room /// (RgfxRingWriter::post, `whileWaiting` called as it waits): on the ring where the message - /// fits it (fitsRing()), else as a COMMAND_BUFFER_IN_REGION naming its block, the one it was - /// built in, or one taken now from setMessageBlocks's pool, into which it is copied. The + /// fits it (fitsRing()), else as a COMMAND_BUFFER_IN_REGION naming a block taken now from + /// setMessageBlocks's pool, into which it is copied, the message from the block's start. The /// block must stay the process's until the buffer completes: it goes to `*held` (when not /// null) before the message is posted, whether or not the post succeeds, and its holder /// gives it back to the pool then; else the builder holds it until it goes. Returns whether the message was posted: false for one no block could be had for, @@ -550,7 +557,8 @@ public: return static_cast(m_end - m_ops) + RGFX_COMMAND_BUFFER_OPS_OFFSET + m_prefix; } - /// Whether the message is being built in a block of the region pool (setMessageBlocks). + /// Whether the builder holds the block of the region pool its finished message was copied + /// into (finish, with no holder given). bool inBlock() const { return m_inBlock; } /// The op-stream bytes appended so far (the message size less the header). @@ -730,14 +738,9 @@ private: else if (tail != 0) std::memcpy(at + RGFX_OP_BODY_OFFSET + head_n, elems, tail); } - // Makes room for `n` more bytes: a larger buffer of the builder's own, or a block of the - // region pool once the message outgrows the ring, its bytes so far copied there once. + // Makes room for `n` more bytes: a larger buffer of the builder's own, the bytes so far + // moved there. void grow(size_t n); - // Moves the bytes so far to a block of at least `size` bytes; false, nothing moved, where - // none was had. - bool moveToBlock(size_t size); - // Moves the bytes so far to a buffer of the builder's own of `size` bytes. - void moveToHeap(size_t size); // Gives back the block the builder holds, if any. void giveBackBlock(); // A video decode op of `tag`: its header, the `n` bytes of its body at `body`, then the @@ -758,10 +761,11 @@ private: RgfxRingWriter *m_ring; // null for a segment RgfxCommandBuffer m_head; - // The storage: a buffer of the builder's own (malloc) or a region block (m_inBlock), from - // m_store, m_end the end; the op stream from m_ops (kHeadroom and the header before it, - // none for a segment) to m_cur. The surface uses and the surface order put first lie in the - // m_prefix bytes before m_ops (prependRoom). + // The storage: a buffer of the builder's own (malloc), or after finish the region block the + // message was copied into (m_inBlock), from m_store, m_end the end; the op stream from m_ops + // (kHeadroom and the header before it in the builder's buffer, the header alone in the + // block, none for a segment) to m_cur. The surface uses and the surface order put first lie + // in the m_prefix bytes before m_ops (prependRoom). uint8_t *m_store = nullptr; uint8_t *m_ops = nullptr; uint8_t *m_cur = nullptr; @@ -770,7 +774,7 @@ private: bool m_inBlock = false; RgfxMessageBlock m_block = {}; std::shared_ptr m_blocks; - uint64_t m_blockHint = 0; + uint64_t m_sizeHint = 0; uint32_t m_renderStateSet = 0; uint64_t m_keepStamp; std::vector> m_surfaceWrites; diff --git a/guest/bundle/src/RgfxUploads.h b/guest/bundle/src/RgfxUploads.h index 82a32c229..cf7e7224a 100644 --- a/guest/bundle/src/RgfxUploads.h +++ b/guest/bundle/src/RgfxUploads.h @@ -91,9 +91,9 @@ private: using RgfxBodyBlock = RgfxMessageBlock; /// A queue's blocks for the messages of its command buffers too large for its ring: one taken -/// as the message outgrows the ring (RgfxEncoder::setMessageBlocks), or at the commit, given -/// back at the completion (the host read the message out of it before it ran the buffer), or as -/// a buffer no completion comes for goes, and reused by a later such buffer, so the block stays +/// at the commit, the message copied into it (RgfxEncoder::finish), given back at the completion +/// (the host read the message out of it before it ran the buffer), or as a buffer no completion +/// comes for goes, and reused by a later such buffer, so the block stays /// the process's, and in its window, with no kext call per buffer. A block is a power of two of /// at least kGranule bytes. The pool keeps every block given back, as the upload pool keeps its /// chunks, and a take reuses the smallest free one that holds the message: so of each size it diff --git a/guest/bundle/tests/queue_tests.mm b/guest/bundle/tests/queue_tests.mm index ea38542f8..2f6777989 100644 --- a/guest/bundle/tests/queue_tests.mm +++ b/guest/bundle/tests/queue_tests.mm @@ -1686,10 +1686,11 @@ void test_no_copy_write_backs_land_at_the_take() } // A command buffer let go with no completion gives back the region block its message lies in, as -// its completion does: one encoded past what its queue's ring takes and never committed, and one -// posted out of line on a queue whose completion ring nothing reads. Buffer after buffer reuse -// one block, and the queue's going gives it back to the region. (A buffer let go so used to keep -// its block, and the region lost one a buffer.) +// its completion does: one posted out of line on a queue whose completion ring nothing reads. +// Buffer after buffer reuse one block, and the queue's going gives it back to the region; one +// encoded past what its queue's ring takes and never committed takes none, its message copied +// into a block only at the commit. (A buffer let go so used to keep its block, and the region +// lost one a buffer.) void test_buffers_let_go_give_their_blocks_back() { std::vector mem(RGFX_ALLOCATIONS_OFFSET + 0x400000, 0); @@ -1719,7 +1720,7 @@ void test_buffers_let_go_give_their_blocks_back() (void)encode(); } } - CHECK(blocks.made <= 1); + CHECK(blocks.made == 0); for (int i = 0; i < n; i++) { @autoreleasepool { id cb = encode(); diff --git a/guest/bundle/tests/serializer_tests.cpp b/guest/bundle/tests/serializer_tests.cpp index 11ba561e0..f3f21feac 100644 --- a/guest/bundle/tests/serializer_tests.cpp +++ b/guest/bundle/tests/serializer_tests.cpp @@ -1682,11 +1682,12 @@ struct TestBlocks final : RgfxMessageBlocks { void giveBack(const RgfxMessageBlock &block) override { given.push_back(block); } }; -// A command buffer's message is built where it is posted from: on the ring while it fits half of -// it, else in a block, which it moves to once as it outgrows the ring and grows from by doubling, -// and which the COMMAND_BUFFER_IN_REGION names, the whole COMMAND_BUFFER in it; the block goes to -// whoever holds the posted message, the ones it outgrew back to the pool. The surface uses a -// commit puts first lead the op stream, in the order put, before every op, however many. +// A command buffer's message is built in the builder's own buffer and posted from it on the ring +// while it fits half of it, else copied at the commit into one block, from its start, which the +// COMMAND_BUFFER_IN_REGION names, the whole COMMAND_BUFFER in it; the block goes to whoever holds +// the posted message. The buffer grows to the queue's guess as the message outgrows the ring. +// The surface uses a commit puts first lead the op stream, in the order put, before every op, +// however many. void test_command_buffer_storage() { TestRing ring(0x1000); // up to 2 KiB a message on the ring @@ -1748,35 +1749,43 @@ void test_command_buffer_storage() CHECK(blocks->taken.empty()); } - // Past the ring: built in a block from the op that outgrows it, grown block to block, the - // outgrown ones back to the pool; more uses than the room before the header move the ops. + // Past the ring: built in the builder's buffer, which grows to the guess at the op that + // outgrows the ring and doubles past it, with no block taken; more uses than the room before + // the header move the ops; the commit copies the message into one block, from its start. { RgfxEncoder enc(writer, 1, 3, 0x100); - enc.setMessageBlocks(blocks, 0); + enc.setMessageBlocks(blocks, 0x10000); enc.beginBlitPass(); int fills = 0; - while (!enc.inBlock()) { + auto fill = [&enc, &fills] { enc.blitFillBuffer(static_cast(fills), 0, 4, 1); fills++; - } - CHECK(blocks->taken.size() == 1 && fills > 2048 / 48 && fills < 4096 / 32); - for (; fills < 5000; fills++) // 5000 fills of 40 bytes: 200 KB, past one 64 KiB block - enc.blitFillBuffer(static_cast(fills), 0, 4, 1); + }; + while (enc.fitsRing()) + fill(); + CHECK(fills > 2048 / 48 && fills < 4096 / 32); + // Its first growth past the ring takes the guess at once. + const size_t fitted = enc.capacity(); + while (enc.capacity() == fitted) + fill(); + CHECK(fitted < 0x10000 && enc.capacity() >= 0x10000); + while (fills < 5000) // 5000 fills of 40 bytes: 200 KB, past the 64 KiB guess + fill(); enc.endEncoder(); - CHECK(blocks->taken.size() == 3 && blocks->given.size() == 2); + CHECK(blocks->taken.empty() && !enc.inBlock()); std::vector u = uses(100, 1000); enc.prependSurfaceUses(u.data(), u.size()); uint64_t seqno = 0; RgfxMessageBlock held = {}; CHECK(enc.finish(&seqno, {}, {}, &held)); - CHECK(held.ptr == blocks->taken.back().ptr && blocks->given.size() == 2); + CHECK(blocks->taken.size() == 1 && held.ptr == blocks->taken.back().ptr && + blocks->given.empty() && !enc.inBlock()); RgfxMsgHeader h = {}; std::vector bytes; CHECK(ring.next(&h, &bytes) && h.type == RGFX_CMD_COMMAND_BUFFER_IN_REGION); RgfxCommandBufferInRegion ref = {}; std::memcpy(&ref, bytes.data(), sizeof(ref)); - CHECK(ref.region_offset >= held.offset && ref.region_offset % 8 == 0 && - ref.region_offset + ref.byte_length <= held.offset + held.size); + CHECK(ref.region_offset == held.offset && ref.byte_length <= held.size); const uint8_t *message = blocks->mem.data() + ref.region_offset; RgfxCommandBuffer cb = {}; std::memcpy(&cb, message, sizeof(cb)); @@ -1805,9 +1814,9 @@ void test_command_buffer_storage() for (int i = 0; i < 200; i++) enc.blitFillBuffer(9, 0, 4, 1); enc.endEncoder(); - CHECK(!enc.inBlock() && enc.messageSize() > 2048); + CHECK(!enc.fitsRing() && enc.messageSize() > 2048); RgfxMessageBlock held = {}; - CHECK(!enc.finish(nullptr, {}, {}, &held) && held.ptr == nullptr); + CHECK(!enc.finish(nullptr, {}, {}, &held) && held.ptr == nullptr && !enc.inBlock()); RgfxMsgHeader h = {}; std::vector bytes; CHECK(!ring.next(&h, &bytes)); diff --git a/guest/bundle/tests/shell_tests.mm b/guest/bundle/tests/shell_tests.mm index d7ab57848..651dff599 100644 --- a/guest/bundle/tests/shell_tests.mm +++ b/guest/bundle/tests/shell_tests.mm @@ -10853,9 +10853,9 @@ void test_command_buffer_out_of_line() CHECK(h.size == sizeof(RgfxCommandBufferInRegion)); RgfxCommandBufferInRegion ref = {}; std::memcpy(&ref, bytes.data(), sizeof(ref)); - // Built in the block once it outgrew the ring, after the room a commit's surface uses take. - CHECK(blocks.allocated.size() == 1 && ref.region_offset > blocks.allocated[0] && - ref.region_offset + ref.byte_length <= blocks.allocated[0] + RgfxBodyPool::kGranule); + // Copied into the block at the commit, from its start. + CHECK(blocks.allocated.size() == 1 && ref.region_offset == blocks.allocated[0] && + ref.byte_length <= RgfxBodyPool::kGranule); CHECK(ref.byte_length > 2048 && ref.byte_length % 8 == 0 && ref.region_offset % 8 == 0); // The block holds the whole message: a COMMAND_BUFFER of that length, seqno 0, its ops.