Compare commits

..
Author SHA1 Message Date
YXC0915 1a6d1626ca 📝 Record the Places texture-pool suspend baseline
The Places allocation patch changes the graphics memory layout. Give this Alpha build its own suspend compatibility family until recovery of older snapshots has been verified.
2026-12-03 01:02:03 +08:00
Xiaochi You 1ac525f616 Merge PR #2: Batch Vulkan draws and limit copied buffer sync
🐎 Batch Vulkan vertex draws and limit copied buffer sync to blit ranges
2026-12-03 00:01:49 +08:00
棠渚听潮 0824c15d61 🐎 Limit copied buffer sync to blit ranges 2026-12-02 19:33:13 +08:00
棠渚听潮 7e7b50364b 🐎 Encode Vulkan vertex draws in batches 2026-12-02 19:33:13 +08:00
YXC0915 9835066ce3 🐛 Update maintenance branch references [ci skip]
Keep automation and documentation aligned with the renamed branch.
The source pins and build steps stay the same.
2026-12-02 19:27:54 +08:00
YXC0915 8ae206e06a Use the organization QEMU fork for runtime builds 2026-12-02 18:59:09 +08:00
YXC0915 cf00aac721 🐛 Supersede unfinished Alpha builds on push
Cancel an older dispatcher and request the newest runtime build.
2026-12-02 02:05:39 +08:00
YXC0915 e76060b02c 🆕 Queue an Alpha for runtime branch pushes
Dispatch the default packaging workflow with the pushed runtime SHA.
Publish the verified build through the existing Alpha release path.
2026-12-02 01:58:33 +08:00
YXC0915 9d9be66a68 🐛 Pin the Win32 user NAT socket fix
Use the QEMU maintenance merge that removes Winsock fd_set truncation in Windows user networking.
2026-12-02 01:15:32 +08:00
YXC0915 c95335699c 🆕 Ask Reims-Go to confirm Windows VM close requests
Forward managed Windows closes to the desktop client. Keep the SDL question available when the desktop instance cannot take the request.
2026-12-01 12:04:24 +08:00
YXC0915 edd66dcc12 🐛 Pin the Win32 direct-write retry fix 2026-12-01 11:57:57 +08:00
YXC0915 ff284bc497 chore: bump vendor/qemu for fast Win32 mapped-ram suspend I/O
Updates vendor/qemu to yxc0915/qemu-reims-vgpu@4c4757156a with ascending zero-page partitioning, Win32 64 KiB NTFS sparse write coalescing, and Win32 direct-io support.
2026-12-01 11:40:59 +08:00
15 changed files with 1298 additions and 146 deletions

No files matched your search

@@ -0,0 +1,25 @@
name: Queue Runtime Alpha
on:
push:
branches: [intel-vm-suspend]
permissions:
actions: write
concurrency:
group: queue-runtime-alpha
cancel-in-progress: true
jobs:
alpha:
if: github.repository == 'reims-go/reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Queue Alpha for the pushed commit
env:
GH_TOKEN: ${{ github.token }}
run: |
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
-f upstream_commit="$GITHUB_SHA" -f publish=true -f supersede=true
+2 -2
View File
@@ -1,4 +1,4 @@
[submodule "vendor/qemu"]
path = vendor/qemu
url = https://github.com/yxc0915/qemu-reims-vgpu.git
branch = codex/intel-vm-suspend
url = https://github.com/reims-go/qemu-reims-vgpu.git
branch = intel-vm-suspend
+145
View File
@@ -4570,6 +4570,151 @@ mod tests {
(platform, device)
}
/// A draw batch records the original Metal calls in order, including each new buffer offset.
#[test]
fn on_vulkan_draw_batches_record_each_bind_and_draw() {
use crate::core::platform::Platform as _;
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _, WorkNames};
use crate::core::platform::descriptor::RenderPassDescriptor as _;
use crate::core::platform::device::GpuDevice as _;
use crate::core::platform::render::{RenderCmd, RenderEncoder as _, VertexDraw};
use crate::core::platform::resource::Library as _;
use crate::core::platform::values::{
ColorAttachmentDesc, ColorAttachmentSet, FullRenderPipelineDesc, TextureDesc,
};
use crate::core::raise::OnFault;
in_recording_child(
"recorder::tests::on_vulkan_draw_batches_record_each_bind_and_draw",
|streams| {
let run = || -> Result<(), &'static str> {
let (platform, device) = recording_device();
let on = OnFault::Return;
let function = |bytes: &[u8], name| {
let Ok(Ok(Some(library))) = device.new_library(bytes) else {
return Err("no library");
};
library
.new_function(on, name)
.ok()
.flatten()
.ok_or("no function")
};
let vertex = function(
include_bytes!("../../../tests/shaders/vert.metallib"),
"tri_vert",
)?;
let fragment = function(
include_bytes!("../../../tests/shaders/frag.metallib"),
"tri_frag",
)?;
let mut desc = FullRenderPipelineDesc::new(&vertex, Some(&fragment));
desc.colors = vec![(
0,
ColorAttachmentDesc {
pixel_format: 80,
..ColorAttachmentDesc::default()
},
)];
let Ok(Some(pipeline)) = device.new_render_pipeline_state_full(&desc) else {
return Err("no pipeline");
};
let Ok(Some(buffer)) = device.new_buffer_of_length(on, 256, 0) else {
return Err("no vertex buffer");
};
let Ok(Some(target)) = device.new_texture(
on,
&platform.texture_descriptor(&TextureDesc {
pixel_format: 80,
width: 4,
height: 4,
usage: 4,
..TextureDesc::default()
}),
) else {
return Err("no render target");
};
let queue = device.new_command_queue().ok_or("no queue")?;
let Ok(Some(cb)) = queue.command_buffer(on) else {
return Err("no command buffer");
};
cb.names_work(&std::sync::Arc::new(WorkNames::new(1)));
let pass = platform.render_pass_descriptor();
assert_eq!(
pass.set_color_attachment(
on,
0,
&ColorAttachmentSet {
texture: Some(Some(&target)),
load_action: Some(2),
store_action: Some(1),
..ColorAttachmentSet::default()
}
),
Ok(())
);
let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else {
return Err("no render encoder");
};
assert_eq!(
encoder.encode(
on,
RenderCmd::SetRenderPipelineState {
pipeline_state: Some(&pipeline),
}
),
Ok(())
);
let draw = VertexDraw {
buffer: Some(&buffer),
offset: 0,
index: 0,
primitive_type: 3,
vertex_start: 0,
vertex_count: 3,
};
let draws = [draw, VertexDraw { offset: 16, ..draw }];
assert_eq!(encoder.encode_draws(on, &draws), Ok(()));
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
let receiver = id_at(encoder.rec_ptr()).ok_or("no encoder stream id")?;
let buffer = id_at(buffer.rec_ptr()).ok_or("no buffer stream id")?;
let (calls, _) = recorded(streams, |calls| {
calls
.iter()
.any(|c| c.receiver == receiver && c.selector == "endEncoding")
});
let selectors_and_args: Vec<_> = calls
.iter()
.filter(|c| c.receiver == receiver)
.map(|c| (c.selector.as_str(), c.args.as_slice()))
.collect();
assert_eq!(selectors_and_args.len(), 6, "{calls:?}");
let bind =
|offset| [Value::Object(buffer), Value::Uint(offset), Value::Uint(0)];
let primitives = [Value::Uint(3), Value::Uint(0), Value::Uint(3)];
assert_eq!(
selectors_and_args[1..5],
[
("setVertexBuffer:offset:atIndex:", bind(0).as_slice()),
(
"drawPrimitives:vertexStart:vertexCount:",
primitives.as_slice()
),
("setVertexBuffer:offset:atIndex:", bind(16).as_slice()),
(
"drawPrimitives:vertexStart:vertexCount:",
primitives.as_slice()
),
]
);
Ok(())
};
assert_eq!(run(), Ok(()));
},
);
}
/// A stream starts with the device's making and then its identity, rt's `deviceName` and
/// `hasUnifiedMemory`, before any call on the device.
#[test]
+125 -61
View File
@@ -47,6 +47,7 @@
use std::ops::Range;
use metal2vulkan::metal::format;
use metal2vulkan_runtime as rt;
use crate::core::platform::Platform;
@@ -56,10 +57,11 @@ use crate::core::raise::{OnFault, RaiseResult};
use crate::core::sync::Mutex;
use super::command::{Kept, OpenMark};
use super::copied::Used;
use super::diag::Use;
use super::fault::{EncoderKind, EncoderNames, Naming, Operands};
use super::unbuilt::{RtRefusal, Unbuilt, refuse, refused_as, rt_refused_texture};
use super::{RtObj, RtPlatform, RtTexture};
use super::{RtBuffer, RtObj, RtPlatform, RtTexture};
/// `id<MTLBlitCommandEncoder>` on metal2vulkan-runtime.
pub struct RtBlitEncoder {
@@ -105,10 +107,9 @@ impl RtBlitEncoder {
/// Notes `cmd`'s textures in its command buffer's `kept`: its copies' as uses
/// ([`Kept::used`]), and a mipmap generation's and a synchronize's as tiled textures' uses
/// alone (`super::tiled`); and the copies its buffers and textures lie over
/// alone (`super::tiled`); and the copies these textures and synchronized buffers lie over
/// ([`super::copied::Used`]).
fn note_uses(&self, cmd: &BlitCmd<'_, RtPlatform>) {
self.note_copies(cmd);
let (from, into) = match *cmd {
BlitCmd::CopyBufferToTexture {
destination_texture,
@@ -146,6 +147,12 @@ impl RtBlitEncoder {
self.kept.copies().add(texture.copied(), true);
(None, None)
}
BlitCmd::SynchronizeResource {
resource: Some(ResourceRef::Buffer(buffer)),
} => {
self.kept.copies().buffer(buffer);
(None, None)
}
_ => (None, None),
};
if let Some(texture) = from {
@@ -155,47 +162,6 @@ impl RtBlitEncoder {
self.kept.used(texture, Use::BlittedInto);
}
}
/// Notes the copies `cmd`'s buffers lie over in its command buffer's `kept`
/// ([`super::copied::Used`]); its textures' are noted with their uses.
fn note_copies(&self, cmd: &BlitCmd<'_, RtPlatform>) {
if !super::copied::any() {
return;
}
let used = self.kept.copies();
match *cmd {
BlitCmd::CopyBufferToTexture {
source_buffer: buffer,
..
} => used.buffer_read(buffer),
BlitCmd::CopyTextureToBuffer {
destination_buffer: buffer,
..
}
| BlitCmd::FillBufferPattern4 { buffer, .. }
| BlitCmd::FillBuffer { buffer, .. }
| BlitCmd::SynchronizeResource {
resource: Some(ResourceRef::Buffer(buffer)),
} => used.buffer(buffer),
BlitCmd::CopyBufferToTextureOptions {
source_buffer: buffer,
..
} => buffer.iter().for_each(|b| used.buffer_read(b)),
BlitCmd::CopyTextureToBufferOptions {
destination_buffer: buffer,
..
} => buffer.iter().for_each(|b| used.buffer(b)),
BlitCmd::CopyBufferToBuffer {
source_buffer,
destination_buffer,
..
} => {
source_buffer.iter().for_each(|b| used.buffer_read(b));
destination_buffer.iter().for_each(|b| used.buffer(b));
}
_ => {}
}
}
}
/// Notes in `operands` what `cmd`, a command of an encoder of a command buffer of the host's own,
@@ -438,17 +404,24 @@ fn copy_texture(
/// ([`super::unbuilt::refusal_detail`]), and is counted with the command ([`report`]).
fn copy_bytes(
e: &mut rt::BlitCommandEncoder,
sel: &'static str,
(buffer, lies): (&rt::Buffer, rt::BufferLayout),
(sel, used): (&'static str, &Used),
(buffer, lies): (&RtBuffer, rt::BufferLayout),
size: [u32; 3],
(texture, place): (&RtTexture, rt::TexturePlace),
into: bool,
option: rt::BlitOption,
) -> Result<(), Stop> {
let copied = if into {
e.copy_from_buffer_with_options(buffer, lies, size, texture.rt(), place, option)
e.copy_from_buffer_with_options(buffer.rt(), lies, size, texture.rt(), place, option)
} else {
e.copy_from_texture_to_buffer_with_options(texture.rt(), place, size, buffer, lies, option)
e.copy_from_texture_to_buffer_with_options(
texture.rt(),
place,
size,
buffer.rt(),
lies,
option,
)
};
copied.map_err(|error| {
let (texture, buffer) = (Copied::of(texture, place), Copied::Buffer(lies));
@@ -465,7 +438,70 @@ fn copy_bytes(
};
super::unbuilt::refusal_detail(sel, &error, Some(&what));
Stop::Rt(error)
})
})?;
if buffer.copied().is_some() {
match buffer_image_ranges(texture.rt().descriptor(), size, lies, option) {
Some(ranges) => used.buffer_ranges(buffer, !into, ranges),
None => used.add(buffer.copied(), !into),
}
}
Ok(())
}
/// The buffer bytes of an accepted image copy, excluding padding between rows and images.
fn buffer_image_ranges(
desc: &rt::TextureDescriptor,
[width, mut height, mut depth]: [u32; 3],
layout: rt::BufferLayout,
option: rt::BlitOption,
) -> Option<impl Iterator<Item = Range<u64>>> {
if height == 0
&& matches!(
desc.texture_type,
rt::TextureType::Type1D | rt::TextureType::Type1DArray
)
{
height = 1;
}
if depth == 0 && desc.texture_type != rt::TextureType::Type3D {
depth = 1;
}
let format = desc.pixel_format;
let bytes = match (option, format) {
(rt::BlitOption::StencilFromDepthStencil, _) | (NONE, rt::PixelFormat::Stencil8) => 1,
(NONE | rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth16Unorm) => 2,
(NONE | rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth32Float)
| (rt::BlitOption::DepthFromDepthStencil, rt::PixelFormat::Depth32FloatStencil8) => 4,
(NONE, _) if format::aspects(format) == Some(metal2vulkan::vk::ImageAspectFlags::COLOR) => {
format::byte_format(format)?.block()?.size
}
_ => return None,
};
// At a compressed mip's edge, rt clips a whole block to the edge without changing the
// number of blocks transferred.
let [bw, bh] = format::block_extent(format).unwrap_or([1, 1]);
let row = u64::from(width.div_ceil(bw)) * u64::from(bytes);
let mut rows = u64::from(height.div_ceil(bh));
let mut images = if row == 0 || rows == 0 {
0
} else {
u64::from(depth)
};
let mut run = row;
if images > 0 && (rows == 1 || layout.bytes_per_row == row) {
run = row.checked_mul(rows)?;
rows = 1;
if images == 1 || layout.bytes_per_image == run {
run = run.checked_mul(images)?;
images = 1;
}
}
Some((0..images).flat_map(move |image| {
(0..rows).map(move |row| {
let start = layout.offset + image * layout.bytes_per_image + row * layout.bytes_per_row;
start..start + run
})
}))
}
/// What a copy of texels asked of rt, for the process's first line of each kind of rt's refusals
@@ -599,7 +635,11 @@ impl std::fmt::Display for CopyDetail {
}
/// Encodes `cmd` into `e`, rt's open encoder (the module's docs); `EndEncoding` is the caller's.
fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Result<(), Stop> {
fn encode(
e: &mut rt::BlitCommandEncoder,
cmd: BlitCmd<'_, RtPlatform>,
used: &Used,
) -> Result<(), Stop> {
let sel = cmd.selector();
match cmd {
BlitCmd::EndEncoding => {}
@@ -616,9 +656,17 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
} => {
let to = place(destination_slice, destination_level, destination_origin)?;
let lies = layout(source_offset, source_bytes_per_row, source_bytes_per_image);
let (source, destination) = (source_buffer.rt(), destination_texture);
let (source, destination) = (source_buffer, destination_texture);
let size = size(source_size)?;
copy_bytes(e, sel, (source, lies), size, (destination, to), true, NONE)?;
copy_bytes(
e,
(sel, used),
(source, lies),
size,
(destination, to),
true,
NONE,
)?;
}
BlitCmd::CopyBufferToTextureOptions {
source_buffer,
@@ -638,11 +686,10 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
let option = blit_option(options)?;
let to = place(destination_slice, destination_level, destination_origin)?;
let lies = layout(source_offset, source_bytes_per_row, source_bytes_per_image);
let (source, destination) = (source.rt(), destination);
let size = size(source_size)?;
copy_bytes(
e,
sel,
(sel, used),
(source, lies),
size,
(destination, to),
@@ -665,6 +712,18 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
(destination.rt(), destination_offset),
);
e.copy_from_buffer_to_buffer(from.0, from.1, to.0, to.1, size)?;
if size != 0 {
used.buffer_ranges(
source,
false,
std::iter::once(source_offset..source_offset + size),
);
used.buffer_ranges(
destination,
true,
std::iter::once(destination_offset..destination_offset + size),
);
}
}
BlitCmd::CopyTextureToBuffer {
source_texture,
@@ -683,11 +742,11 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
destination_bytes_per_row,
destination_bytes_per_image,
);
let (source, destination) = (source_texture, destination_buffer.rt());
let (source, destination) = (source_texture, destination_buffer);
let size = size(source_size)?;
copy_bytes(
e,
sel,
(sel, used),
(destination, lies),
size,
(source, from),
@@ -717,11 +776,10 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
destination_bytes_per_row,
destination_bytes_per_image,
);
let (source, destination) = (source, destination.rt());
let size = size(source_size)?;
copy_bytes(
e,
sel,
(sel, used),
(destination, lies),
size,
(source, from),
@@ -805,13 +863,19 @@ fn encode(e: &mut rt::BlitCommandEncoder, cmd: BlitCmd<'_, RtPlatform>) -> Resul
if rest.iter().any(|&byte| byte != value) {
return Err(Stop::Unbuilt(Unbuilt::Blit));
}
e.fill_buffer(buffer.rt(), bytes(range)?, value)?;
let bytes = bytes(range)?;
e.fill_buffer(buffer.rt(), bytes.clone(), value)?;
used.buffer_ranges(buffer, true, std::iter::once(bytes));
}
BlitCmd::FillBuffer {
buffer,
range,
value,
} => e.fill_buffer(buffer.rt(), bytes(range)?, value)?,
} => {
let bytes = bytes(range)?;
e.fill_buffer(buffer.rt(), bytes.clone(), value)?;
used.buffer_ranges(buffer, true, std::iter::once(bytes));
}
BlitCmd::FillTexture { .. } => return Err(Stop::Unbuilt(Unbuilt::FillTexture)),
BlitCmd::FillTextureColor { .. } => return Err(Stop::Unbuilt(Unbuilt::Blit)),
BlitCmd::GenerateMipmaps { texture } => {
@@ -874,7 +938,7 @@ impl BlitEncoder<RtPlatform> for RtObj<RtBlitEncoder> {
note_operands(operands, &cmd);
}
let stopped = match open.encoder.as_mut() {
Some(e) => encode(e, cmd).err(),
Some(e) => encode(e, cmd, self.kept.copies()).err(),
None => Some(Stop::Metal("a command after endEncoding")),
};
if ending && let Some(e) = open.encoder.take() {
@@ -498,6 +498,8 @@ pub struct RtBuffer {
/// The copy of host pages it lies over (`super::copied`), which a command buffer that uses it
/// syncs; `None` for any other.
copied: Option<Arc<super::copied::Copied>>,
/// Whether the buffer was placed over an existing copy by its address or mapping.
aliases_copy: bool,
/// The guest's object id for it, which its release's entry in the device's history names
/// (`super::fault`).
named: super::fault::Named,
@@ -672,6 +674,11 @@ impl RtBuffer {
pub(super) fn copied(&self) -> Option<&Arc<super::copied::Copied>> {
self.copied.as_ref()
}
/// A buffer placed by a heap or made over an existing block's mapping.
pub(super) fn copied_alias(&self) -> bool {
self.in_heap || self.aliases_copy
}
}
/// The longest a deferred buffer's memory took to make, in nanoseconds
@@ -1202,6 +1209,7 @@ fn deferred_as(
#[cfg(unix)]
exported: OnceLock::new(),
copied: None,
aliases_copy: false,
}))
}
@@ -1331,17 +1339,17 @@ fn made(
/// The buffer's handle, of rt's buffer `rt` answering `options`.
fn buffer(device: &RtObj<RtDevice>, rt: rt::Buffer, options: u64) -> RtObj<RtBuffer> {
buffer_of(device, rt, options, (false, None), None)
buffer_of(device, rt, options, (false, None, false), None)
}
/// The buffer's handle, of rt's buffer `rt` answering `options`, placed by a heap where `in_heap`,
/// lying over `copied` where it lies over a copy of host pages (`super::copied`), running
/// `deallocator` as it goes where given.
/// lying over `copied` where it lies over a copy of host pages (`super::copied`). A buffer
/// placed by address or mapping `aliases_copy`. Runs `deallocator` as it goes where given.
pub(super) fn buffer_of(
device: &RtObj<RtDevice>,
rt: rt::Buffer,
options: u64,
(in_heap, copied): (bool, Option<Arc<super::copied::Copied>>),
(in_heap, copied, aliases_copy): (bool, Option<Arc<super::copied::Copied>>, bool),
deallocator: Option<Slot>,
) -> RtObj<RtBuffer> {
RtObj::new(RtBuffer {
@@ -1356,6 +1364,7 @@ pub(super) fn buffer_of(
#[cfg(unix)]
exported: OnceLock::new(),
copied,
aliases_copy,
})
}
@@ -1379,6 +1388,7 @@ pub(super) fn with_export(
deallocator: None,
exported: OnceLock::from(exported),
copied: None,
aliases_copy: false,
})
}
@@ -1428,7 +1438,17 @@ fn in_known(
};
let (block, offset) = known_at(device, pin, length, class, None)?;
match device.rt().new_buffer(block.id, offset, length, zero_from) {
Ok(made) => Some(Some(buffer(device, made, o.answered))),
Ok(made) => {
let copied = super::copied::of(block.id);
let aliases_copy = copied.is_some();
Some(Some(buffer_of(
device,
made,
o.answered,
(false, copied, aliases_copy),
None,
)))
}
Err(error) => {
rt_refused_create(sel, &error);
Some(None)
@@ -1639,7 +1659,7 @@ fn no_copy(
if in_place {
read_only(sel);
}
let placed = (false, super::copied::of(block.id));
let placed = (false, super::copied::of(block.id), deallocator.is_some());
Some(buffer_of(device, made, o.answered, placed, deallocator))
}
@@ -5517,6 +5537,85 @@ mod tests {
}
}
#[test]
fn texture_blits_sync_only_the_buffer_rows_on_vulkan() -> Result<(), &'static str> {
use crate::core::platform::types::{MtlOrigin, MtlSize};
let platform = RtPlatform::new();
let device = platform.system_default_device().ok_or("no Vulkan device")?;
let queue = device.new_command_queue().ok_or("no command queue")?;
let source = over_a_copy(&device, false);
let destination = over_a_copy(&device, false);
let page = device.facts().page_size;
let pitch = page;
let offset = 16;
let descriptor = platform.texture_descriptor(&TextureDesc {
pixel_format: 70,
width: 4,
height: 2,
..TextureDesc::default()
});
let texture = device
.new_texture(OnFault::Return, &descriptor)
.map_err(|_| "texture creation raised")?
.ok_or("no texture")?;
// SAFETY: the two 16-byte rows and the padding are inside the source's two pages.
unsafe {
source
.pages
.wrapping_add(offset)
.as_ptr::<u8>()
.write_bytes(0x22, 16);
source
.pages
.wrapping_add(offset + pitch)
.as_ptr::<u8>()
.write_bytes(0x33, 16);
destination
.pages
.wrapping_add(offset + 16)
.as_ptr::<u8>()
.write(0x44);
}
let size = MtlSize::new(4, 2, 1);
let origin = MtlOrigin::new(0, 0, 0);
blit_and_wait(
&queue,
vec![
BlitCmd::CopyBufferToTexture {
source_buffer: &source.buffer,
source_offset: offset,
source_bytes_per_row: pitch,
source_bytes_per_image: 0,
source_size: size,
destination_texture: &texture,
destination_slice: 0,
destination_level: 0,
destination_origin: origin,
},
BlitCmd::CopyTextureToBuffer {
source_texture: &texture,
source_slice: 0,
source_level: 0,
source_origin: origin,
source_size: size,
destination_buffer: &destination.buffer,
destination_offset: offset,
destination_bytes_per_row: pitch,
destination_bytes_per_image: 0,
},
],
);
let mut first = [0x22; 17];
first[16] = 0x44;
assert_eq!(read(destination.pages.wrapping_add(offset), 17), first);
assert_eq!(
read(destination.pages.wrapping_add(offset + pitch), 16),
[0x33; 16]
);
Ok(())
}
/// On the GPU the test holds: a copy a compute encoder declares with `useResources:`, as a
/// shader that reaches it through an argument buffer's address asks, and binds not, is synced
/// for its command buffer: the CPU's bytes copied in at the commit, and, declared for writing
@@ -58,8 +58,9 @@
//! copy.
//! - **Copied in at the commits that use it** ([`copy_in`], from `super::command`'s commit,
//! before rt is handed the command buffer, so before the work that reads it): every byte of the
//! pages that differs from the base is written into the copy and the base. A byte the CPU did
//! not change is never written, so a GPU write to the copy by work still in flight stays. Where
//! pages in a chunk the work can read or write that differs from the base is written into the
//! copy and the base. A byte the CPU did not change is never written, so a GPU write to the copy
//! by work still in flight stays. Where
//! the device's Shared memory type is host-coherent, the GPU reads the bytes written with no
//! flush; where it is not, rt flushes the Shared memory the command buffer keeps before it
//! submits it, and flushes then invalidates what it may write before its completed handlers run
@@ -68,9 +69,10 @@
//! are dropped is written whole instead ("Writes dropped").
//! - **Merged back at the completions of the command buffers that can write it** ([`merging`],
//! the first of the command buffer's completed handlers, so before core's and before a waiter
//! returns): every byte of the copy that differs from the base is written into the pages where
//! the pages' byte still is the base's, and the base takes the copy's byte. A byte both sides
//! changed keeps the CPU's, which the next commit that uses it copies in, as Metal keeps the
//! returns): every byte of the copy in a chunk the work can write that differs from the base
//! is written into the pages where the pages' byte still is the base's, and the base takes the
//! copy's byte. A byte both sides changed keeps the CPU's, which the next commit that uses it
//! copies in, as Metal keeps the
//! later of two writes. A byte the guest writes between the merge's read of it and its store is
//! lost only where the GPU changed it too. A command buffer whose uses of a copy can only read
//! it neither merges it back nor puts back its bytes: its work wrote none of them.
@@ -119,6 +121,7 @@
//! ([`DECLARATIONS_CODE`]), with the commits that declared one ([`DECLARING_COMMITS_CODE`]).
use std::collections::BTreeMap;
use std::ops::Range;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Weak};
@@ -502,16 +505,80 @@ impl Drop for Fresh {
}
}
/// A copy a command buffer uses, and whether a use of it can write it ([`Used`]).
/// A copy a command buffer uses, with byte ranges relative to the start of its block.
#[derive(Clone)]
pub(super) struct CopyUse {
/// The copy.
copied: Arc<Copied>,
/// Whether a use of it can write it.
writes: bool,
reads: Ranges,
writes: Ranges,
}
/// The copies a command buffer uses, each once, with whether a use of it can write it ("Synced
const MAX_RANGES: usize = 16;
#[derive(Clone, Debug, PartialEq, Eq)]
enum Ranges {
Known(Vec<Range<usize>>),
All,
}
impl Ranges {
const EMPTY: Self = Self::Known(Vec::new());
fn is_empty(&self) -> bool {
matches!(self, Self::Known(ranges) if ranges.is_empty())
}
fn add(&mut self, bytes: Range<usize>) {
let Self::Known(ranges) = self else { return };
let first = ranges.partition_point(|range| range.end < bytes.start);
let count = ranges[first..].partition_point(|range| range.start <= bytes.end);
if count == 0 {
if ranges.len() == MAX_RANGES {
*self = Self::All;
} else {
ranges.insert(first, bytes);
}
return;
}
let last = first + count - 1;
ranges[first] = bytes.start.min(ranges[first].start)..bytes.end.max(ranges[last].end);
ranges.drain(first + 1..last + 1);
}
/// The union of two sets, rounded out to chunks. Ranges in separate sets can touch the same
/// chunk even when their bytes do not.
fn chunks<'a>(
&'a self,
other: &'a Self,
len: usize,
) -> impl Iterator<Item = Range<usize>> + 'a {
let (mut first, mut second, mut whole) = match (self, other) {
(Self::Known(first), Self::Known(second)) => (&first[..], &second[..], None),
_ => (&[][..], &[][..], Some(0..len / CHUNK)),
};
let mut end = 0;
std::iter::from_fn(move || {
if whole.is_some() {
return whole.take();
}
while let Some(next) = match (first.first(), second.first()) {
(Some(a), Some(b)) if a.start <= b.start => first.split_off_first(),
(_, Some(_)) => second.split_off_first(),
_ => first.split_off_first(),
} {
let start = end.max(next.start / CHUNK);
let past = next.end.div_ceil(CHUNK);
if start < past {
end = past;
return Some(start..past);
}
}
None
})
}
}
/// The copies a command buffer uses, each once, with the ranges it can read or write ("Synced
/// for the command buffers that use it"), noted by its encoders as they set or declare an object
/// over one, and taken at its commit.
#[derive(Clone, Default)]
@@ -524,24 +591,88 @@ impl Used {
let Some(copied) = copied else {
return;
};
self.note(copied, |u| {
u.reads = Ranges::All;
if writes {
u.writes = Ranges::All;
}
});
}
fn note(&self, copied: &Arc<Copied>, note: impl FnOnce(&mut CopyUse)) {
let mut used = self.0.lock();
match used.iter_mut().find(|u| Arc::ptr_eq(&u.copied, copied)) {
Some(u) => u.writes |= writes,
None => used.push(CopyUse {
copied: Arc::clone(copied),
writes,
}),
Some(u) => note(u),
None => {
let mut use_ = CopyUse {
copied: Arc::clone(copied),
reads: Ranges::EMPTY,
writes: Ranges::EMPTY,
};
note(&mut use_);
if !use_.reads.is_empty() || !use_.writes.is_empty() {
used.push(use_);
}
}
}
}
/// A blit reads or writes these buffer-relative byte ranges.
pub(super) fn buffer_ranges(
&self,
buffer: &RtBuffer,
writes: bool,
ranges: impl IntoIterator<Item = Range<u64>>,
) {
let Some(copied) = buffer.copied() else {
return;
};
// A Managed buffer with a separate GPU copy uploads any pending `didModifyRange:` ranges
// from its Shared backing at commit time, even if this blit touches a different page.
if buffer.copied_alias() || buffer.gpu_copy_apart() {
if ranges.into_iter().any(|bytes| !bytes.is_empty()) {
self.add(Some(copied), writes);
}
return;
}
self.add_ranges(copied, writes, buffer.rt().offset(), ranges);
}
fn add_ranges(
&self,
copied: &Arc<Copied>,
writes: bool,
offset: u64,
ranges: impl IntoIterator<Item = Range<u64>>,
) {
self.note(copied, |u| {
let used = if writes { &mut u.writes } else { &mut u.reads };
for bytes in ranges {
if *used == Ranges::All {
break;
}
let at = |byte: u64| {
offset
.saturating_add(byte)
.min(copied.len.to_u64())
.to_usize()
};
let bytes = at(bytes.start)..at(bytes.end);
if !bytes.is_empty() {
used.add(bytes);
}
}
});
}
/// The command buffer uses `buffer` where its work can write it (bound to a shader's slot, a
/// blit's destination or fill): its copy, where it lies over one.
/// synchronize): its copy, where it lies over one.
pub(super) fn buffer(&self, buffer: &RtBuffer) {
self.add(buffer.copied(), true);
}
/// The command buffer's work reads `buffer` alone (as indices, as an indirect or tessellation
/// factor buffer, as a blit's source): its copy, where it lies over one.
/// factor buffer): its copy, where it lies over one.
pub(super) fn buffer_read(&self, buffer: &RtBuffer) {
self.add(buffer.copied(), false);
}
@@ -620,7 +751,7 @@ pub(super) fn declare(
pub(super) fn writes(copies: &[CopyUse]) -> bool {
copies
.iter()
.any(|u| u.writes && u.copied.kind != Kind::Drops)
.any(|u| !u.writes.is_empty() && u.copied.kind != Kind::Drops)
}
/// Counts a render pass `sel` made whose attachments lie in the blocks `blocks` where one is a
@@ -656,12 +787,10 @@ pub(super) fn copy_in(copies: &[CopyUse]) {
let mut tally = Tally::default();
for u in copies {
let at = clock.now_mono();
let written = u.copied.copy_in();
let bytes = match u.copied.kind {
Kind::Merges | Kind::Drops => u.copied.len.to_u64(),
Kind::Unchanging { .. } => 0,
};
tally.note(&u.copied, (written, bytes), (&clock, at));
// A write needs the pre-submit CPU bytes in the base too. Otherwise merge_back
// would see those bytes as CPU writes made during the submission.
let chunks = u.reads.chunks(&u.writes, u.copied.len);
tally.note(&u.copied, u.copied.copy_in(chunks), (&clock, at));
}
tally.count(true);
synced(IN_BYTES_CODE, tally.written, &clock, began);
@@ -688,14 +817,16 @@ fn merge_back(copies: &[CopyUse]) {
let clock = crate::os::OsClock::new();
let began = clock.now_mono();
let mut tally = Tally::default();
for u in copies.iter().filter(|u| u.writes) {
for u in copies.iter().filter(|u| !u.writes.is_empty()) {
let at = clock.now_mono();
let written = match u.copied.kind {
Kind::Merges => u.copied.merge_back(),
let bytes = match u.copied.kind {
Kind::Merges => u
.copied
.merge_back(u.writes.chunks(&Ranges::EMPTY, u.copied.len)),
Kind::Drops => continue,
Kind::Unchanging { .. } => u.copied.copy_whole(),
Kind::Unchanging { .. } => (u.copied.copy_whole(), u.copied.len.to_u64()),
};
tally.note(&u.copied, (written, u.copied.len.to_u64()), (&clock, at));
tally.note(&u.copied, bytes, (&clock, at));
}
tally.count(false);
synced(BACK_BYTES_CODE, tally.written, &clock, began);
@@ -815,16 +946,20 @@ impl Copied {
/// Writes into the copy the bytes of the pages that differ from the base, and the base takes
/// them: the bytes written. The whole of the pages for a copy of read-only pages that may
/// change ("Writes dropped"); nothing for one of unchanging pages ("Unchanging pages").
fn copy_in(&self) -> u64 {
fn copy_in(&self, chunks: impl Iterator<Item = Range<usize>>) -> (u64, u64) {
match self.kind {
Kind::Merges => {}
Kind::Drops => return self.copy_whole(),
Kind::Unchanging { .. } => return 0,
Kind::Drops => return (self.copy_whole(), self.len.to_u64()),
Kind::Unchanging { .. } => return (0, 0),
}
let mut base = self.base.lock();
let mut now = [0_u64; WORDS];
let mut written = 0;
for (chunk, was) in base.as_chunks_mut::<WORDS>().0.iter_mut().enumerate() {
let mut scanned = 0;
let base = base.as_chunks_mut::<WORDS>().0;
for chunk in chunks.flatten() {
scanned += CHUNK.to_u64();
let was = &mut base[chunk];
let at = chunk * CHUNK;
// SAFETY: the chunk lies in the pages, mapped until the copy goes (`new`'s contract).
unsafe { read_chunk(self.home.as_ptr().add(at), &mut now) };
@@ -842,16 +977,20 @@ impl Copied {
}
}
}
written
(written, scanned)
}
/// Writes into the pages the bytes of the copy that differ from the base where the pages'
/// still are the base's, and the base takes the copy's: the bytes written.
fn merge_back(&self) -> u64 {
fn merge_back(&self, chunks: impl Iterator<Item = Range<usize>>) -> (u64, u64) {
let mut base = self.base.lock();
let (mut gpu, mut cpu) = ([0_u64; WORDS], [0_u64; WORDS]);
let mut written = 0;
for (chunk, was) in base.as_chunks_mut::<WORDS>().0.iter_mut().enumerate() {
let mut scanned = 0;
let base = base.as_chunks_mut::<WORDS>().0;
for chunk in chunks.flatten() {
scanned += CHUNK.to_u64();
let was = &mut base[chunk];
let at = chunk * CHUNK;
// SAFETY: the chunk lies in the copy's first bytes, the length of the pages.
unsafe { read_chunk(self.copy.as_ptr().add(at), &mut gpu) };
@@ -871,7 +1010,7 @@ impl Copied {
}
}
}
written
(written, scanned)
}
/// Writes the whole of the pages into the copy again, the GPU's writes to it put back ("Writes
@@ -954,6 +1093,163 @@ mod tests {
unsafe { Copied::new(home, len, kind, (copy, cap, None)) }
}
#[test]
fn blit_ranges_coalesce_clamp_and_fall_back_independently() -> Result<(), &'static str> {
let mut pages = chunks(3);
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
let len = 3 * CHUNK;
// SAFETY: the pages outlive the copy.
let copied = Arc::new(unsafe { copy_of(home, len, Kind::Merges) }.ok_or("copy")?);
let used = Used::default();
let end = len.to_u64();
used.add_ranges(&copied, false, 10, [3..3, end..u64::MAX]);
assert!(used.take().is_empty());
used.add_ranges(
&copied,
false,
10,
[12..20, 0..7, 6..12, end - 11..u64::MAX],
);
used.add_ranges(&copied, true, 0, std::iter::once(1..2));
let uses = used.take();
assert_eq!(uses[0].reads, Ranges::Known(vec![10..30, len - 1..len]));
assert_eq!(
uses[0]
.reads
.chunks(&uses[0].writes, len)
.collect::<Vec<_>>(),
[0..1, 2..3],
);
used.add_ranges(
&copied,
true,
0,
(0..=MAX_RANGES.to_u64()).map(|n| 2 * n..2 * n + 1),
);
used.add_ranges(&copied, false, 0, std::iter::once(2..3));
let uses = used.take();
assert_eq!(uses[0].writes, Ranges::All);
assert_eq!(
uses[0].reads,
Ranges::Known(std::iter::once(2..3).collect())
);
Ok(())
}
#[test]
fn a_full_shader_use_expands_a_local_blit_use() -> Result<(), &'static str> {
let mut pages = chunks(2);
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
// SAFETY: the pages outlive the copy.
let copied = Arc::new(unsafe { copy_of(home, 2 * CHUNK, Kind::Merges) }.ok_or("copy")?);
let used = Used::default();
for shader_writes in [false, true] {
used.add_ranges(&copied, true, 0, std::iter::once(5..8));
used.add(Some(&copied), shader_writes);
let uses = used.take();
assert_eq!(uses.len(), 1);
assert_eq!(uses[0].reads, Ranges::All);
let expected = if shader_writes {
Ranges::All
} else {
Ranges::Known(std::iter::once(5..8).collect())
};
assert_eq!(uses[0].writes, expected);
}
Ok(())
}
#[test]
fn local_blit_syncs_only_its_chunks_and_keeps_cpu_writes() -> Result<(), &'static str> {
let mut pages = chunks(5);
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
let len = 5 * CHUNK;
// SAFETY: the pages outlive the copy.
let copied = Arc::new(unsafe { copy_of(home, len, Kind::Merges) }.ok_or("copy")?);
let used = Used::default();
let (read, write, outside) = (CHUNK, 2 * CHUNK + 8, 4 * CHUNK);
used.add_ranges(
&copied,
false,
read.to_u64(),
std::iter::once(0..CHUNK.to_u64()),
);
used.add_ranges(
&copied,
true,
write.to_u64(),
std::iter::once(0..CHUNK.to_u64()),
);
let uses = used.take();
// SAFETY: each byte range lies inside its respective allocation.
unsafe {
home.as_ptr().add(read).write_bytes(0x11, CHUNK);
home.as_ptr().add(write).write_bytes(0x22, CHUNK);
home.as_ptr().add(outside).write(0x33);
}
copy_in(&uses);
// SAFETY: same bounds as above, including the eight bytes before the destination.
unsafe {
assert_eq!(bytes(copied.copy.add(read), CHUNK), [0x11; CHUNK]);
assert_eq!(bytes(copied.copy.add(write), CHUNK), [0x22; CHUNK]);
assert_eq!(copied.copy.as_ptr().add(outside).read(), 0);
copied.copy.as_ptr().add(write).write_bytes(0x44, CHUNK);
home.as_ptr().add(write).write(0x55);
home.as_ptr().add(write - 1).write(0x66);
copied.copy.as_ptr().add(outside + 1).write(0x77);
}
merge_back(&uses);
// SAFETY: same bounds as above.
unsafe {
assert_eq!(bytes(home.add(write - 1), 2), [0x66, 0x55]);
assert_eq!(bytes(home.add(write + 1), CHUNK - 1), [0x44; CHUNK - 1]);
assert_eq!(bytes(home.add(outside), 2), [0x33, 0]);
}
Ok(())
}
#[test]
fn a_64_mib_copy_scans_only_the_chunks_of_a_4_kib_blit() -> Result<(), &'static str> {
let len = 64 * 1024 * 1024;
let mut pages = chunks(len / CHUNK);
let mut memory = chunks(len / CHUNK);
let home = NonNull::new(pages.as_mut_ptr().cast::<u8>()).ok_or("pages")?;
let copy = NonNull::new(memory.as_mut_ptr().cast::<u8>()).ok_or("copy memory")?;
// SAFETY: both allocations are disjoint, aligned and outlive the copy.
let copied = Arc::new(
unsafe { Copied::new(home, len, Kind::Merges, (copy, len, None)) }.ok_or("copy")?,
);
let clock = crate::os::OsClock::new();
for (offset, expected) in [(len / 2, 1), (len / 2 + 4, 2)] {
let used = Used::default();
used.add_ranges(
&copied,
true,
offset.to_u64(),
std::iter::once(0..CHUNK.to_u64()),
);
let uses = used.take();
for (label, ranges, want) in [
("whole", &Ranges::All, 16_384),
("local", &uses[0].writes, expected),
] {
let began = clock.now_mono();
let (_, in_bytes) = copied.copy_in(ranges.chunks(&Ranges::EMPTY, len));
let incoming = clock.now_mono().saturating_duration_since(began);
let began = clock.now_mono();
let (_, back_bytes) = copied.merge_back(ranges.chunks(&Ranges::EMPTY, len));
let outgoing = clock.now_mono().saturating_duration_since(began);
let segments = (in_bytes / CHUNK.to_u64(), back_bytes / CHUNK.to_u64());
assert_eq!(segments, (want, want));
eprintln!(
"64 MiB / 4 KiB, offset {offset}, {label}: copy_in {} chunks {incoming:?}, merge_back {} chunks {outgoing:?}",
segments.0, segments.1
);
}
}
Ok(())
}
/// A copy holds its pages' bytes and zeros past them; a commit's copy in writes the bytes the
/// CPU changed and leaves the copy's others, which the GPU may have written meanwhile; a
/// completion's merge back writes the bytes the GPU changed where the CPU did not, a byte both
@@ -971,7 +1267,13 @@ mod tests {
// SAFETY: the copy's memory holds `TAIL` bytes past the pages'.
let tail = bytes(unsafe { copied.copy.add(len) }, TAIL);
assert_eq!(tail, vec![0; TAIL], "zeros past the pages' bytes");
assert_eq!((copied.copy_in(), copied.merge_back()), (0, 0));
assert_eq!(
(
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
copied.merge_back(std::iter::once(0..len / CHUNK)).0
),
(0, 0)
);
// The CPU writes 3 bytes of the pages; the GPU, meanwhile, a byte of the copy beside one.
// SAFETY: inside the pages and the copy.
@@ -979,7 +1281,7 @@ mod tests {
home.as_ptr().add(5).write_bytes(0x22, 3);
copied.copy.as_ptr().add(8).write(0x33);
}
assert_eq!(copied.copy_in(), 3);
assert_eq!(copied.copy_in(std::iter::once(0..len / CHUNK)).0, 3);
let copy = bytes(copied.copy, 16);
assert_eq!(copy[..5], [0x11; 5]);
assert_eq!(copy[5..8], [0x22; 3]);
@@ -994,14 +1296,20 @@ mod tests {
copied.copy.as_ptr().add(far + 8).write(0x55);
home.as_ptr().add(far + 8).write(0x66);
}
assert_eq!(copied.merge_back(), 1 + 8);
assert_eq!(copied.merge_back(std::iter::once(0..len / CHUNK)).0, 1 + 8);
let back = bytes(home, len);
assert_eq!(back[8], 0x33);
assert_eq!(back[far..far + 8], [0x44; 8]);
assert_eq!(back[far + 8], 0x66);
assert_eq!(copied.copy_in(), 1);
assert_eq!(copied.copy_in(std::iter::once(0..len / CHUNK)).0, 1);
assert_eq!(bytes(copied.copy, len), back);
assert_eq!((copied.copy_in(), copied.merge_back()), (0, 0));
assert_eq!(
(
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
copied.merge_back(std::iter::once(0..len / CHUNK)).0
),
(0, 0)
);
}
/// The count of `code` in the degradation counts' line.
@@ -1074,7 +1382,11 @@ mod tests {
);
let why_now = [why_counts[0] + 1, why_counts[1] + len.to_u64()];
assert_eq!(whys.map(counted), why_now, "by the guest's why");
assert_eq!(copied.copy_in(), len.to_u64(), "whole at each");
assert_eq!(
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
len.to_u64(),
"whole at each"
);
}
/// A command buffer's completion merges back only the copies a use of which can write them:
@@ -1111,7 +1423,7 @@ mod tests {
used.add(Some(written), true);
used.add(None, true);
let copies = used.take();
let uses: Vec<bool> = copies.iter().map(|u| u.writes).collect();
let uses: Vec<bool> = copies.iter().map(|u| !u.writes.is_empty()).collect();
assert_eq!(uses, [false, false, true], "each copy once");
assert!(writes(&copies));
assert!(used.take().is_empty(), "taken");
@@ -1218,7 +1530,11 @@ mod tests {
read.add(Some(&copied), false);
let reads = read.take();
copy_in(&reads);
assert_eq!(copied.copy_in(), 0, "never copied in");
assert_eq!(
copied.copy_in(std::iter::once(0..len / CHUNK)).0,
0,
"never copied in"
);
merge_back(&reads);
let mut gpu = vec![0x11; len];
gpu[CHUNK + 16..CHUNK + 24].fill(0x44);
@@ -464,7 +464,7 @@ impl Heap<RtPlatform> for RtObj<RtHeap> {
return Ok(None);
}
};
let placed = (true, self.copied.clone());
let placed = (true, self.copied.clone(), false);
let buffer = buffer::buffer_of(&self.device, made, self.options, placed, None);
Ok(Some(buffer))
});
@@ -109,7 +109,7 @@ use metal2vulkan::metal::{
};
use metal2vulkan_runtime as rt;
use crate::core::platform::render::{RenderCmd, RenderEncoder};
use crate::core::platform::render::{RenderCmd, RenderEncoder, VertexDraw, encode_each};
use crate::core::platform::types::{MtlScissorRect, MtlViewport};
use crate::core::platform::{Handle, ObjId};
use crate::core::raise::{OnFault, RaiseResult};
@@ -123,7 +123,7 @@ use super::diag::{self, Bound, Point, Target, Use};
use super::fault::{EncoderKind, EncoderNames, Naming};
use super::render_pipeline::{Formats, Raster, RtRenderPipeline};
use super::texture::RtTexture;
use super::unbuilt::{Unbuilt, naming_functions, refuse};
use super::unbuilt::{Named, Unbuilt, naming_functions, refuse};
use super::{RtBuffer, RtObj, RtPlatform};
/// A count, a base or an index past rt's 32 bits.
@@ -250,6 +250,40 @@ impl RtRenderEncoder {
}
}
/// Records a draw gap's details and returns the functions to name when reporting the refusal.
#[cold]
fn refusal_functions(
&self,
seen: &Seen,
sel: &'static str,
stopped: &Stop,
draw: bool,
primitive: Option<u64>,
viewports: Option<Viewports<'_>>,
) -> Named {
let functions = match (stopped, &seen.state) {
(Stop::Rt(_) | Stop::Unbuilt(_), Some(state)) if draw => state.functions(),
_ => Vec::new(),
};
if let Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind })) = stopped {
let what = DrawDetail {
primitive,
raster: seen.state.as_ref().map(|state| state.raster()),
formats: (*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(seen)),
viewports,
};
naming_functions(functions.clone(), || {
super::unbuilt::refusal_detail(sel, error, Some(&what));
});
match kind {
rt::DrawKind::AttachmentRead => self.attachment_read(seen),
rt::DrawKind::FetchedAttachment => self.fetched_attachment(seen),
_ => {}
}
}
functions
}
/// Encodes `cmd` but `endEncoding`, which the caller ends.
fn command(&self, open: &mut Open, cmd: RenderCmd<'_, RtPlatform>) -> Result<(), Stop> {
let Open {
@@ -268,8 +302,7 @@ impl RtRenderEncoder {
vertex_count,
} => {
set(*pipeline)?;
let (start, count) = (small(vertex_start)?, small(vertex_count)?);
e.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?;
draw_primitives(e, primitive_type, vertex_start, vertex_count)?;
}
RenderCmd::DrawPrimitivesInstances {
primitive_type,
@@ -688,6 +721,18 @@ fn set(pipeline: Option<ObjId>) -> Result<(), Stop> {
}
}
/// The short draw form, after checking that a pipeline is bound.
fn draw_primitives(
encoder: &mut rt::RenderCommandEncoder,
primitive_type: u64,
vertex_start: u64,
vertex_count: u64,
) -> Result<(), Stop> {
let (start, count) = (small(vertex_start)?, small(vertex_count)?);
encoder.draw_primitives(primitive(primitive_type)?, start, count, 1, 0)?;
Ok(())
}
/// `Ok` where a setting rt has none of is at Metal's default (`at_default`); unbuilt otherwise.
fn unbuilt_unless(at_default: bool) -> Result<(), Stop> {
match at_default {
@@ -1104,30 +1149,9 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
note_names(names, &cmd);
}
let stopped = self.command(&mut open, cmd).err();
let functions = match (&stopped, &open.seen.state) {
(Some(Stop::Rt(_) | Stop::Unbuilt(_)), Some(state)) if draw => state.functions(),
_ => Vec::new(),
};
if let Some(Stop::Rt(error @ rt::Error::Unsupported(rt::Gap::Draw { kind }))) = &stopped
{
let raster = open.seen.state.as_ref().map(|state| state.raster());
let formats =
(*kind == rt::DrawKind::AttachmentFormats).then(|| self.formats(&open.seen));
let what = DrawDetail {
primitive,
raster,
formats,
viewports,
};
naming_functions(functions.clone(), || {
super::unbuilt::refusal_detail(sel, error, Some(&what));
});
match kind {
rt::DrawKind::AttachmentRead => self.attachment_read(&open.seen),
rt::DrawKind::FetchedAttachment => self.fetched_attachment(&open.seen),
_ => {}
}
}
let functions = stopped.as_ref().map_or_else(Vec::new, |stop| {
self.refusal_functions(&open.seen, sel, stop, draw, primitive, viewports)
});
let icb_gap = |error: &rt::Error| {
matches!(
error,
@@ -1153,6 +1177,69 @@ impl RenderEncoder<RtPlatform> for RtObj<RtRenderEncoder> {
recorded_answer
}
fn encode_draws(&self, on: OnFault, draws: &[VertexDraw<'_, RtPlatform>]) -> RaiseResult<()> {
if draws.is_empty() {
return Ok(());
}
if crate::recorder::on() || super::copied::any() {
return encode_each(self, on, draws);
}
let held = self.open.lock();
let mut open = held.borrow_mut();
let Open {
rt,
pipeline,
seen,
naming,
} = &mut *open;
let (Some(encoder), Some(_), Some(names)) = (rt, pipeline, naming.names()) else {
drop(open);
drop(held);
return encode_each(self, on, draws);
};
let mut last = None;
let mut buffer = None;
for (i, draw) in draws.iter().enumerate() {
if let Some(bound) = draw.buffer {
names.bound_buffers.add_named(bound.named());
}
let key = draw.buffer.map(std::ptr::from_ref);
if key != last {
last = key;
buffer = draw.buffer.map(|b| b.rt());
}
let bound = small(draw.index).and_then(|index| {
encoder
.set_vertex_buffer(buffer, draw.offset, index)
.map_err(Stop::from)
});
// A refusal is reported once. After a refused bind, the draw still sees the
// encoder's existing binding, and only commands that have yet to run go to encode.
if let Err(stop) = bound {
drop(open);
drop(held);
report(draw.vertex_buffer().selector(), Some(stop));
self.encode(on, draw.primitives())?;
return encode_each(self, on, &draws[i + 1..]);
}
if let Err(stop) = draw_primitives(
encoder,
draw.primitive_type,
draw.vertex_start,
draw.vertex_count,
) {
let sel = draw.primitives().selector();
let functions =
self.refusal_functions(seen, sel, &stop, true, Some(draw.primitive_type), None);
drop(open);
drop(held);
naming_functions(functions, || report(sel, Some(stop)));
return encode_each(self, on, &draws[i + 1..]);
}
}
Ok(())
}
/// Holds the encoder for `run` ([`RtRenderEncoder`]'s `open`): the commands `run` sends take
/// its lock again on this thread, and another thread's wait for it to end.
fn encoding<T>(&self, run: impl FnOnce() -> T) -> T {
@@ -1515,6 +1602,382 @@ mod tests {
words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
/// Each draw, including the draw after a refused bind, uses the binding it would see
/// alone. The visibility result counts the draws even when a later one covers their pixels.
#[test]
fn draw_batches_match_individual_commands_on_vulkan() -> Result<(), &'static str> {
check_draw_batch(DrawBatchCase::Existing)
}
#[test]
fn draw_batches_clear_and_rebind_a_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
check_draw_batch(DrawBatchCase::Unbind)
}
#[test]
fn draw_batches_report_a_gap_and_continue_on_vulkan() -> Result<(), &'static str> {
check_draw_batch(DrawBatchCase::Gap)
}
#[test]
fn draw_batches_record_bound_buffer_names_on_vulkan() -> Result<(), &'static str> {
check_draw_batch(DrawBatchCase::Names)
}
#[derive(PartialEq, Eq)]
enum DrawBatchCase {
Existing,
Unbind,
Gap,
Names,
}
fn check_draw_batch(case: DrawBatchCase) -> Result<(), &'static str> {
use crate::core::platform::command::WorkNames;
use crate::rt_platform::fault::{Ids, Operands, name_buffer};
use std::sync::Arc;
let platform = RtPlatform::new();
let device = platform.system_default_device().ok_or("no Vulkan device")?;
let queue = device.new_command_queue().ok_or("no command queue")?;
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
let (red, green, cyan, blue) = (
[255, 0, 0, 255],
[0, 255, 0, 255],
[0, 255, 255, 255],
[0, 0, 255, 255],
);
let a = shared(&device, &vertices(&[green, cyan]));
let b = shared(&device, &vertices(&[blue]));
name_buffer(&a, 7);
let results = shared(&device, &[0; 8]);
let on = OnFault::Return;
let Ok(Some(target)) = device.new_texture(
on,
&platform.texture_descriptor(&TextureDesc {
width: 4,
height: 4,
usage: 5,
..TextureDesc::default()
}),
) else {
return Err("no render target");
};
let pass = pass(&target, 2);
pass.set_pass(&PassSet {
visibility_result_buffer: Some(Some(&results)),
..PassSet::default()
});
let draw_a = VertexDraw {
buffer: Some(&a),
offset: 0,
index: 0,
primitive_type: TRIANGLE,
vertex_start: 0,
vertex_count: 3,
};
let next_a = VertexDraw {
offset: 36,
..draw_a
};
let draw_b = VertexDraw {
buffer: Some(&b),
..draw_a
};
let bad_bind = VertexDraw {
index: 31,
..draw_b
};
let bad_draw = VertexDraw {
primitive_type: u64::MAX,
..draw_b
};
let codes = [RtRefusal::Refused, RtRefusal::Ours, RtRefusal::Gap].map(RtRefusal::code);
let render = |draws: &[VertexDraw<'_, RtPlatform>],
batch,
operands: bool,
no_pipeline: bool,
ended| {
let Ok(Some(cb)) = queue.command_buffer(on) else {
return Err("no command buffer");
};
if !operands {
cb.names_work(&Arc::new(WorkNames::new(1)));
}
let Ok(Some(encoder)) = cb.render_encoder(on, &pass) else {
return Err("no render encoder");
};
if !no_pipeline {
assert_eq!(
encoder.encode(
on,
RenderCmd::SetRenderPipelineState {
pipeline_state: Some(&state),
},
),
Ok(())
);
}
assert_eq!(
encoder.encode(
on,
RenderCmd::SetVisibilityResultMode { mode: 2, offset: 0 }
),
Ok(())
);
if case == DrawBatchCase::Gap {
// Triangles still draw; the line in the middle hits rt's DrawKind::LineWidth.
encoder
.open
.lock()
.borrow_mut()
.rt
.as_mut()
.ok_or("no rt encoder")?
.set_line_width(2.0);
}
if ended {
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
}
let before = codes.map(counted);
let answer = if batch {
encoder.encode_draws(on, draws)
} else {
encode_each(&encoder, on, draws)
};
assert_eq!(answer, Ok(()));
let refused = std::array::from_fn(|i| counted(codes[i]) - before[i]);
let names = encoder.open.lock().borrow_mut().naming.names().cloned();
if let Some(names) = &names {
assert_eq!(names.operands, operands.then(Operands::default));
}
if !ended {
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
}
assert_eq!(cb.commit(on), Ok(()));
assert_eq!(cb.wait_until_completed(on), Ok(()));
assert_eq!(cb.status(), CommandBufferStatus::COMPLETED);
let mut pixels = [0; 64];
target.read_pixels(&mut pixels, 16);
// SAFETY: the Shared result buffer is mapped for eight bytes and the GPU has finished.
let samples =
u64::from_le_bytes(unsafe { results.contents().as_ptr::<[u8; 8]>().read() });
Ok((
pixels,
samples,
refused,
names.map(|names| names.bound_buffers),
))
};
if case != DrawBatchCase::Existing {
let (draws, colour, samples, refused) = match case {
DrawBatchCase::Unbind => (
vec![
draw_a,
VertexDraw {
buffer: None,
..draw_a
},
next_a,
],
cyan,
32,
[0, 1, 0],
),
DrawBatchCase::Gap => (
vec![
draw_a,
VertexDraw {
primitive_type: 1,
vertex_count: 2,
..draw_b
},
next_a,
],
cyan,
32,
[0, 0, 1],
),
DrawBatchCase::Names => (vec![draw_a, next_a, draw_b, draw_b], blue, 64, [0, 0, 0]),
DrawBatchCase::Existing => unreachable!("handled by the cases below"),
};
let batch = render(&draws, true, true, false, false)?;
assert_eq!(batch, render(&draws, false, true, false, false)?);
let mut bound = Ids::default();
bound.add(7);
match case {
DrawBatchCase::Gap => bound.add(0),
DrawBatchCase::Names => {
bound.add(0);
bound.add(0);
}
_ => {}
}
assert_eq!(
batch,
(
std::array::from_fn(|i| colour[i % 4]),
samples,
refused,
Some(bound)
)
);
return Ok(());
}
for (draws, operands, no_pipeline, ended, colour, samples, refusals) in [
(&[][..], false, false, false, red, 0, 0),
(&[draw_a, next_a][..], false, false, false, cyan, 32, 0),
(
&[draw_a, next_a, draw_b][..],
false,
false,
false,
blue,
48,
0,
),
(
&[draw_a, next_a, draw_b][..],
true,
false,
false,
blue,
48,
0,
),
(&[draw_a, bad_bind][..], false, false, false, green, 32, 1),
(
&[draw_a, bad_bind, next_a][..],
false,
false,
false,
cyan,
48,
1,
),
(
&[draw_a, bad_draw, bad_bind][..],
false,
false,
false,
blue,
32,
2,
),
(&[draw_a, draw_b][..], false, true, false, red, 0, 2),
(&[draw_a, draw_b][..], false, false, true, red, 0, 4),
(&[][..], false, false, true, red, 0, 0),
] {
let batch = render(draws, true, operands, no_pipeline, ended)?;
assert_eq!(batch, render(draws, false, operands, no_pipeline, ended)?);
assert_eq!(
(batch.0, batch.1, batch.2[0]),
(std::array::from_fn(|i| colour[i % 4]), samples, refusals)
);
}
Ok(())
}
#[test]
fn draw_batches_sync_a_copied_vertex_buffer_on_vulkan() -> Result<(), &'static str> {
use crate::core::host::HostPtr;
use crate::core::num::ToUsize as _;
use crate::core::platform::HostRange;
use std::alloc::{Layout, alloc_zeroed, dealloc};
let platform = RtPlatform::new();
let device = platform.system_default_device().ok_or("no Vulkan device")?;
let queue = device.new_command_queue().ok_or("no command queue")?;
let on = OnFault::Return;
let page = device.facts().page_size;
let layout =
Layout::from_size_align(page.to_usize(), page.to_usize()).map_err(|_| "page layout")?;
// SAFETY: the page layout has nonzero size.
let memory = HostPtr::from_ptr(unsafe { alloc_zeroed(layout) });
if memory == HostPtr::from_ptr(std::ptr::null_mut::<u8>()) {
return Err("page allocation");
}
// SAFETY: the page lives until the buffer's deallocator runs.
let bytes = unsafe { HostRange::new(memory, page) };
let buffer = device
.new_buffer_over_host_memory(
on,
bytes,
super::super::buffer::READ_ONLY,
// SAFETY: this frees the page once the copy and its users let it go.
Some(Box::new(move || unsafe {
dealloc(memory.as_ptr(), layout)
})),
)
.map_err(|_| "buffer creation raised")?
.ok_or("no copied buffer")?;
assert!(buffer.copied().is_some());
assert!(super::super::copied::any());
let green = [0, 255, 0, 255];
let data = vertices(&[green]);
// SAFETY: the vertices fit in the mapped page, and the copy was already initialized.
unsafe {
memory
.as_ptr::<u8>()
.copy_from_nonoverlapping(data.as_ptr(), data.len())
};
let state = vdesc_state(&device, &function(&device, COLOR, "render_color"));
let target = device
.new_texture(
on,
&platform.texture_descriptor(&TextureDesc {
width: 4,
height: 4,
usage: 5,
..TextureDesc::default()
}),
)
.map_err(|_| "texture creation raised")?
.ok_or("no render target")?;
let pass = pass(&target, 2);
let commands = queue
.command_buffer(on)
.map_err(|_| "command buffer raised")?
.ok_or("no command buffer")?;
let encoder = commands
.render_encoder(on, &pass)
.map_err(|_| "render encoder raised")?
.ok_or("no render encoder")?;
assert_eq!(
encoder.encode(
on,
RenderCmd::SetRenderPipelineState {
pipeline_state: Some(&state)
}
),
Ok(())
);
assert_eq!(
encoder.encode_draws(
on,
&[VertexDraw {
buffer: Some(&buffer),
offset: 0,
index: 0,
primitive_type: TRIANGLE,
vertex_start: 0,
vertex_count: 3,
}]
),
Ok(())
);
assert_eq!(encoder.encode(on, RenderCmd::EndEncoding), Ok(()));
assert_eq!(commands.commit(on), Ok(()));
assert_eq!(commands.wait_until_completed(on), Ok(()));
assert_eq!(commands.status(), CommandBufferStatus::COMPLETED);
let mut pixels = [0; 64];
target.read_pixels(&mut pixels, 16);
assert_eq!(pixels, std::array::from_fn(|i| green[i % 4]));
Ok(())
}
/// A run of `encoding` holds the encoder: the run's own commands go through and draw, and a
/// command another thread sends meanwhile waits for the run to end, then goes through.
#[test]
+1
View File
@@ -31,6 +31,7 @@ libc.workspace = true
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_System_Com",
"Win32_System_Threading",
"Win32_UI_Shell",
] }
+4 -2
View File
@@ -743,8 +743,10 @@ runtime's own device. The switches above apply, and `resolution=` too.
the host's arrow shows over the window, and a minimized window is
restored and raised. Where the window draws no more (its GPU lost, or no
swapchain), the question shows in SDL's message box instead: zenity's
where zenity is installed, else SDL's own X11 dialog. On Windows a task
dialog the window owns, Turn Off left of Cancel. Turn Off asks the host
where zenity is installed, else SDL's own X11 dialog. On Windows,
Reims-Go can handle the close in its own dialog with Shut down, Suspend
and Cancel. When the client handoff fails, SDL shows a task dialog the
window owns, Turn Off left of Cancel. Turn Off asks the host
to end the VM; Cancel, or the question dismissed, leaves the window and
the VM running, nothing held in the guest and the input released. From
the close to the answer nothing of the window's input reaches the guest:
+15
View File
@@ -4,6 +4,8 @@
//! shutdown request with the power-off action, which the guest is not asked about). So the window
//! asks first, in a question of the host OS's own over the window ([`QUESTION`], [`DETAIL`]), with
//! two answers: [`CANCEL`], the default, keeps the VM running, and [`TURN_OFF`] tells the host.
//! A Windows VM started by Reims-Go can hand the question to its client
//! instead. The client then handles the chosen action.
//!
//! **When it asks** ([`Asks::request`]): only where the host would hear of the close, while the
//! window lives (the display's release takes the host's callbacks back) and the host gave a close
@@ -55,6 +57,9 @@ pub(crate) enum Answer {
Cancel,
/// No question could show: nothing happens, as for Cancel, and the OS's side logs why.
Unshown,
/// Reims-Go's dialog handles the close.
#[cfg(target_os = "windows")]
Delegated,
}
/// The process's questions: whether one is open, and whether the person has chosen Turn Off.
@@ -108,6 +113,8 @@ pub(crate) fn answered(answer: Answer) -> bool {
Answer::TurnOff => "the person chose Turn Off: the host turns the VM off",
Answer::Cancel => "the close is cancelled, or its window ended: the host is not told",
Answer::Unshown => "no question showed: the host is not told, and the VM runs on",
#[cfg(target_os = "windows")]
Answer::Delegated => "the close question was handed to Reims-Go",
};
log::info!(target: "reims_vgpu_window", "{said}");
tell
@@ -144,5 +151,13 @@ mod tests {
assert_eq!(unshown.request(true), Step::Ask);
assert!(!unshown.answered(Answer::Unshown));
assert_eq!(unshown.request(true), Step::Ask);
#[cfg(target_os = "windows")]
{
let mut delegated = Asks::default();
assert_eq!(delegated.request(true), Step::Ask);
assert!(!delegated.answered(Answer::Delegated));
assert_eq!(delegated.request(true), Step::Ask);
}
}
}
@@ -657,6 +657,8 @@ fn ask_in_a_dialog(id: u64, ids: Vec<u64>) {
super::ui::post(move || {
let parent = shell::with_shell(id, |s| (!s.closed).then_some(s.sdl)).flatten();
let answer = match parent {
#[cfg(target_os = "windows")]
Some(_) if super::super::windows::request_client_close() => Answer::Delegated,
Some(parent) => question(parent),
None => Answer::Cancel,
};
@@ -46,6 +46,8 @@ use std::cell::Cell;
use std::ffi::c_void;
use std::io::Write;
use std::net::{SocketAddr, TcpStream};
use std::os::windows::process::CommandExt;
use std::process::Command;
use std::ptr::{NonNull, null, null_mut};
use std::sync::OnceLock;
use std::sync::mpsc::{self, RecvTimeoutError, SyncSender};
@@ -61,6 +63,7 @@ use windows_sys::Win32::System::Com::{
CLSCTX_INPROC_SERVER, COINIT_APARTMENTTHREADED, CoCreateInstance, CoInitializeEx,
CoUninitialize,
};
use windows_sys::Win32::System::Threading::CREATE_NO_WINDOW;
use windows_sys::Win32::UI::Shell::TaskbarList;
use windows_sys::core::{BOOL, GUID, HRESULT};
@@ -69,6 +72,22 @@ use crate::capture::HostOs;
/// The OS whose names the title gives the release chord's keys: Ctrl+Alt+Win (the module doc).
pub(super) const HOST_OS: HostOs = HostOs::Windows;
/// Asks the Reims-Go desktop instance that started this VM to show its
/// close dialog. A failed handoff leaves the SDL dialog available.
pub(super) fn request_client_close() -> bool {
let Some(executable) = std::env::var_os("REIMS_GO_VM_CLOSE_EXE") else {
return false;
};
let Ok(name) = std::env::var("REIMS_GO_VM_CLOSE_NAME") else {
return false;
};
Command::new(executable)
.arg(format!("--close-vm={name}"))
.creation_flags(CREATE_NO_WINDOW)
.status()
.is_ok_and(|status| status.success())
}
/// Win32 MSG layout matching winuser.h for SDL_SetWindowsMessageHook.
#[repr(C)]
struct Win32Msg {
+1
View File
@@ -1,5 +1,6 @@
{
"capabilities": [
"client-window-close",
"display-fixed-mode",
"nested-virt-nonfatal",
"vm-suspend",
Vendored
+1 -1
Submodule vendor/qemu updated: c67660108a...e6d7cb7422.