🐎 Lay no-copy Managed buffers over the app's pages in place

A no-copy Managed buffer over writable app memory took a shadow: a range of
a slab as its CPU copy, synced with the app's memory at every commit that used
it and written back at every completion that might write it, and on a discrete
host a third copy, the platform's own Managed buffer, beside it.

Where the region has pages blocks it now lies over the app's own pages, as a
writable Shared one has since 2c09b2196: a BUFFER_OVER_PAGES whose buffer the
host makes Shared, so the memory is one copy on every host, as the Intel 630's
no-copy Managed buffer is (dgpu-oracle.md Q3; the AMD 5300M keeps two, and
Metal's contract for the mode allows either). The buffer still answers the
Managed options it was asked. Its didModifyRange:, and a blit's
synchronizeResource: or synchronizeTexture: of it or of a texture over it,
send the host nothing, as one copy has nothing to bring over.

What the guest sees: a GPU write to such a buffer shows in the app's memory as
the GPU makes it, not at its command buffer's completion, and a CPU write is
seen by the GPU's next read with no didModifyRange:, as on the Intel 630.
Read-only memory, and memory the kext or host makes no pages block of, keep
the shadow.
This commit is contained in:
Anees Iqbal committed 2026-11-05 21:59:33 -08:00
1 parent ac62d3d88a
commit e828db91bc
9 files changed
+165 -30

No files matched your search

+6 -3
View File
@@ -1762,9 +1762,12 @@ and sends each as a placement at that offset. The heap's `usedSize` and
process's lies over them in place (`BUFFER_OVER_HOST_MEMORY` at their offset).
Metal makes one over any range the process maps readable, at any alignment:
malloc'd, `vm_allocate`d, read-only, or a file mapping (measured on an M3 Max,
16 KiB and 4 KiB pages). Writable Shared memory the kext wires lies in place
(`PagesBlock`, `BUFFER_OVER_PAGES`). Over any other memory (read-only, a Managed
buffer's, or memory the kext or host makes no pages block of) the buffer lies
16 KiB and 4 KiB pages). Writable Shared or Managed memory the kext wires lies
in place (`PagesBlock`, `BUFFER_OVER_PAGES`). A Managed one is one copy on every
host, as the Intel UHD 630's no-copy Managed buffer is (dgpu-oracle.md Q3): the
host's buffer over the pages is a Shared one, and its `didModifyRange:` and a
blit's synchronize of it, or of a texture over it, send nothing. Over any other
memory (read-only, or memory the kext or host makes no pages block of) the buffer lies
over a range of a slab of its own options, as a device buffer of them does
("Shared and Managed buffers lie in slabs"): the process's own superpages where
the device takes them, so no app-sized copy lies in the region. `contents`
+3 -2
View File
@@ -231,8 +231,9 @@ Probes: `oracle_storage DEVICE shtex`, `lintex shared|managed`, `argenc shared|m
`didModifyRange:` of all of it (`RgfxTexture.mm`).
- **A no-copy Managed buffer** (`nocopy`, 11-03) is two copies on AMD: the GPU's copy holds zeros,
not the pages' bytes, until a `didModifyRange:`, and a CPU write with no call is never seen
(also 200 ms later). Ours is two copies on a discrete host too, the GPU's copy filled from the
pages at the create.
(also 200 ms later); Intel's is one copy. Ours is one copy, as Intel's, wherever the kext wires
the pages (`RgfxBuffer.mm`, bufferOverPagesOf), and two copies over read-only memory and where
it wires none, the GPU's copy filled from the pages at the create.
- **An argument encoder writing a Managed argument buffer** (`argenc managed`, 11-03):
`setBuffer:` and `setTexture:` reach the GPU's copy on AMD only at the app's
`didModifyRange:`; Intel is one copy. A Shared argument buffer's writes are seen at once on
+10 -4
View File
@@ -99,10 +99,11 @@ NS_ASSUME_NONNULL_BEGIN
/// The buffer `newBufferWithBytesNoCopy:length:options:deallocator:` makes over the caller's
/// `length` bytes at `pointer`, whose `contents` is `pointer`, with `deallocator` (may be nil)
/// called with them once the buffer is gone from the host. Bytes in `region` (a block of the
/// process's) the host sees in place. Shared bytes the process may write, where `region` has
/// pages blocks (RgfxRegion::acquirePages), the host sees in place too: the kext wires their
/// pages for the buffer's life, and the buffer's GPU address keeps the pointer's offset in its
/// page. Any others, and those the kext or the host makes no pages block of, get a range of a
/// process's) the host sees in place. Shared or Managed bytes the process may write, where
/// `region` has pages blocks (RgfxRegion::acquirePages), the host sees in place too: the kext
/// wires their pages for the buffer's life, the buffer's GPU address keeps the pointer's offset
/// in its page, and a Managed one is one copy (rgfxOneCopy). Read-only bytes, and those the kext
/// or the host makes no pages block of, get a range of a
/// slab of `slabs` as a device buffer of their options does (RgfxSlabs.hpp), the GPU's copy,
/// synced with them at the command buffers that use the buffer (RgfxMemoryShadow.hpp): the
/// process's own pages where the device takes them, the region's only where the kernel has none.
@@ -126,6 +127,11 @@ NS_ASSUME_NONNULL_BEGIN
/// The GPU's copy of app memory the buffer lies over (a no-copy buffer's outside the device
/// region), null for any other.
- (std::shared_ptr<RgfxMemoryShadow>)rgfxShadow;
/// Whether the buffer is a Managed one of one copy: a no-copy buffer over the app's own pages in
/// place, which the host's GPU uses as a Shared buffer's memory, so neither its didModifyRange:
/// nor a blit's synchronize of it, or of a texture over it, has anything to bring over.
- (BOOL)rgfxOneCopy;
#endif
/// Designated initialiser: wraps an already-created host buffer. `objId` and
+26 -8
View File
@@ -153,6 +153,10 @@ NSString *rgfxLinearTypeName(MTLTextureType type)
// a buffer over pages lies past it by its pointer's offset in its page; 0 for any other,
// whose pick is `_gpuAddress`.
uint64_t _addressPick;
// YES for a Managed no-copy buffer over the app's own pages in place (bufferOverPagesOf): one
// copy, the app's memory, which the host's GPU uses as a Shared buffer's, so neither
// didModifyRange: nor a synchronize has anything to bring over.
BOOL _oneCopy;
}
+ (instancetype)bufferWithLength:(NSUInteger)length
@@ -344,10 +348,10 @@ NSString *rgfxLinearTypeName(MTLTextureType type)
if (pointer != nullptr && !rgfxMappedReadable(pointer, length, &writable))
return nil;
// The app's own pages in place, where the kext wires them for the buffer and the host maps
// them: nothing copied or synced. Read-only and Managed memory, and memory the kext or the
// host makes no pages block of, takes a shadow in a slab below.
if (pointer != nullptr && writable && region->hasPagesBlocks() &&
(options & MTLResourceStorageModeMask) == MTLResourceStorageModeShared) {
// them: nothing copied or synced, a Managed buffer's one copy (bufferOverPagesOf). Read-only
// memory, and memory the kext or the host makes no pages block of, takes a shadow in a slab
// below.
if (pointer != nullptr && writable && region->hasPagesBlocks()) {
RgfxBuffer *inPlace = [RgfxBuffer bufferOverPagesOf:pointer
length:length
options:options
@@ -410,6 +414,11 @@ NSString *rgfxLinearTypeName(MTLTextureType type)
// A no-copy buffer over the app's own pages (bufferWithBytesNoCopy): a pages block of them, and a
// buffer over its view at the pointer's offset in its page, which keeps the block until the host
// has dropped the buffer. Nil where the kext gives no block, or the device never got the create.
// A Managed one is one copy, the app's memory, as the Intel 630's no-copy Managed buffer is (the
// GPU sees a CPU write with no didModifyRange:, and the CPU a GPU write with no synchronize;
// docs/graphics-kext/dgpu-oracle.md, Q3; the AMD 5300M's is two copies, which Metal's contract
// for the mode allows either way): the host's buffer over the pages is a Shared one, and the
// buffer answers the Managed options it was asked.
+ (instancetype)bufferOverPagesOf:(void *)pointer
length:(NSUInteger)length
options:(MTLResourceOptions)options
@@ -422,7 +431,10 @@ NSString *rgfxLinearTypeName(MTLTextureType type)
if (!block.ok)
return nil;
const uint64_t offset = reinterpret_cast<uintptr_t>(pointer) & (kRgfxGuestPage - 1);
RgfxCreated created = serializer->createBufferOverPages(length, static_cast<uint32_t>(options),
const bool managed = (options & MTLResourceStorageModeMask) == MTLResourceStorageModeManaged;
const MTLResourceOptions onHost =
managed ? (options & ~MTLResourceStorageModeMask) | MTLResourceStorageModeShared : options;
RgfxCreated created = serializer->createBufferOverPages(length, static_cast<uint32_t>(onHost),
block.offset, block.size, offset);
if (created.obj_id == 0 || serializer->refused(created)) {
region->release(block.offset); // no buffer lies over the block
@@ -446,10 +458,16 @@ NSString *rgfxLinearTypeName(MTLTextureType type)
if (buffer != nil) {
buffer->_ownsAddress = YES;
buffer->_addressPick = created.gpu_address;
buffer->_oneCopy = managed;
}
return buffer;
}
- (BOOL)rgfxOneCopy
{
return _oneCopy;
}
- (std::shared_ptr<RgfxMemoryShadow>)rgfxShadow
{
return _shadow;
@@ -607,9 +625,9 @@ RGFX_RESOURCE_SPI
// A Managed buffer's contents are its CPU copy, a region block: the host copies the range
// to the GPU's copy before any command buffer committed after this, on any queue
// (RGFX_CMD_BUFFER_DID_MODIFY_RANGE). A Shared or Private buffer has nothing to tell, as
// Metal does nothing for one.
if ([self storageMode] != MTLStorageModeManaged || _ownsContents || _serializer == nullptr ||
range.length == 0) {
// Metal does nothing for one, and neither has a Managed one of one copy (rgfxOneCopy).
if ([self storageMode] != MTLStorageModeManaged || _ownsContents || _oneCopy ||
_serializer == nullptr || range.length == 0) {
return;
}
// A no-copy buffer's CPU copy is the app's memory: the block takes its bytes first.
+19 -2
View File
@@ -311,6 +311,15 @@ void rgfxNoteIcbFlush(const RgfxIcbFlush &flush)
}
}
/// Whether `res` is a Managed buffer of one copy, or a texture over one (RgfxBuffer's
/// rgfxOneCopy), whose synchronize has nothing to bring over.
bool rgfxOfOneCopy(id<MTLResource> res)
{
if ([res isKindOfClass:[RgfxBuffer class]])
return [(RgfxBuffer *)res rgfxOneCopy];
return [res isKindOfClass:[RgfxTexture class]] && [(RgfxTexture *)res rgfxOverOneCopy];
}
/// The RGFX_RESOURCE_KIND_* of a Metal resource, for the resource-reference ops.
uint32_t rgfxResourceKind(id<MTLResource> res)
{
@@ -4469,13 +4478,21 @@ destinationBytesPerImage:(NSUInteger)destinationBytesPerImage
_enc->blitOptimizeIndirectCommandBuffer(rgfxNamed(_enc, indirectCommandBuffer), range.location,
range.length);
}
// A Managed buffer of one copy, or a texture over one, has nothing to bring over (RgfxBuffer's
// rgfxOneCopy): it is named as written, and nothing is sent.
- (void)synchronizeResource:(id<MTLResource>)resource
{
_enc->blitSynchronizeResource(rgfxWrites(_enc, resource), rgfxResourceKind(resource));
const uint64_t name = rgfxWrites(_enc, resource);
if (rgfxOfOneCopy(resource))
return;
_enc->blitSynchronizeResource(name, rgfxResourceKind(resource));
}
- (void)synchronizeTexture:(id<MTLTexture>)texture slice:(NSUInteger)slice level:(NSUInteger)level
{
_enc->blitSynchronizeTexture(rgfxWrites(_enc, texture), slice, level);
const uint64_t name = rgfxWrites(_enc, texture);
if (rgfxOfOneCopy(texture))
return;
_enc->blitSynchronizeTexture(name, slice, level);
}
// --- unsupported: the device answers NO for these features -----------------------
+2 -2
View File
@@ -1,8 +1,8 @@
/*
* RgfxMemoryShadow: the GPU's copy of app memory a no-copy buffer wraps
* (`newBufferWithBytesNoCopy:length:options:deallocator:` over memory outside the device
* region that the host does not use in place: read-only, a Managed buffer's, or memory the kext
* or the host makes no pages block of). The buffer lies over a range of a slab of its own
* region that the host does not use in place: read-only memory, or memory the kext or the host
* makes no pages block of). The buffer lies over a range of a slab of its own
* (RgfxSlabs.hpp, RgfxBuffer.h), the block here, and `contents` stays the app's pointer, as
* Metal's does.
*
+4
View File
@@ -121,6 +121,10 @@ NS_ASSUME_NONNULL_BEGIN
/// factory calls it on the texture it made; until then the texture answers Metal's defaults.
- (void)rgfxTakeDescriptor:(nullable MTLTextureDescriptor *)descriptor;
/// Whether the texture lies over a Managed buffer of one copy (RgfxBuffer's rgfxOneCopy), itself
/// or as a view of one that does: a synchronize of it has nothing to bring over.
- (BOOL)rgfxOverOneCopy;
@end
/// Ends the process, with Metal's words, at a descriptor Metal's texture descriptor validation
+6
View File
@@ -1031,6 +1031,12 @@ std::atomic<uint64_t> g_lastTextureNumber{0};
return _parent != nil ? _parent.buffer : _buffer;
}
- (BOOL)rgfxOverOneCopy
{
id<MTLBuffer> buffer = self.buffer;
return [buffer isKindOfClass:[RgfxBuffer class]] && [(RgfxBuffer *)buffer rgfxOneCopy];
}
// The bytes the texture takes: its buffer's, for one made over a buffer (measured on the M3 Max
// under macOS 27.0.1: a texture of four rows over buffers of 5000, 65536 and 200000 bytes
// answers 5000, 65536 and 212992, each buffer's allocatedSize); the size its Automatic heap
+89 -9
View File
@@ -7790,9 +7790,11 @@ void test_no_copy_buffers()
// (RgfxBuffer.h): the buffer lies over the app's own pages, no block or shadow of its own, its
// create a BUFFER_OVER_PAGES over the block the kext gave for exactly the app's bytes, at the
// pointer's offset in its page, which its GPU address keeps. Its block goes back once the host
// has dropped it, before the deallocator. Read-only memory, Managed storage, a null pointer and
// bytes in the region never ask for a block, and a block not given, or one the region does not
// hold, falls back to the shadow.
// has dropped it, before the deallocator. Writable Managed memory lies there too, one copy: the
// host's buffer a Shared one, the buffer still Managed, its didModifyRange: and a blit's
// synchronize of it, or of a texture over it, sending nothing, where a Managed buffer's shadow
// sends both. Read-only memory, a null pointer and bytes in the region never ask for a block, and
// a block not given, or one the region does not hold, falls back to the shadow.
void test_no_copy_buffers_in_place()
{
@autoreleasepool {
@@ -7872,10 +7874,87 @@ void test_no_copy_buffers_in_place()
serializer:&f.ser];
};
@autoreleasepool {
// Never asked: Managed storage, a null pointer, bytes in the region, read-only memory.
// Managed, writable: in place, one copy.
pages.asked.clear();
const MTLResourceOptions managedOptions =
MTLResourceStorageModeManaged | MTLResourceCPUCacheModeWriteCombined;
RgfxBuffer *managed = noCopy(p, 0x2000, managedOptions);
CHECK(managed != nil && [managed contents] == p && [managed rgfxShadow] == nullptr);
CHECK(managed.storageMode == MTLStorageModeManaged &&
managed.cpuCacheMode == MTLCPUCacheModeWriteCombined);
CHECK(pages.asked.size() == 1 && std::get<0>(pages.asked[0]) == p &&
std::get<2>(pages.asked[0]));
auto over = expectMessage<RgfxBufferOverPages>(f.control, RGFX_CMD_BUFFER_OVER_PAGES);
CHECK(over.obj_id == managed.rgfxObjId && over.length == 0x2000 && over.offset == 0x123);
CHECK((over.options & MTLResourceStorageModeMask) == MTLResourceStorageModeShared &&
(over.options & MTLResourceCPUCacheModeMask) == MTLResourceCPUCacheModeWriteCombined);
MTLTextureDescriptor *td =
[MTLTextureDescriptor texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm
width:16
height:16
mipmapped:NO];
td.storageMode = MTLStorageModeManaged;
td.usage = MTLTextureUsageShaderRead;
id<MTLTexture> overManaged = [managed newTextureWithDescriptor:td offset:0 bytesPerRow:256];
CHECK(overManaged != nil && overManaged.storageMode == MTLStorageModeManaged);
drainRing(f.control);
[managed didModifyRange:NSMakeRange(0, 0x100)];
uint32_t px[4] = {1, 2, 3, 4};
[overManaged replaceRegion:MTLRegionMake2D(0, 1, 4, 1) mipmapLevel:0 withBytes:px
bytesPerRow:16];
CHECK(std::memcmp(p + 256, px, sizeof px) == 0);
RgfxMsgHeader h = {};
std::vector<uint8_t> sent;
CHECK(!f.control.next(&h, &sent)); // no BUFFER_DID_MODIFY_RANGE: one copy
// Read-only Managed memory keeps its shadow, a Managed buffer of two copies, whose
// didModifyRange: and synchronize the host carries.
uint8_t *roManaged = reinterpret_cast<uint8_t *>(app) + 0x38000;
CHECK(vm_protect(mach_task_self(), reinterpret_cast<vm_address_t>(roManaged), 0x4000,
false, VM_PROT_READ) == KERN_SUCCESS);
RgfxBuffer *twoCopies = noCopy(roManaged, 0x1000, MTLResourceStorageModeManaged);
CHECK(twoCopies != nil && [twoCopies rgfxShadow] != nullptr && pages.asked.size() == 1);
drainRing(f.control);
[twoCopies didModifyRange:NSMakeRange(0, 0x10)];
auto told =
expectMessage<RgfxBufferDidModifyRange>(f.control, RGFX_CMD_BUFFER_DID_MODIFY_RANGE);
CHECK(told.obj_id == twoCopies.rgfxObjId && told.length == 0x10);
id<MTLCommandBuffer> cb = [f.queue commandBuffer];
id<MTLBlitCommandEncoder> blit = [cb blitCommandEncoder];
[blit synchronizeResource:managed];
[blit synchronizeResource:overManaged];
[blit synchronizeTexture:overManaged slice:0 level:0];
[blit synchronizeResource:twoCopies];
[blit endEncoding];
[cb commit];
CHECK(f.submit.next(&h, &sent) && h.type == RGFX_CMD_COMMAND_BUFFER);
RgfxCommandBuffer cbh = {};
std::memcpy(&cbh, sent.data(), sizeof(cbh));
OpWalk walk(sent.data() + RGFX_COMMAND_BUFFER_OPS_OFFSET, cbh.op_bytes);
std::vector<uint64_t> synced;
while (!walk.done()) {
uint16_t tag = 0;
uint32_t len = 0;
const uint8_t *body = nullptr;
size_t bodyLength = 0;
CHECK(walk.next(&tag, &len, &body, &bodyLength));
if (tag == RGFX_OP_BLIT_SYNCHRONIZE_RESOURCE) {
RgfxBlitOpSynchronizeResource m = {};
std::memcpy(&m, body, std::min(bodyLength, sizeof m));
synced.push_back(m.resource_obj_id);
}
CHECK(tag != RGFX_OP_BLIT_SYNCHRONIZE_TEXTURE);
}
CHECK(synced.size() == 1 && synced[0] == twoCopies.rgfxObjId);
RgfxCbComplete done = cbComplete(h.seqno, ((RgfxResource *)cb).rgfxObjId);
CHECK(f.completion.postFromHost(&done, sizeof(done)));
[cb waitUntilCompleted];
overManaged = nil;
drainRing(f.control);
}
drainRing(f.control);
@autoreleasepool {
// Never asked: a null pointer, bytes in the region, read-only memory.
pages.asked.clear();
RgfxBuffer *managed = noCopy(p, 0x1000, MTLResourceStorageModeManaged);
CHECK(managed != nil && [managed rgfxShadow] != nullptr);
RgfxBuffer *own = noCopy(nullptr, 0x1000, shared);
CHECK(own != nil && [own rgfxShadow] == nullptr);
RgfxRegion::Block inRegion = region.allocate(0x1000);
@@ -7909,7 +7988,7 @@ void test_no_copy_buffers_in_place()
// A no-copy buffer's GPU copy (its shadow) is a range of a slab of its options, as a device
// buffer's is (RgfxBuffer.h): with the process's superpages as the slabs' first source, the
// copies of read-only memory and of Managed buffers lie in them, seeded from the memory, eight 4 KiB
// copies of read-only memory, Shared and Managed, lie in them, seeded from the memory, eight 4 KiB
// copies a page apart in one heap over one pages block, and the region gives none of them a block
// of its own (each took one before: the region held every app-sized copy).
void test_no_copy_shadows_lie_in_slabs()
@@ -7960,7 +8039,7 @@ void test_no_copy_shadows_lie_in_slabs()
uint8_t *p = reinterpret_cast<uint8_t *>(app);
for (size_t i = 0; i < 0x10000; i++)
p[i] = static_cast<uint8_t>(i * 7 + 3);
CHECK(vm_protect(mach_task_self(), app, 0x8000, false, VM_PROT_READ) == KERN_SUCCESS);
CHECK(vm_protect(mach_task_self(), app, 0xa000, false, VM_PROT_READ) == KERN_SUCCESS);
auto noCopy = [&](void *ptr, NSUInteger length, MTLResourceOptions options) {
return [RgfxBuffer bufferWithBytesNoCopy:ptr
length:length
@@ -7991,7 +8070,8 @@ void test_no_copy_shadows_lie_in_slabs()
}
// A Managed one's CPU copy lies in a superpage of its own class, placed in its heap.
RgfxBuffer *managed = noCopy(p + 0x8000, 0x2000, MTLResourceStorageModeManaged);
CHECK(managed != nil && [managed rgfxShadow] != nullptr && [managed rgfxShadow]->writable());
CHECK(managed != nil && [managed rgfxShadow] != nullptr &&
![managed rgfxShadow]->writable());
CHECK(vm.held.size() == 2 && blocks.allocated.size() == 2);
auto mheap = expectMessage<RgfxHeapOverPages>(f.control, RGFX_CMD_HEAP_OVER_PAGES);
auto mat =