Runtime: a two-copy buffer's rebind makes a new host copy; a texture leg; the docs

A rebind of a Managed no-copy buffer with a device copy makes a new host copy
of the new pages as the making does (an import made as HostCopy, never a
copied.rs copy, or the pages alone), in place of the old, which goes once
nothing holds it, and copies the pages in whole: a rebind whose import the
gate refuses no longer stacks a copied host buffer under the device copy.

Tests: a texture over a two-copy buffer follows its device copy (its GPU
reads after the making, did_modify_range and replace_region, and its
synchronize_resource).

Docs: the runtime's guide (the memory model, host memory without a copy,
host_backing, the recovery), docs/API.md (the two-copy paragraph beside the
Managed device-copy textures, which now reach only buffers that lie in their
pages, and device-memory-overflow), HOWTO (copied host buffers: a two-copy
buffer is never one; did_modify_range is the contract).
This commit is contained in:
Anees Iqbal committed 2026-11-11 11:22:53 -08:00
1 parent 26c7d527b0
commit f0cdff884d
6 files changed
+194 -45

No files matched your search

+30 -7
View File
@@ -358,13 +358,16 @@ after it, and 0 of 80 with the device dropped first
- **Storage modes** keep Metal's meaning. `DeviceProperties::has_unified_memory` answers from the
device type: yes for an integrated GPU or a CPU implementation, no for a discrete GPU. Without
unified memory a `Managed` buffer has two copies, as on a Mac with a discrete GPU
(`did_modify_range` and a blit's `synchronize_resource` move the bytes), and a `Shared` resource
lies in host-cached system memory (announced once, `shared-in-system-memory`).
(`did_modify_range` and a blit's `synchronize_resource` move the bytes), a `Managed` no-copy
buffer's included (its CPU copy the caller's pages; **Host memory without a copy**, below), and
a `Shared` resource lies in host-cached system memory (announced once,
`shared-in-system-memory`).
- **Past device-local memory.** Where no device-local memory type a `Private` buffer or heap, a
texture's image or (without unified memory) a `Managed` buffer's own bytes takes has room, it
lies in system memory, as Metal makes such resources past a discrete GPU's memory rather than refusing
them (announced once, `device-memory-overflow`; counted in
`WorkCounts::device_memory_overflows`). Where the device lists
`WorkCounts::device_memory_overflows`); a `Managed` no-copy buffer then lies in the caller's
pages, as a `Shared` one does (`WorkCounts::managed_device_copies_in_place`). Where the device lists
`VK_EXT_pageable_device_local_memory`, the runtime enables it and the driver may page memory out
to make room instead. A resource Metal itself refuses (longer than `max_buffer_length`, past a
texture's limits) is refused as before.
@@ -421,6 +424,21 @@ after it, and 0 of 80 with the device dropped first
readable (a dma-buf's mapping among them); over pages not mapped readable it is refused. A
rebind's textures follow it onto the copy. A buffer over exactly the bytes a live copy covers
lies in that copy, as one over a live import's bytes lies in that import.
Without unified memory a `Managed` no-copy buffer is two copies instead
(`HostBacking::DeviceCopy`): the GPU's in device-local memory of the runtime's own, which every
command reads and writes, and the caller's pages, which `contents` answers. The pages are
copied in as the buffer is made, by `did_modify_range` (its range) and by a rebind (whole),
before any command of a command buffer committed after the call; a CPU write no
`did_modify_range` names is not seen by the GPU, as on a Mac with a discrete GPU. A blit's
`synchronize_resource` copies the GPU's copy out to the pages in its command buffer's order.
The copies run from an import of the pages where the device makes one, else (the gate refused
it, the device refused the pointer) through staging buffers held until their work completed,
at most 256 MiB staged ahead (`WorkCounts::managed_staging_bytes`): never through a copy of the
pages as well. Over pages the process maps read-only the GPU's writes are dropped: nothing is
copied out, and the pages are copied in again at the completion of each command buffer that
used the buffer (`managed_writes_undone`). A detach keeps the GPU's copy, which commands go on
reading and writing; `contents` answers `None` until a rebind. The device-local memory it holds
is counted in `managed_device_copy_bytes`.
`CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a
program knows when it may take memory away. The pages under a no-copy object are unmapped only
after the object goes and its keep-alive is dropped (or, given none, its deallocator ran), never
@@ -451,8 +469,10 @@ after it, and 0 of 80 with the device dropped first
whose check did not
pass), where the device's linear images cannot hold Metal's layout, and where the rows lie with
bytes between them (but over a buffer whose maker declared them unobserved,
`BufferDescriptor::padding_unobserved`, below). On a discrete GPU, a `Managed` texture
over a no-copy buffer's bytes (not an IOSurface plane's) that only samples or reads, whose
`BufferDescriptor::padding_unobserved`, below). A texture over a two-copy `Managed` no-copy
buffer's bytes is over the GPU's copy, as over a `Managed` buffer of the runtime's own. On a
discrete GPU, a `Managed` texture over the bytes of a no-copy buffer that lies in its pages
(not an IOSurface plane's) that only samples or reads, whose
policy takes the image in place, over memory that carries a log of its writes
(`HostMemory::with_dirty_pages`), tracked and laid out as one copy, is instead such a copy in
the device's memory, announced nowhere, whatever the check answered: the GPU's copy of the two
@@ -594,7 +614,8 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
them.
- `Buffer::host_backing` (with `HostBacking`): what the GPU uses for a no-copy buffer's bytes now,
or a no-copy heap's buffer's: the caller's pages, imported by their pointer, as dma-bufs or in a
guest RAM's chunk, or a copy of them (`copied-host-pages`), which Metal never makes; a rebind
guest RAM's chunk, a copy of them (`copied-host-pages`), which Metal never makes, or, for a
`Managed` one without unified memory, a copy in device-local memory (`DeviceCopy`); a rebind
may change it ([HOWTO](../../docs/HOWTO.md#copied-host-buffers)).
- `BufferDescriptor::padding_unobserved` (`with_padding_unobserved`): the maker of a buffer of
the runtime's own memory declares that nothing reads the bytes between a texture's rows over it
@@ -772,7 +793,9 @@ meanwhile wait for it.
of host pages costs its submissions nothing and that textures over such pages take in place
what they take over the device's own memory, the blocks of pages the `Shared` and `Managed`
(unified memory) buffers lie in, imported again on the new `VkDevice`. A no-copy buffer is
made again over the same pages, so it keeps its bytes and its pointer; its import gate, run
made again over the same pages, so it keeps its bytes and its pointer (a two-copy `Managed` one
makes its GPU copy again and copies the pages in: what the GPU wrote and no synchronize copied
out is lost, as a `Private` buffer's contents are); its import gate, run
resolver and dma-buf source are asked again, on the thread that recovers, and must not call
into the device. Its deallocator runs at its release once no `VkDevice` imports its pages. A
`Private` buffer's contents are lost: it reads zero.
@@ -965,7 +965,9 @@ degradations! {
/// device-local memory type the resource takes had room for it, and it takes a type that
/// is not device-local (`memory.rs`'s `overflow_candidates`), as Metal makes such a
/// resource past a discrete GPU's memory rather than refuse it. Each such placement is
/// counted (`WorkCounts::device_memory_overflows`). A driver may instead page device-local
/// counted (`WorkCounts::device_memory_overflows`). A `Managed` no-copy buffer there,
/// whose GPU copy found no room in device-local memory, lies in the caller's pages as a
/// `Shared` one does (`managed_copy.rs`, `WorkCounts::managed_device_copies_in_place`). A driver may instead page device-local
/// memory out to make room rather than fail the allocation
/// (`VK_EXT_pageable_device_local_memory`, enabled where the device lists it with its
/// feature); what it pages, it places, and nothing overflows.
+18 -24
View File
@@ -48,8 +48,9 @@
//! `Shared` one does (`read_only_view.rs`, `copied.rs`).
//! - **Rebind and detach** (`rebind.rs`, `detach.rs`) are the host copy's: a detach lets go of
//! it, as a no-copy buffer's lets go of its pages, and keeps the device copy, which the GPU
//! reads and writes on; a rebind gives it the new pages, imported or not as at the making, and
//! copies them in whole. The import's own rebind and detach serve an import's.
//! reads and writes on; a rebind makes a new host copy of the new pages, as at the making (so
//! never a copy of them either), and copies them in whole. An import's detach is its own, as a
//! no-copy buffer's.
//! - **Memory.** The device copy holds the buffer's bytes in device-local memory for its life
//! (`WorkCounts::managed_device_copy_bytes`); staging buffers live only until the submission
//! or command buffer that uses them completed (`WorkCounts::managed_staging_bytes`). Where no
@@ -421,9 +422,10 @@ impl CallerCopy {
}
}
/// `rebind_bytes_no_copy` of `buffer`: the host copy's pages replaced by `memory`, an
/// import's by its own rebind, pages no import maps by new ones made as the buffer's first
/// were; then the new pages copied in whole.
/// `rebind_bytes_no_copy` of `buffer`: a new host copy of `memory`, made as the buffer's
/// first was (an import, never a copy of the pages, or the pages alone), in place of the old,
/// which goes once no copy or command holds it, its deallocator then; then the new pages
/// copied in whole.
///
/// # Safety
///
@@ -436,25 +438,17 @@ impl CallerCopy {
keep_alive: Option<super::host_memory::KeepAlive>,
) -> Result<(), Error> {
const CALL: &str = "rebind_bytes_no_copy";
match self.side() {
// SAFETY: the caller's contract.
Side::Import(import) => unsafe {
import.rebind_bytes_no_copy(memory, deallocator, keep_alive)?
},
Side::Pages(..) => {
let device = buffer.device();
let release = super::host_memory::HostRelease::new(deallocator, keep_alive);
let parts = memory.into_parts();
let release = release.of(parts.pointer, buffer.length());
let made = (CALL, buffer.length(), buffer.resource_options());
// SAFETY: the caller's contract.
let side = unsafe { device.caller_side(made, parts, release)? };
// The old pages go once no copy holds them: their deallocator in the call, where
// none does, as Metal runs it at the replace.
let old = std::mem::replace(&mut *lock(&self.side), side);
drop(old);
}
}
let device = buffer.device();
let release = super::host_memory::HostRelease::new(deallocator, keep_alive);
let parts = memory.into_parts();
let release = release.of(parts.pointer, buffer.length());
let made = (CALL, buffer.length(), buffer.resource_options());
// SAFETY: the caller's contract.
let side = unsafe { device.caller_side(made, parts, release)? };
// The old host copy goes once nothing holds it, after the lock: its deallocator in the
// call where nothing does, as Metal runs it at the replace.
let old = std::mem::replace(&mut *lock(&self.side), side);
drop(old);
self.copy_in(buffer, 0..self.reach, true)
}
}
@@ -19,6 +19,10 @@
//! - **Read-only pages** (a rebind over pages the process maps read-only): the GPU's writes are
//! dropped. A synchronize writes nothing to the pages, and the next command buffer reads the
//! pages' bytes, not the GPU's writes.
//! - **Textures** over the buffer's bytes follow the device copy: their GPU reads take what was
//! copied in, and a `synchronize_resource` of one copies the GPU's writes out to the pages.
//! - **Recovery** carries the buffer: its host copy made again over the same pages, its device
//! copy made on the new `VkDevice` and the pages copied in.
//! - **Elsewhere, one copy.** A `Shared` no-copy buffer, and a `Managed` one on a device with
//! unified memory, lie in their pages.
//!
@@ -29,10 +33,11 @@
use super::blit_holds::{device, Scratch, WAIT};
use super::host_ram_device::gate;
use crate::{
BlitCommandEncoder, Buffer, CommandBufferStatus, CommandQueue, CpuCacheMode, Deallocator,
Device, HazardTrackingMode, HostBacking, HostMemory, ImportRequest, ResourceOptions,
ResourceRef, StorageMode, WorkCounts,
BlitCommandEncoder, BlitOption, Buffer, CommandBufferStatus, CommandQueue, CpuCacheMode,
Deallocator, Device, HazardTrackingMode, HostBacking, HostMemory, ImportRequest, Origin,
Region, ResourceOptions, ResourceRef, Size, StorageMode, TextureDescriptor, WorkCounts,
};
use metal2vulkan::metal::PixelFormat;
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
@@ -649,3 +654,92 @@ fn a_recovery_carries_a_two_copy_buffer_with_an_import() {
fn a_recovery_carries_a_two_copy_buffer_over_pages_no_import_maps() {
recovery(Route::Pages);
}
/// The side of the texture leg's `RGBA8Unorm` texture: its rows tight, 256 bytes each.
const SIDE: u64 = 64;
/// A texture over a two-copy buffer's bytes follows the device copy: its GPU reads take the bytes
/// copied in (at the making, by `did_modify_range`, by its own `replace_region`), and a
/// `synchronize_resource` of it copies the GPU's writes out to the pages.
fn texture(route: Route) {
let texels = SIDE * SIDE * 4;
let pages = Pages::new(BYTES);
pages.write_pattern();
let scratch = Scratch::new("managed-texture");
let Some(device) = two_copy_device(&scratch, "texture", route) else {
return;
};
let queue = device.new_command_queue().unwrap();
let ran = Ran::default();
let buffer = no_copy(&device, &pages, route, managed(), &ran);
let mut descriptor = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, SIDE, SIDE, false);
descriptor.resource_options = managed();
let texture = buffer.new_texture(&descriptor, 0, SIDE * 4).unwrap();
// The texture's texels as the GPU reads them.
let gpu_texels = || {
let target = device
.new_buffer(texels, ResourceOptions::shared())
.unwrap();
blit(&queue, |blit| {
blit.copy_from_texture_to_buffer(
&texture,
0,
0,
Origin::new(0, 0, 0),
Size::new(SIDE, SIDE, 1),
&target,
0,
SIDE * 4,
texels,
BlitOption::None,
)
.unwrap()
});
let contents = target.contents().unwrap();
// SAFETY: the target's bytes, which no command writes now.
unsafe { std::slice::from_raw_parts(contents.as_ptr(), texels as usize) }.to_vec()
};
assert_eq!(gpu_texels(), pattern(BYTES)[..texels as usize]);
pages.write(0..texels, 0x33);
buffer.did_modify_range(0..texels).unwrap();
assert_eq!(gpu_texels(), vec![0x33; texels as usize], "{route:?}");
let row = vec![0x44; (SIDE * 4) as usize];
texture
.replace_region(Region::new_2d(0, 0, SIDE, 1), 0, 0, &row, SIDE * 4, 0)
.unwrap();
let seen = gpu_texels();
assert_eq!(seen[..row.len()], row, "{route:?}");
assert!(seen[row.len()..].iter().all(|&byte| byte == 0x33));
// The GPU's write reaches the pages at the texture's synchronize.
blit(&queue, |blit| {
blit.fill_buffer(&buffer, 0..texels, 0x55).unwrap();
blit.synchronize_resource(ResourceRef::Texture(&texture))
.unwrap();
});
assert_eq!(
pages.bytes()[..texels as usize],
vec![0x55; texels as usize]
);
let mut read_back = vec![0; texels as usize];
texture
.get_bytes(
&mut read_back,
SIDE * 4,
0,
Region::new_2d(0, 0, SIDE, SIDE),
0,
0,
)
.unwrap();
assert_eq!(read_back, vec![0x55; texels as usize]);
}
#[test]
fn a_texture_over_a_two_copy_buffer_through_an_import_follows_its_device_copy() {
texture(Route::Import);
}
#[test]
fn a_texture_over_a_two_copy_buffer_over_pages_no_import_maps_follows_its_device_copy() {
texture(Route::Pages);
}
+30 -10
View File
@@ -483,15 +483,33 @@ refused meanwhile (`NotImplemented(DetachedTexelAccess)`), as a one-level textur
`generate_mipmaps` leaves as it is or refuses has its first level copied and its later levels left
as they are (docs/FAST-PATHS.md, known gaps).
A texture of one level is `new_texture`'s, in place where that is.
On a discrete GPU, a `Managed` texture over a no-copy buffer's bytes (not an IOSurface plane's)
that only samples or reads, whose policy takes the image in place, over memory that carries a log
of its writes (`HostMemory::with_dirty_pages`), tracked, one slice laid out as one copy, is instead
a device copy (`WorkCounts::device_copy_textures`, whatever the check answered): the GPU's copy of
the two a `Managed` resource is on a Mac with a discrete GPU, a shadow whose copies in take only
the bands of rows the log reports changed (`dirty_copies_in_gated` and kin). Its notice is not
announced: it holds the bytes wherever a command reads it. A `Shared` texture and an IOSurface's
are the pages' alone there too, in place where the check passed, which the GPU reads across the
bus as a discrete Mac's GPU reads them.
On a discrete GPU (no unified memory), a `Managed` no-copy buffer is two copies, as Metal keeps a
`Managed` resource on a Mac with a discrete GPU (`HostBacking::DeviceCopy`): the GPU's own in
device-local memory, which every command reads and writes, at the buffer's `gpu_address`, and the
caller's pages, which `contents` answers. The pages reach the GPU's copy as the buffer is made,
at `did_modify_range` (its range) and at a rebind (whole), each before any command of a command
buffer committed after the call; a CPU write that no `did_modify_range` names is not seen by the
GPU. A blit encoder's `synchronize_resource` copies the GPU's copy out to the pages in its
command buffer's order, which the CPU sees once the command buffer completed. The copies run
from an import of the pages where the device makes one (never a copy of them), else through
staging buffers the runtime frees once their work completed, at most 256 MiB staged ahead
(`WorkCounts::managed_*`). A texture over the buffer's bytes is over the GPU's copy and follows
it, its `replace_region` copying in and its `synchronize_resource` copying out. Over pages the
process maps read-only, the GPU's writes are dropped: nothing is copied out, and the pages are
copied in again at the completion of each command buffer that used the buffer. A detach keeps
the GPU's copy. Where device-local memory has no room for the GPU's copy, the buffer lies in its
pages as a `Shared` one does (`device-memory-overflow`). A `Shared` no-copy buffer, and every
no-copy buffer on a device with unified memory, lies in the caller's pages, which the GPU of a
discrete device reads across the bus, as a discrete Mac's GPU reads them.
A `Managed` texture over a no-copy buffer's bytes that lie in its pages there (not an IOSurface
plane's) that only samples or reads, whose policy takes the image in place, over memory that
carries a log of its writes (`HostMemory::with_dirty_pages`), tracked, one slice laid out as one
copy, is instead a device copy (`WorkCounts::device_copy_textures`, whatever the check answered):
the GPU's copy of the two a `Managed` resource is on a Mac with a discrete GPU, a shadow whose
copies in take only the bands of rows the log reports changed (`dirty_copies_in_gated` and kin).
Its notice is not announced: it holds the bytes wherever a command reads it. A `Shared` texture
and an IOSurface's are the pages' alone there too, in place where the check passed, which the GPU
reads across the bus as a discrete Mac's GPU reads them.
A texture placed in a heap over dma-buf pages is an image over a dma-buf of its own pages, which its
first submission acquires from `VK_QUEUE_FAMILY_FOREIGN_EXT`; a linear image over a buffer of the
runtime's own memory starts `VK_IMAGE_LAYOUT_PREINITIALIZED`, and its move from there keeps its
@@ -2468,7 +2486,9 @@ bound.
unified memory, or a texture's image, of any storage mode, lies in system memory: no
device-local memory type the resource takes had room for it, so it takes one that is not
device-local, as Metal makes such a resource past a discrete GPU's memory rather than refuse it.
`WorkCounts::device_memory_overflows` counts each such placement. A driver that pages
`WorkCounts::device_memory_overflows` counts each such placement. A `Managed` no-copy buffer
there whose GPU copy found no room lies in the caller's pages, as a `Shared` one does
(`WorkCounts::managed_device_copies_in_place`). A driver that pages
device-local memory (`VK_EXT_pageable_device_local_memory`, which the runtime enables where
listed with its feature) may page memory out to make room instead, and then nothing overflows.
Cost: the GPU reads and writes it across the bus, at the bus's speed, for as long as it lives;
+16
View File
@@ -585,6 +585,22 @@ over the copy (its driver lays the linear image out at other pitches and makes n
`DRM_FORMAT_MOD_LINEAR` image at the texture's pitch that the pooled memory's check passed, or
either lies in memory of another type or alignment), or where the buffer's GPU writes are dropped and its bytes moved in their page.
A `Managed` no-copy buffer on a device without unified memory is never such a copy: it is two
copies, as on a Mac with a discrete GPU, the GPU's in device-local memory and the caller's pages
(`HostBacking::DeviceCopy`; the runtime's guide, **Host memory without a copy**), and it holds
the buffer's bytes of device-local memory for its life (`WorkCounts::managed_device_copy_bytes`).
Its pages are imported as above, the gate asked, as the transfers' source and target; where the
gate refuses, the device refuses the pointer or the import fails, they are reached through staging
buffers instead (`managed_staging_bytes`, at most 256 MiB staged ahead, none once their work
completed), no copy of them made and nothing compared at commit or completion. The GPU sees only
the CPU writes `did_modify_range` names, and the CPU sees the GPU's only through a blit's
`synchronize_resource`, as Metal's contract for `Managed` storage on such a Mac says, so a
consumer that wrote the pages without calling `did_modify_range` (relying on a log of their
writes) must call it. Pages the process maps read-only keep the GPU's writes out of them the same
way: the pages are copied in again at the completion of each command buffer that used the
buffer. A rebind whose import is not made, of a buffer whose first pages were imported, makes such
a copy of the new pages for the import (FAST-PATHS.md, known gaps).
### Guest RAM imported whole
A VMM whose device refuses views of guest pages made through dma-bufs (each import of scattered