✅ Retarget the surface-plane tests to the buffer creator

The tests of what a texture over a surface's plane does (its formats,
planes, usages, sampling, resolves, rotations, YCbCr reads and identifiers)
made their surfaces as host-OS IOSurfaces, which no production caller has
made since 110b53637. The live creator, new_texture_over_surface_plane, runs
the same machinery over a buffer and the plane's shape, so the tests now make
a stand-in: a buffer of the surface's bytes with its facts and planes
(resource.rs's StandIn), and keep their recorded Metal answers. The
device_lend tests make their out-of-order view of pages as the device's
views are made, with remap_runs_shared_overwrite.

The tests of the OS surfaces themselves go: buffers on surfaces, a
command buffer's retains and use counts of a surface, a texture's range
held until its command buffer completed, a released texture keeping its
surface's memory while imported, the pages a texture over a surface maps,
two buffers made over one surface at once, the creator's debug line
over a surface, an offset surface's base address, and the death of a write
the runtime refuses into a texture of 523 or 527, which only a texture over
an OS surface reached. The OS surfaces' own modules and their tests go
with them in the next commit.

Nothing the guest or host observes changes: only tests change.
This commit is contained in:
Anees Iqbal committed 2026-11-14 09:27:31 -08:00
1 parent a2e110a8db
commit 4585dc4e33
18 files changed
+611 -2264

No files matched your search

-409
View File
@@ -3379,372 +3379,6 @@ pub(crate) mod tests {
assert_eq!(d.raw.work_counts().host_deallocators_delayed, 0);
}
/// A texture on a surface, whose buffer imports the surface's memory at its base address,
/// released with the surface's last reference while a command buffer that binds the device's
/// heap set runs: that command buffer may read any live texture through its ID, and the
/// texture's texels lie in the runtime's shadow of them, an image of its own memory, which it
/// keeps until the command buffer completes, while the texture and its buffer go at the
/// release, Metal's moment, and with the buffer the deallocator runs, which drops the surface's
/// last reference. The runtime may free the buffer's import then, the command buffer still
/// running, as no command of it names the buffer or the texture. Whenever it frees it, the
/// surface's memory stays mapped until it did ([`crate::os::surface_memory_hold`]): read
/// unmapped, the device imports no more by their pointer than before the texture was made.
/// Where the device refuses the pointer and imports dma-bufs of the pages instead (RADV, for
/// any page with a file behind it), the import reads the file's pages the dma-buf pinned,
/// whatever is mapped at the address, and may outlive the mapping: the runtime drops the
/// keep-alive as it destroys the buffer's `VkBuffer`, then frees the dma-bufs' imports with the
/// pages (its `Imported`'s drop; 3 runs of 20 on the Radeon 780M, RADV, Mesa 26.2.4, read the
/// memory unmapped with the import live). The import is counted either way, and goes. Its own
/// memory, and a single range of pages the platform's VM mapped, which the test unmaps through
/// it as core's mapping's release would. Core makes no surface over such a range (a single
/// range is a page of the host's own RAM, which no hold defers), so the second case pins only
/// the unmap hold the surface's hold carries. An i915 execbuffer that lists an import whose
/// pages are unmapped fails, which ANV answers as the device lost (`crate::remap`'s docs): the
/// command buffer completes, and the memory is unmapped once the import was freed. The command
/// buffer reads another texture through its ID, so no command of it names the surface's.
/// Linux's: on macOS IOSurface's memory is the surface's own
#[cfg(target_os = "linux")]
#[test]
fn a_released_surface_texture_keeps_the_surfaces_memory_while_imported() {
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use crate::core::host::PhysicalMemoryRange;
use crate::core::num::ToU64 as _;
use crate::core::platform::blit::ResourceRef;
use crate::core::platform::command::{CommandBuffer, CommandQueue};
use crate::core::platform::compute::{ComputeCmd, ComputeEncoder};
use crate::core::platform::os::surface::{IoSurfaces as _, Surface as _, SurfaceSpec};
use crate::core::platform::os::vm::HostVm as _;
use crate::core::platform::resource::{Buffer, Library, Texture as _};
use crate::core::platform::types::{CommandBufferStatus, MtlSize, NsRange};
use crate::gpu::resource::tests::bgra;
/// The kernels that read a texture an argument buffer holds (`src/gpu/rgbx.metal`).
const RGBX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/rgbx.metallib"));
/// How long the kernel that keeps the GPU busy runs, and its fewest rounds, as the test
/// above sizes it.
const HOLD: Duration = Duration::from_millis(60);
const FEWEST: u32 = 1_000;
/// `MTLResourceUsageRead`.
const READ: u64 = 1;
/// The surface's bytes: 64 x 32 BGRA texels.
const LEN: u64 = 64 * 32 * 4;
let wait = Duration::from_secs(30);
// Whether `done` came true within `wait`, polled each millisecond.
let within = |done: &dyn Fn() -> bool| {
(0..wait.as_millis()).any(|_| {
done() || {
std::thread::sleep(Duration::from_millis(1));
false
}
}) || done()
};
let d = dev();
// The device's own checks import pages of their own: they end before the counts are read,
// so only the surfaces' imports move them.
settle_device_checks(&d);
let state = |metallib: &[u8], kernel: &str| {
let library = d.new_library(metallib).unwrap().unwrap().unwrap();
let function = library.new_function(OnFault::Die, kernel).unwrap().unwrap();
d.new_compute_pipeline_state_for_function(Some(&function))
.unwrap()
.unwrap()
};
let buffer = |length: u64| {
d.new_buffer_of_length(OnFault::Die, length, 0)
.unwrap()
.unwrap()
};
let spin = crate::gpu::spin::state(&d);
let held_read = state(RGBX, "rgbx_read_held_float");
let other = d
.new_texture(OnFault::Die, &bgra(4, 4, 0))
.unwrap()
.unwrap();
let queue = d.new_command_queue().unwrap();
let rounds = crate::gpu::spin::rounds_to_hold(&d, &queue, &spin, HOLD, FEWEST);
// Core's mapping of the guest's pages the second surface lies in, as a memory map's.
let vm = crate::remap::VulkanVm::new();
let pages = vm.allocate_anywhere(LEN).unwrap();
let over_pages = SurfaceSpec {
pixel_format: u32::from_be_bytes(*b"BGRA"),
alloc_size: LEN,
width: 64,
height: 32,
bytes_per_element: 4,
bytes_per_row: 64 * 4,
element_width: 1,
element_height: 1,
client_address_ranges: Some(vec![PhysicalMemoryRange {
physical_address: pages.addr().to_u64(),
physical_length: LEN,
}]),
..SurfaceSpec::default()
};
let surfaces = [
(crate::os::tests::bgra_surface(64, 32), false),
(
crate::os::OsSurfaces::new().create(&over_pages).unwrap(),
true,
),
];
// The device's imports of host memory now: by their pointer, of dma-bufs of the pages
// where the device refuses their pointer (RADV refuses any page with a file behind it, the
// surface's own memory among them: one chunk on the 7900 XTX and the 780M), and of the
// images the runtime lays over such a dma-buf.
let imports = || {
let counts = d.raw.work_counts();
(
counts.host_imports_live,
counts.dma_buf_memories_live,
counts.dma_buf_image_memories_live,
)
};
for (surface, cores) in surfaces {
let base = surface.base_address();
let before = imports();
let texture = d
.new_texture_on_surface(&bgra(64, 32, 0), Some(&surface), 0)
.unwrap()
.unwrap();
let (pointers, dma_bufs, images) = imports();
// The buffer standing for the surface imports its pages once, by their pointer or as
// a dma-buf. Where the runtime takes the texture in place over that dma-buf, its image
// imports the same pages a second time (a Radeon 780M, 2026-11-07), and where it does
// not, the image imports nothing.
assert_eq!(
pointers + dma_bufs,
before.0 + before.1 + 1,
"imported (core's mapping: {cores})"
);
assert!(
images == before.2 || images == before.2 + 1,
"the texture's image imported at most once (core's mapping: {cores})"
);
// Whether the surface's memory is mapped, or the device no longer imports it by its
// pointer: read in that order, as the runtime frees such an import before it lets the
// memory go. A dma-buf's import may outlive the mapping (the test's docs).
let mapped_while_imported = || crate::os::mapped(base) || imports().0 == before.0;
let (words, read, held) = (buffer(16), buffer(16), buffer(8));
let word = |i: usize| {
// SAFETY: one of the buffer's four words, which the kernel reads and writes.
unsafe { AtomicU32::from_ptr(words.contents().as_ptr::<u32>().add(i)) }
};
word(0).store(rounds, Ordering::SeqCst);
// SAFETY: the argument buffer's 8 bytes, which no command uses yet.
unsafe {
held.contents()
.as_ptr::<u64>()
.write(other.gpu_resource_id())
};
let cb = queue.command_buffer(OnFault::Die).unwrap().unwrap();
let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap();
let resident = [Some(ResourceRef::Texture(&other))];
let one = MtlSize::new(1, 1, 1);
for cmd in [
ComputeCmd::SetComputePipelineState { state: Some(&spin) },
ComputeCmd::SetBuffers {
buffers: &[Some(&words)],
offsets: &[0],
range: NsRange::new(0, 1),
},
ComputeCmd::DispatchThreads {
threads_per_grid: one,
threads_per_threadgroup: one,
},
ComputeCmd::SetComputePipelineState {
state: Some(&held_read),
},
ComputeCmd::SetBuffers {
buffers: &[Some(&read), Some(&held)],
offsets: &[0, 0],
range: NsRange::new(0, 2),
},
ComputeCmd::UseResources {
resources: &resident,
usage: READ,
},
ComputeCmd::DispatchThreads {
threads_per_grid: one,
threads_per_threadgroup: one,
},
ComputeCmd::EndEncoding,
] {
e.encode(OnFault::Die, cmd).unwrap();
}
cb.commit(OnFault::Die).unwrap();
cb.wait_until_scheduled().unwrap();
let running = word(1).load(Ordering::SeqCst) == 0;
drop((texture, surface));
// Core's mapping's release (`Teardown::Vm`), once the surface went.
let unmapped = !cores
|| crate::remap::VulkanVm::new()
.deallocate(pages, LEN)
.is_success();
let after_the_release = mapped_while_imported();
assert!(
running,
"released while the kernel ran (core's mapping: {cores})"
);
assert_eq!(
word(1).load(Ordering::SeqCst),
0,
"checked while the kernel ran (core's mapping: {cores})"
);
assert!(unmapped, "core's unmap answers success");
assert!(
after_the_release,
"the surface's memory stays mapped while the device imports it (core's mapping: \
{cores})"
);
let ended = [CommandBufferStatus::COMPLETED, CommandBufferStatus::ERROR];
assert!(
within(&|| {
assert!(
mapped_while_imported(),
"mapped while imported (core's mapping: {cores})"
);
ended.contains(&cb.status())
}),
"the command buffer did not complete"
);
assert_eq!(
cb.status(),
CommandBufferStatus::COMPLETED,
"{:?}",
cb.error()
);
assert!(
within(&|| {
assert!(
mapped_while_imported(),
"mapped while imported (core's mapping: {cores})"
);
!crate::os::mapped(base)
}),
"unmapped once the import was freed (core's mapping: {cores})"
);
assert!(
within(&|| imports() == before),
"freed (core's mapping: {cores})"
);
}
}
/// The buffers under textures over a surface over scattered pages of the guest's at an offset
/// lie over the surface's own view (`crate::os::surface_alias`): the textures map the guest's
/// pages no more, where each took a second view. Counted by the process's mappings of the
/// guest's pages' file, which every view of them mapped from it takes (`/proc/self/maps`), a
/// view through dma-bufs none. Linux's: on macOS IOSurface maps the surface
#[cfg(target_os = "linux")]
#[test]
fn textures_over_a_surface_map_its_pages_no_more() {
use crate::core::host::PhysicalMemoryRange;
use crate::core::num::ToU64 as _;
use crate::core::platform::os::surface::{IoSurfaces as _, SurfaceSpec};
use crate::core::platform::os::vm::HostVm as _;
use crate::gpu::resource::tests::bgra;
/// The guest's pages, each its own run in the surface's view.
const PAGES: u64 = 16;
let page = OsVm::new().page_size();
// The file of a mapping's line (its device and inode).
let file_of = |line: &str| {
let fields: Vec<&str> = line.split_whitespace().collect();
(fields[3].to_owned(), fields[4].to_owned())
};
let maps = || std::fs::read_to_string("/proc/self/maps").unwrap();
let d = dev();
let (width, height) = (64, 255);
// Pages of a file of their own, which no other mapping shares.
let guest = crate::os::allocate_aliasable(PAGES * page).unwrap();
let first = guest.addr().to_u64();
let file = (maps().lines())
.find(|line| {
let range = line.split_whitespace().next().unwrap();
let (low, high) = range.split_once('-').unwrap();
let low = u64::from_str_radix(low, 16).unwrap();
let high = u64::from_str_radix(high, 16).unwrap();
(low..high).contains(&first)
})
.map(file_of)
.unwrap();
// The process's mappings of that file.
let mappings = || {
(maps().lines())
.filter(|line| file_of(line) == file)
.count()
.to_u64()
};
let spec = SurfaceSpec {
pixel_format: u32::from_be_bytes(*b"BGRA"),
offset: 0x40,
alloc_size: PAGES * page,
width,
height,
bytes_per_element: 4,
bytes_per_row: width * 4,
element_width: 1,
element_height: 1,
client_address_ranges: Some(
(0..PAGES)
.rev()
.map(|i| PhysicalMemoryRange {
physical_address: first + i * page,
physical_length: page,
})
.collect(),
),
..SurfaceSpec::default()
};
assert_eq!(mappings(), 1, "the guest's pages");
// A view through dma-bufs maps none of the file's pages itself.
let view = match crate::os::views_through_dma_bufs() {
true => 0,
false => PAGES,
};
let surface = crate::os::OsSurfaces::new().create(&spec).unwrap();
assert_eq!(mappings(), 1 + view, "the view");
let textures: Vec<_> = (0..2)
.map(|_| {
d.new_texture_on_surface(&bgra(width, height, 0), Some(&surface), 0)
.unwrap()
.unwrap()
})
.collect();
assert_eq!(mappings(), 1 + view, "the view, and no more");
drop((textures, surface));
// The pages are left mapped: the runtime may hold an import of them a while longer.
}
/// Every handle to one runtime device is one object
/// Buffers made over one surface on two threads at once are both made, at the surface's address, whichever is made first: the
/// second shares the first's range once the first is made, and none sees the address held
/// with no live buffer to share
#[test]
fn buffers_made_over_a_surface_at_once_are_both_made() {
let d = dev();
for round in 0..64 {
let surface = crate::os::tests::bgra_surface(64, 64);
let started = std::sync::Barrier::new(2);
let made = || {
started.wait();
catch_death(|| d.new_buffer_on_surface(Some(&surface)).unwrap().unwrap())
.map_err(|site| (site.kind, site.file))
};
let (one, two) = std::thread::scope(|s| {
let other = s.spawn(made);
(made(), other.join().unwrap())
});
let (one, two) = (one.unwrap(), two.unwrap());
use crate::core::platform::resource::Buffer as _;
assert_eq!(one.gpu_address(), two.gpu_address(), "round {round}");
}
}
#[test]
fn a_device_is_one_object() {
let d = dev();
@@ -3766,49 +3400,6 @@ pub(crate) mod tests {
assert_eq!(opened.map(|o| o.id()), Some(d.id()));
}
/// The debug line of a texture over a surface names the descriptor's format, raw and by
/// name, the plane, the size, the usage (the runtime's flags and the raw bits beside them)
/// and the storage mode, then the surface's OSType, its plane count and each plane's size
/// and rows, or the surface's own for a surface of no planes
#[test]
fn a_texture_over_a_surface_has_a_debug_line_of_its_shape() {
use crate::core::platform::values::TextureDesc;
let fields = |pixel_format, (width, height), usage, resource_options| {
TextureFields::of(&TextureDesc {
texture_type: 2,
pixel_format,
width,
height,
usage,
resource_options: Some(resource_options),
..TextureDesc::default()
})
};
let x420 = crate::gpu::ycbcr::measure::Shape::of(b"x420").surface((40, 24));
let line = OnSurface {
fields: &fields(505, (40, 24), 0x9, 0x20),
surface: &x420,
plane: 1,
};
assert_eq!(
line.to_string(),
"newTextureWithDescriptor:iosurface:plane: format 505 MTLPixelFormatYCBCR10_420_2P, \
plane 1, 40x24, usage 0x9, storage 2; surface 'x420', 2 planes: plane 0 40x24, 128 \
bytes per row; plane 1 20x12, 128 bytes per row"
);
let bgra = crate::os::tests::bgra_surface(16, 8);
let line = OnSurface {
fields: &fields(80, (16, 8), 0x1, 0),
surface: &bgra,
plane: 0,
};
assert_eq!(
line.to_string(),
"newTextureWithDescriptor:iosurface:plane: format 80 MTLPixelFormatBGRA8Unorm, plane \
0, 16x8, usage 0x1, storage 0; surface 'BGRA', 0 planes: 16x8, 64 bytes per row"
);
}
/// A compute pipeline the runtime refuses for a gap of its own or of the device's is, by
/// default, nil and the runtime's refusal as the `NSError`, relayed; in strict mode it dies
/// at its selector as before. The creators' decision, without a device
@@ -1,6 +1,10 @@
//! The tests of `device` that compare with Metal on this host: macOS only.
//! The tests of `device` that compare with Metal on this host: macOS only. A surface is the
//! buffer that stands for it ([`StandIn`]), as the reims-graphics device's surfaces reach this
//! platform.
use super::*;
use crate::gpu::resource::tests::StandIn;
use crate::gpu::ycbcr::measure::Surface;
/// A reservation keeps its IDs from plain allocation of textures, sampler states and
/// indirect command buffers, as Metal's does: only a type's first call counts, and none made
@@ -70,18 +74,17 @@ fn reservations_keep_ids_from_plain_allocation() {
);
}
/// A `YCBCR8_420_2P` texture of `size` over plane `plane` of `surface` on the device `d`, as the
/// guest's creator makes it.
/// A `YCBCR8_420_2P` texture of `size` over plane `plane` of `surface`, as the guest's creator
/// makes it.
fn ycbcr8_420_on(
d: &VulkanDevice,
surface: &OsSurface,
surface: &Surface,
plane: u64,
size: (u64, u64),
) -> RaiseResult<Option<VulkanTexture>> {
use crate::core::platform::Platform as _;
let desc = crate::platform::tests::platform()
.texture_descriptor(&crate::gpu::ycbcr::measure::desc(500, size));
d.new_texture_on_surface(&desc, Some(surface), plane)
surface.texture(&desc, plane)
}
/// A probe of [`linear_samples`]: its grid, where it starts and its step, in texels.
@@ -240,11 +243,10 @@ fn linear_samples<P: crate::core::platform::Platform>(
ignore = "MoltenVK: the runtime records pixel-sampler-scaling, a death in strict mode; Mac-only test, off everywhere; ledger: MoltenVK strict deaths"
)]
fn ycbcr8_420_textures_over_surfaces_read_as_metals() {
use crate::gpu::ycbcr::measure::host::set_value;
use crate::gpu::ycbcr::measure::host::set_matrix;
use crate::gpu::ycbcr::measure::{
Shape, float_bits, float_texels, probe, read_floats, sampled_floats, texels,
};
use crate::os::MATRIX_KEY;
let d = dev();
let p = crate::platform::tests::platform();
for (ostype, size) in [(b"420v", (33, 17)), (b"420f", (64, 32))] {
@@ -258,12 +260,12 @@ fn ycbcr8_420_textures_over_surfaces_read_as_metals() {
];
for matrix in matrices {
let case = format!("{} {size:?} {matrix:?}", String::from_utf8_lossy(ostype));
let s = shape.surface(size);
let mut s = shape.surface(&d, size);
shape.fill_noise(&s, size, 7);
if let Some(m) = matrix {
set_value(&s, MATRIX_KEY, m);
set_matrix(&mut s, m);
}
let t = ycbcr8_420_on(&d, &s, 0, size).unwrap().unwrap();
let t = ycbcr8_420_on(&s, 0, size).unwrap().unwrap();
let read = read_floats::<VulkanPlatform>(&d, &t, size);
let centres = probe((0.5, 0.5), 1.0, size, false, 0);
let nearest = (0, 0, false, 0);
@@ -323,7 +325,7 @@ fn ycbcr8_420_samples_the_exact_filter_does_not_reach_die() {
let p = crate::platform::tests::platform();
let size = (33, 17);
let shape = Shape::of(b"420v");
let s = shape.surface(size);
let s = shape.surface(&d, size);
shape.fill_noise(&s, size, 7);
let mut swizzled = desc(500, size);
swizzled.swizzle = Some(Swizzle {
@@ -332,8 +334,8 @@ fn ycbcr8_420_samples_the_exact_filter_does_not_reach_die() {
blue: 2,
alpha: 5,
});
let t = d
.new_texture_on_surface(&p.texture_descriptor(&swizzled), Some(&s), 0)
let t = s
.texture(&p.texture_descriptor(&swizzled), 0)
.unwrap()
.unwrap();
let sampler = linear::<VulkanPlatform>(&d, false, false);
@@ -407,14 +409,14 @@ fn xr10_desc(
/// A texture of [`xr10_desc`] over plane `plane` of `surface`, made by this platform.
fn xr10_over(
format: u64,
surface: &crate::os::OsSurface,
surface: &Surface,
plane: u64,
(size, options): ((u64, u64), u64),
) -> RaiseResult<Option<VulkanTexture>> {
use crate::core::platform::Platform as _;
let p = crate::platform::tests::platform();
let desc = p.texture_descriptor(&xr10_desc(format, size, options));
dev().new_texture_on_surface(&desc, Some(surface), plane)
surface.texture(&desc, plane)
}
/// A texture of a two-plane XR10 format (550, 551) over plane 0 of a 'b3a8' surface, its
@@ -486,7 +488,7 @@ fn two_plane_xr10_textures_over_unaligned_planes_are_metals() {
for format in [550, 551] {
for (rows, seed) in [((132, 36), 7), ((136, 40), 8)] {
let case = format!("{format} rows {rows:?}");
let s = noisy_surface(&b3a8_spec(size, rows), seed);
let s = noisy_surface(b3a8_spec(size, rows), seed);
*crate::answer::LAST_LINE.lock() = None;
let site = catch_death(|| xr10_over(format, &s, 0, (size, 0x10))).unwrap_err();
let line = crate::answer::LAST_LINE.lock().take().unwrap_or_default();
@@ -498,7 +500,7 @@ fn two_plane_xr10_textures_over_unaligned_planes_are_metals() {
[((192, 64), 192 * 17 + 8, 9), ((144, 48), 144 * 17 + 4, 10)]
{
let case = format!("{format} rows {rows:?} plane 1 at {alpha_offset}");
let s = noisy_surface(&b3a8_spec_at(size, rows, alpha_offset), seed);
let s = noisy_surface(b3a8_spec_at(size, rows, alpha_offset), seed);
let t = xr10_over(format, &s, 0, (size, 0x10)).unwrap().unwrap();
assert_eq!(t.pixel_format(), format, "{case}");
let ours = bits(read_floats::<VulkanPlatform>(&d, &t, size));
@@ -524,8 +526,8 @@ fn two_plane_xr10_textures_the_runtime_refuses_die() {
use crate::core::platform::Platform as _;
let size = (16, 16);
let two = b3a8(size, (64, 64), 5);
let one = crate::os::tests::bgra_surface(16, 16);
let other = crate::gpu::ycbcr::measure::Shape::of(b"420v").surface(size);
let one = StandIn::<VulkanPlatform>::bgra(&dev(), 16, 16);
let other = crate::gpu::ycbcr::measure::Shape::of(b"420v").surface(&dev(), size);
let sel = "newTextureWithDescriptor:iosurface:plane:";
let refused = |case: &str, made: &dyn Fn() -> RaiseResult<Option<VulkanTexture>>| {
*crate::answer::LAST_LINE.lock() = None;
@@ -553,9 +555,7 @@ fn two_plane_xr10_textures_the_runtime_refuses_die() {
};
let case = format!("{format} rotated");
let p = crate::platform::tests::platform();
refused(&case, &|| {
dev().new_texture_on_surface(&p.texture_descriptor(&rotated), Some(&two), 0)
});
refused(&case, &|| two.texture(&p.texture_descriptor(&rotated), 0));
}
}
@@ -563,11 +563,11 @@ fn two_plane_xr10_textures_the_runtime_refuses_die() {
/// `RenderTarget` usage too (E26d's 0x5), after a pass of platform `p` that clears it to
/// `color` and stores it: the surface's bytes from its base address to `length`, once the
/// command buffer completed.
fn cleared<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
fn cleared<P: crate::core::platform::Platform>(
p: &P,
d: &P::Device,
format: u64,
surface: &crate::os::OsSurface,
surface: &StandIn<P>,
(size, options): ((u64, u64), u64),
color: crate::core::platform::types::ClearColor,
length: u64,
@@ -578,8 +578,8 @@ fn cleared<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
use crate::core::platform::values::ColorAttachmentSet;
let mut desc = xr10_desc(format, size, options);
desc.usage = 0x5;
let t = d
.new_texture_on_surface(&p.texture_descriptor(&desc), Some(surface), 0)
let t = surface
.texture(&p.texture_descriptor(&desc), 0)
.unwrap()
.unwrap();
let pass = p.render_pass_descriptor();
@@ -602,8 +602,7 @@ fn cleared<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
cb.commit(OnFault::Die).unwrap();
cb.wait_until_completed(OnFault::Die).unwrap();
assert_eq!(cb.error(), None);
use crate::core::platform::os::surface::Surface as _;
let base = surface.base_address().as_ptr::<u8>();
let base = surface.base();
let length = usize::try_from(length).unwrap();
// SAFETY: the surface's bytes, read after the command buffer that wrote them completed.
unsafe { std::slice::from_raw_parts(base, length) }.to_vec()
@@ -652,11 +651,11 @@ enum Pattern<'a> {
/// `surface` (`size`, `options`) with `pattern` writes on `p`'s device `d`: the surface's
/// bytes from its base address to `length`, once the command buffer completed.
#[allow(clippy::too_many_arguments)]
fn filled<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
fn filled<P: crate::core::platform::Platform>(
p: &P,
d: &P::Device,
format: u64,
surface: &crate::os::OsSurface,
surface: &StandIn<P>,
(size, options): ((u64, u64), u64),
([x, y], [w, h]): ([u64; 2], [u64; 2]),
pattern: Pattern<'_>,
@@ -665,13 +664,9 @@ fn filled<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
use crate::core::platform::HostRange;
use crate::core::platform::blit::{BlitCmd, BlitEncoder as _};
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::os::surface::Surface as _;
use crate::core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
let desc = p.texture_descriptor(&xr10_desc(format, size, options));
let t = d
.new_texture_on_surface(&desc, Some(surface), 0)
.unwrap()
.unwrap();
let t = surface.texture(&desc, 0).unwrap().unwrap();
let q = d.new_command_queue().unwrap();
let cb = q.command_buffer(OnFault::Die).unwrap().unwrap();
let e = cb.blit_encoder(OnFault::Die).unwrap().unwrap();
@@ -698,7 +693,7 @@ fn filled<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
cb.commit(OnFault::Die).unwrap();
cb.wait_until_completed(OnFault::Die).unwrap();
assert_eq!(cb.error(), None);
let base = surface.base_address().as_ptr::<u8>();
let base = surface.base();
let length = usize::try_from(length).unwrap();
// SAFETY: the surface's bytes, read after the command buffer that wrote them completed.
unsafe { std::slice::from_raw_parts(base, length) }.to_vec()
@@ -780,7 +775,7 @@ impl Memory {
/// blit encoder, of a texture of `format` over `memory` (a surface's of luma `size`, or a
/// buffer's rows of `size`) write on `p`'s device `d`: every byte of the memory, which starts as
/// `i * 37 % 251` at byte `i` on every platform, once the command buffer completed.
fn memory_fill_on<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
fn memory_fill_on<P: crate::core::platform::Platform>(
p: &P,
d: &P::Device,
(format, size, memory): (u64, (u64, u64), Memory),
@@ -789,7 +784,6 @@ fn memory_fill_on<P: crate::core::platform::Platform<Surface = crate::os::OsSurf
use crate::core::platform::HostRange;
use crate::core::platform::blit::{BlitCmd, BlitEncoder as _};
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::os::surface::Surface as _;
use crate::core::platform::resource::Buffer as _;
use crate::core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
let texture_size = memory.texture_size(size);
@@ -806,10 +800,12 @@ fn memory_fill_on<P: crate::core::platform::Platform<Surface = crate::os::OsSurf
let (surface, buffer, t, length);
match memory {
Memory::Plane(ostype, plane) => {
let made = crate::gpu::ycbcr::measure::Shape::of(ostype).surface(size);
length = made.alloc_size();
write(made.base_address().as_ptr::<u8>(), length);
t = d.new_texture_on_surface(&desc, Some(&made), plane);
let shape = crate::gpu::ycbcr::measure::Shape::of(ostype);
let (facts, planes, alloc_size) = shape.layout(size);
let made = StandIn::<P>::shared(d, facts, planes, alloc_size);
length = alloc_size;
write(made.base(), length);
t = made.texture(&desc, plane);
(surface, buffer) = (Some(made), None);
}
Memory::Buffer(row) => {
@@ -853,13 +849,13 @@ fn memory_fill_on<P: crate::core::platform::Platform<Surface = crate::os::OsSurf
cb.wait_until_completed(OnFault::Die).unwrap();
assert_eq!(cb.error(), None);
let base = match (&surface, &buffer) {
(Some(s), _) => s.base_address(),
(_, Some(b)) => b.contents(),
(Some(s), _) => s.base(),
(_, Some(b)) => b.contents().as_ptr::<u8>(),
_ => unreachable!(),
};
let length = usize::try_from(length).unwrap();
// SAFETY: the memory's bytes, read after the command buffer that wrote them completed.
unsafe { std::slice::from_raw_parts(base.as_ptr::<u8>(), length) }.to_vec()
unsafe { std::slice::from_raw_parts(base, length) }.to_vec()
}
/// The textures [`fills_of_ycbcr_and_padded_textures_are_metals`] fills, of `size`: of each
@@ -999,13 +995,10 @@ fn copy_region<'a, P: crate::core::platform::Platform>(
}
}
/// The bytes of `surface` from its base address to `length`.
fn surface_bytes(surface: &crate::os::OsSurface, length: u64) -> Vec<u8> {
use crate::core::platform::os::surface::Surface as _;
let base = surface.base_address().as_ptr::<u8>();
let length = usize::try_from(length).unwrap();
// SAFETY: the surface's bytes, read after the command buffers that wrote them completed.
unsafe { std::slice::from_raw_parts(base, length) }.to_vec()
/// The bytes of `surface` from its base address to `length`, read after the command buffers that
/// wrote them completed.
fn surface_bytes<P: crate::core::platform::Platform>(surface: &StandIn<P>, length: u64) -> Vec<u8> {
surface.bytes(length)
}
/// What copies between textures of `format` (`size`, `Managed`) over plane 0 of 'b3a8'
@@ -1026,23 +1019,17 @@ fn surface_bytes(surface: &crate::os::OsSurface, length: u64) -> Vec<u8> {
/// times each at once, two copied zeros 1 and 2 times and four lost a command buffer to the
/// recovery; copying the top quarter, none in 240 copies of each format; one process alone
/// copying all of them, none in 200). The top quarter holds every byte the copy into `b` reads.
fn surface_copies<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
fn surface_copies<P: crate::core::platform::Platform>(
p: &P,
d: &P::Device,
format: u64,
(a, b): (&crate::os::OsSurface, &crate::os::OsSurface),
(a, b): (&StandIn<P>, &StandIn<P>),
size: (u64, u64),
length: u64,
) -> [Vec<u8>; 2] {
let over = p.texture_descriptor(&xr10_desc(format, size, 0x10));
let ta = d
.new_texture_on_surface(&over, Some(a), 0)
.unwrap()
.unwrap();
let tb = d
.new_texture_on_surface(&over, Some(b), 0)
.unwrap()
.unwrap();
let ta = a.texture(&over, 0).unwrap().unwrap();
let tb = b.texture(&over, 0).unwrap().unwrap();
// Metal's blit rows of a texture of its own memory are `⌊4 w / 16⌋ · 16` bytes apart, its
// planes' rows `4 w` and `w` rounded up to 16: at a width a multiple of 4 they hold every
// column, and no copy of it overlaps its rows or reads their padding, whose bytes Metal's
@@ -1100,17 +1087,9 @@ fn copies_between_two_plane_xr10_textures_over_surfaces_write_as_metals() {
#[test]
fn a_copy_within_a_two_plane_xr10_texture_over_a_surface_dies() {
use crate::core::platform::Platform;
fn within<P: Platform<Surface = crate::os::OsSurface>>(
p: &P,
d: &P::Device,
format: u64,
surface: &crate::os::OsSurface,
) {
fn within<P: Platform>(p: &P, d: &P::Device, format: u64, surface: &StandIn<P>) {
let over = p.texture_descriptor(&xr10_desc(format, (33, 17), 0x10));
let t = d
.new_texture_on_surface(&over, Some(surface), 0)
.unwrap()
.unwrap();
let t = surface.texture(&over, 0).unwrap().unwrap();
let q = d.new_command_queue().unwrap();
blit_one::<P>(&q, copy_region::<P>((&t, [0, 0]), (&t, [16, 8]), [8, 4]));
}
@@ -1229,8 +1208,8 @@ fn formats_the_runtime_lacks_die_where_textures_are_made() {
assert!(line.contains("Metal aborts at"), "{line}");
}
};
let x420 = crate::gpu::ycbcr::measure::Shape::of(b"x420").surface((16, 16));
let bgra = crate::os::tests::bgra_surface(16, 16);
let x420 = crate::gpu::ycbcr::measure::Shape::of(b"x420").surface(&dev(), (16, 16));
let bgra = StandIn::<VulkanPlatform>::bgra(&dev(), 16, 16);
for format in [576, 577, 578, 579, 624, 625, 626, 627, 630, 640, 650] {
let (private, shared) = (desc(format, 2), desc(format, 0));
let ours = p.texture_descriptor(&private);
@@ -1267,9 +1246,7 @@ fn formats_the_runtime_lacks_die_where_textures_are_made() {
});
let sel = "newTextureWithDescriptor:iosurface:plane:";
for (surface, plane) in [(&x420, 0), (&x420, 1), (&bgra, 0)] {
made(sel, &|| {
(dev().new_texture_on_surface(&ours, Some(surface), plane)).unwrap()
});
made(sel, &|| (surface.texture(&ours, plane)).unwrap());
}
let described =
crate::gpu::format_info::described("MTLPixelFormatGetInfoForDevice()", format);
@@ -1466,7 +1443,7 @@ fn packed_10_bit_textures_over_memory_die_named() {
assert!(line.contains(&named), "{sel}: {line}");
assert!(line.contains("which the runtime refuses"), "{sel}: {line}");
};
let surface = crate::os::tests::bgra_surface(64, 64);
let surface = StandIn::<VulkanPlatform>::bgra(&dev(), 64, 64);
for format in [588, 589] {
for storage in [0, 2] {
let desc = packed_10(format, storage, 1);
@@ -1490,7 +1467,7 @@ fn packed_10_bit_textures_over_memory_die_named() {
},
);
dies("newTextureWithDescriptor:iosurface:plane:", format, &|| {
drop(dev().new_texture_on_surface(&ours, Some(&surface), 0));
drop(surface.texture(&ours, 0));
});
}
}
@@ -1694,11 +1671,7 @@ fn write_swizzles_are_made_where_read_alone() {
}
// Each creator's texture's pixel format (0 for nil) of `desc` on `p`'s device `d`: the
// device's, the shared one, a buffer's two, a heap's and the IOSurface one.
fn made<P: Platform<Surface = OsSurface>>(
p: &P,
d: &P::Device,
desc: &TextureDesc,
) -> Vec<u64> {
fn made<P: Platform>(p: &P, d: &P::Device, desc: &TextureDesc) -> Vec<u64> {
let format = |t: Option<P::Texture>| t.map_or(0, |t| t.pixel_format());
let ours = p.texture_descriptor(desc);
let shared = p.texture_descriptor(&TextureDesc {
@@ -1706,10 +1679,10 @@ fn write_swizzles_are_made_where_read_alone() {
..*desc
});
let (buffer, heap) = memory::<P>(d);
let surface = crate::os::tests::bgra_surface(16, 16);
let surface = StandIn::<P>::bgra(d, 16, 16);
let on_buffer = buffer.new_texture(OnFault::Return, &shared, 0, 256);
let linear = buffer.new_linear_texture(&shared, 0, 256, 4096);
let on_surface = d.new_texture_on_surface(&shared, Some(&surface), 0);
let on_surface = surface.texture(&shared, 0);
vec![
format(d.new_texture(OnFault::Return, &ours).unwrap()),
format(d.new_shared_texture(&ours).unwrap()),
@@ -1730,7 +1703,7 @@ fn write_swizzles_are_made_where_read_alone() {
let written = p.texture_descriptor(&desc(usage, 2));
let shared = p.texture_descriptor(&desc(usage, 0));
let (buffer, heap) = memory::<VulkanPlatform>(&d);
let surface = crate::os::tests::bgra_surface(16, 16);
let surface = StandIn::<VulkanPlatform>::bgra(&dev(), 16, 16);
let creators: [(&str, &dyn Fn()); 6] = [
("newTextureWithDescriptor:", &|| {
let _ = d.new_texture(OnFault::Return, &written);
@@ -1751,7 +1724,7 @@ fn write_swizzles_are_made_where_read_alone() {
let _ = heap.new_texture(&written, 0);
}),
("newTextureWithDescriptor:iosurface:plane:", &|| {
let _ = d.new_texture_on_surface(&shared, Some(&surface), 0);
let _ = surface.texture(&shared, 0);
}),
];
for (sel, make) in creators {
@@ -1792,7 +1765,7 @@ fn texture_setters_act_where_metal_does() {
resource_options: Some(0x20),
..TextureDesc::default()
};
let surface = crate::os::tests::bgra_surface(16, 16);
let surface = StandIn::<VulkanPlatform>::bgra(&dev(), 16, 16);
let heap = |d: &VulkanDevice| {
let made = d.new_heap(&HeapDesc {
size: 1 << 20,
@@ -1836,7 +1809,7 @@ fn texture_setters_act_where_metal_does() {
let _ = heap.new_texture(&ours, 0);
}),
("newTextureWithDescriptor:iosurface:plane:", &|| {
let _ = d.new_texture_on_surface(&ours, Some(&surface), 0);
let _ = surface.texture(&ours, 0);
}),
];
for (sel, make) in creators {
@@ -1879,7 +1852,7 @@ fn texture_setters_act_where_metal_does() {
p: &P,
d: &P::Device,
desc: &TextureDesc,
surface: &P::Surface,
surface: &StandIn<P>,
heap: &P::Heap,
) -> Vec<String> {
let ours = p.texture_descriptor(desc);
@@ -1899,7 +1872,7 @@ fn texture_setters_act_where_metal_does() {
let mut out = vec![
made(d.new_texture(OnFault::Return, &ours).unwrap()),
made(d.new_shared_texture(&ours).unwrap()),
made(d.new_texture_on_surface(&ours, Some(surface), 0).unwrap()),
made(surface.texture(&ours, 0).unwrap()),
];
if !placed {
let size = d.heap_texture_size_and_align(&ours).unwrap();
@@ -1995,7 +1968,7 @@ fn invalid_formats_are_metals() {
assert_eq!((site.kind, site.file), (DeathKind::Abort, sel), "{line}");
assert!(line.contains("Metal aborts at"), "{format}: {line}");
};
let bgra = crate::os::tests::bgra_surface(16, 16);
let bgra = StandIn::<VulkanPlatform>::bgra(&dev(), 16, 16);
for format in [255, 262, 0] {
let (private, shared) = (desc(format, 2), desc(format, 0));
let ours = p.texture_descriptor(&private);
@@ -2017,7 +1990,7 @@ fn invalid_formats_are_metals() {
},
);
aborts("newTextureWithDescriptor:iosurface:plane:", format, &|| {
let _ = dev().new_texture_on_surface(&ours, Some(&bgra), 0);
let _ = bgra.texture(&ours, 0);
});
if format == 0 {
assert!(dev().new_shared_texture(&ours).unwrap().is_none());
@@ -2096,17 +2069,13 @@ fn textures_over_planes_a_surface_lacks_are_metals() {
(543, b"x420"),
] {
let desc = crate::gpu::ycbcr::measure::desc(format, size);
let two = crate::gpu::ycbcr::measure::Shape::of(ostype).surface(size);
let made = dev()
.new_texture_on_surface(&p.texture_descriptor(&desc), Some(&two), 2)
.unwrap();
let two = crate::gpu::ycbcr::measure::Shape::of(ostype).surface(&dev(), size);
let made = two.texture(&p.texture_descriptor(&desc), 2).unwrap();
assert!(made.is_none(), "{format}: plane 2 of a two-plane surface");
let one = crate::os::tests::bgra_surface(size.0, size.1);
let one = StandIn::<VulkanPlatform>::bgra(&dev(), size.0, size.1);
for plane in [1, 2] {
let site = catch_death(|| {
dev().new_texture_on_surface(&p.texture_descriptor(&desc), Some(&one), plane)
})
.unwrap_err();
let site =
catch_death(|| one.texture(&p.texture_descriptor(&desc), plane)).unwrap_err();
assert_eq!(
(site.kind, site.file),
(
@@ -2596,13 +2565,17 @@ pub(crate) fn device_with_own_cache() -> (VulkanDevice, OwnCache) {
(device, cache)
}
/// The spec of a 'b3a8' surface of `size` (`kCVPixelFormatType_30RGBLE_8A_BiPlanar`): plane 0
/// the 32-bit colour words, plane 1 the alpha bytes, rows `rows` bytes apart in each, plane 1
/// after plane 0 at a multiple of 4096.
/// The layout of a 'b3a8' surface of `size` (`kCVPixelFormatType_30RGBLE_8A_BiPlanar`): its
/// facts, its planes and its length. Plane 0 the 32-bit colour words, plane 1 the alpha bytes,
/// rows `rows` bytes apart in each, plane 1 after plane 0 at a multiple of 4096.
fn b3a8_spec(
size: (u64, u64),
rows: (u64, u64),
) -> crate::core::platform::os::surface::SurfaceSpec {
) -> (
crate::core::platform::values::SurfaceFacts,
Vec<(u64, u64)>,
u64,
) {
let alpha_offset = (rows.0 * size.1).next_multiple_of(4096);
b3a8_spec_at(size, rows, alpha_offset)
}
@@ -2612,58 +2585,41 @@ fn b3a8_spec_at(
size: (u64, u64),
rows: (u64, u64),
alpha_offset: u64,
) -> crate::core::platform::os::surface::SurfaceSpec {
use crate::core::platform::os::surface::{SurfacePlaneSpec, SurfaceSpec};
let (width, height) = size;
) -> (
crate::core::platform::values::SurfaceFacts,
Vec<(u64, u64)>,
u64,
) {
let (color_row, alpha_row) = rows;
let plane = |offset, bytes_per_row, bytes_per_element| SurfacePlaneSpec {
base: offset,
offset,
width,
height,
size: bytes_per_row * height,
bytes_per_row,
bytes_per_element,
element_width: 1,
element_height: 1,
..SurfacePlaneSpec::default()
};
SurfaceSpec {
planes: Some(vec![
plane(0, color_row, 4),
plane(alpha_offset, alpha_row, 1),
]),
pixel_format: u32::from_be_bytes(*b"b3a8"),
alloc_size: (alpha_offset + alpha_row * height).next_multiple_of(16384),
width,
height,
bytes_per_element: 4,
bytes_per_row: color_row,
element_width: 1,
element_height: 1,
..SurfaceSpec::default()
}
let planes = vec![(0, color_row), (alpha_offset, alpha_row)];
let facts = crate::gpu::resource::tests::facts_of(*b"b3a8", size, &planes);
let length = (alpha_offset + alpha_row * size.1).next_multiple_of(16384);
(facts, planes, length)
}
/// The surface of `spec`, every byte of its allocation `noise(seed)`'s.
/// The surface of `layout` ([`b3a8_spec`]), every byte `noise(seed)`'s, the buffer that stands
/// for it the process's device's.
fn noisy_surface(
spec: &crate::core::platform::os::surface::SurfaceSpec,
(facts, planes, length): (
crate::core::platform::values::SurfaceFacts,
Vec<(u64, u64)>,
u64,
),
seed: u64,
) -> crate::os::OsSurface {
use crate::core::platform::os::surface::{IoSurfaces as _, Surface as _};
let s = crate::os::OsSurfaces::new().create(spec).unwrap();
) -> Surface {
let s = Surface::shared(&dev(), facts, planes, length);
let mut next = crate::gpu::ycbcr::measure::noise(seed);
let base = s.base_address().as_ptr::<u8>();
for at in 0..usize::try_from(spec.alloc_size).unwrap() {
// SAFETY: inside the surface's allocation, which no GPU work uses yet.
let base = s.base();
for at in 0..usize::try_from(length).unwrap() {
// SAFETY: inside the buffer's Shared bytes, which no GPU work uses yet.
unsafe { base.add(at).write(next().to_le_bytes()[0]) };
}
s
}
/// A host-only 'b3a8' surface of [`b3a8_spec`], every byte `noise(seed)`'s.
fn b3a8(size: (u64, u64), rows: (u64, u64), seed: u64) -> crate::os::OsSurface {
noisy_surface(&b3a8_spec(size, rows), seed)
/// A 'b3a8' surface of [`b3a8_spec`], every byte `noise(seed)`'s.
fn b3a8(size: (u64, u64), rows: (u64, u64), seed: u64) -> Surface {
noisy_surface(b3a8_spec(size, rows), seed)
}
/// How [`read_through_another`] orders its two blits: in two encoders of one command buffer, or
@@ -2680,10 +2636,10 @@ enum Order {
/// texture, then a blit of the second texture's texels into a buffer, ordered as `order` says,
/// the buffer's bytes answered once both command buffers completed. The two textures are made
/// first, as a guest makes two over one surface.
fn read_through_another<P: crate::core::platform::Platform<Surface = crate::os::OsSurface>>(
fn read_through_another<P: crate::core::platform::Platform>(
p: &P,
d: &P::Device,
surface: &crate::os::OsSurface,
surface: &StandIn<P>,
((width, height), order): ((u64, u64), Order),
texels: &[u8],
) -> Vec<u8> {
@@ -2700,12 +2656,8 @@ fn read_through_another<P: crate::core::platform::Platform<Surface = crate::os::
usage: 1,
..crate::core::platform::values::TextureDesc::default()
});
let written = (d.new_texture_on_surface(&desc, Some(surface), 0))
.unwrap()
.unwrap();
let reader = (d.new_texture_on_surface(&desc, Some(surface), 0))
.unwrap()
.unwrap();
let written = (surface.texture(&desc, 0)).unwrap().unwrap();
let reader = (surface.texture(&desc, 0)).unwrap().unwrap();
let length = u64::try_from(texels.len()).unwrap();
let buffer = || {
(d.new_buffer_of_length(OnFault::Die, length, 0))
@@ -2791,31 +2743,32 @@ fn surface_texels() -> ((u64, u64), Vec<u8>) {
/// A texture over a surface reads what a blit through another texture over the same surface
/// wrote before it, as Metal's does, in a later encoder of one command buffer and in a command
/// buffer of another queue that waits for an event the write signals: two textures over one
/// surface are one memory, which the runtime imports once for both, the surface over pages of
/// the host's as a guest's mapper makes it
/// buffer of another queue that waits for an event the write signals: two textures over the
/// buffer that stands for one surface are one memory, the surface over pages of the host's as a
/// guest's mapper makes it
#[test]
fn a_texture_over_a_surface_reads_another_ones_writes_as_metals() {
use crate::os::tests::{bgra_surface_over_at, free};
use crate::gpu::resource::tests::{free_pages, host_pages};
let p = crate::platform::tests::platform();
let (size, texels) = surface_texels();
for order in [Order::OneCommandBuffer, Order::EventAcrossQueues] {
let (ours, pages, length) = bgra_surface_over_at(size.0, size.1, 0);
let (pages, length) = host_pages(size.0 * size.1 * 4);
let ours = StandIn::<VulkanPlatform>::bgra_over(&dev(), size, pages, length);
let read = read_through_another(&p, &dev(), &ours, (size, order), &texels);
assert!(read == texels, "{order:?}: in place");
drop(ours);
free(pages, length);
free_pages(pages, length);
}
}
/// [`a_texture_over_a_surface_reads_another_ones_writes_as_metals`] where every import is
/// refused, as Linux's views' gate refuses them past the headroom of the views' budget
/// (`os/linux/import.rs`), so the runtime makes each buffer over the surface over a copy of its
/// pages (`copied-host-pages`): the texture read must still see the other's writes, as Metal's
/// does
/// (`os/linux/import.rs`), so the runtime makes the buffer that stands for the surface over a
/// copy of its pages (`copied-host-pages`): the texture read must still see the other's writes,
/// as Metal's does
#[test]
fn a_texture_over_a_copied_surface_reads_another_ones_writes_as_metals() {
use crate::os::tests::{bgra_surface_over_at, free};
use crate::gpu::resource::tests::{free_pages, host_pages};
let p = crate::platform::tests::platform();
let (size, texels) = surface_texels();
let copies = || {
@@ -2827,9 +2780,10 @@ fn a_texture_over_a_copied_surface_reads_another_ones_writes_as_metals() {
for order in [Order::OneCommandBuffer, Order::EventAcrossQueues] {
let key = format!("{order:?}");
let before = copies();
let (ours, pages, length) = bgra_surface_over_at(size.0, size.1, 0);
let (pages, length) = host_pages(size.0 * size.1 * 4);
let read = crate::answer::relaxed(|| {
crate::os::refusing_imports(|| {
let ours = StandIn::<VulkanPlatform>::bgra_over(&dev(), size, pages, length);
read_through_another(&p, &dev(), &ours, (size, order), &texels)
})
});
@@ -2839,8 +2793,7 @@ fn a_texture_over_a_copied_surface_reads_another_ones_writes_as_metals() {
);
let metals = crate::metal_matches_bytes!(key, &read);
stale.push((order, metals, read.len()));
drop(ours);
free(pages, length);
free_pages(pages, length);
}
assert!(
stale.iter().all(|&(_, metals, _)| metals),
@@ -4423,8 +4423,9 @@ fn drawn_extended_range_samples_resolve_as_metals() {
/// How the resolve texture of [`resolved_into`] is made: a texture of its own of a storage
/// mode (`MTLResourceOptions`), which Metal may compress losslessly or not
/// (`allowGPUOptimizedContents`); one over a host IOSurface of a storage mode, presented as a
/// drawable (`setIsDrawable:` and `setFramebufferOnly:`, render target usage alone) or not; or a
/// (`allowGPUOptimizedContents`); one over an IOSurface of a storage mode, over the buffer that
/// stands for it, presented as a drawable (`setIsDrawable:` and `setFramebufferOnly:`, render
/// target usage alone) or not; or a
/// Private shareable texture (`newSharedTextureWithDescriptor:`), or one opened from its handle.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Made {
@@ -4752,17 +4753,15 @@ fn even_rate_map<P: Platform>(p: &P, d: &P::Device, (width, height): (u64, u64))
/// own: what Metal autoreleased (each command buffer and encoder, which a dev build cannot elide,
/// and through them the case's queue, textures and buffers) goes at its end, where the test
/// thread, which pops no pool, would keep every case's until the test ends.
fn resolved_into<P: Platform<Surface = crate::os::OsSurface>>(
fn resolved_into<P: Platform>(
p: &P,
d: &P::Device,
states: &States<'_, P>,
c: Resolve,
) -> Resolved {
use crate::core::platform::os::surface::{Surface as _, SurfaceSpec};
use crate::core::platform::values::{DepthAttachmentSet, PassSet, StencilAttachmentSet};
use crate::gpu::resource::tests::{StandIn, facts_of};
/// `kIOSurfaceLockReadOnly`.
const READ_ONLY: u32 = 1;
let _pool = crate::core::rt::Pool::here();
let (into, bytes) = c.into;
let (width, height) = c.size;
@@ -4809,34 +4808,16 @@ fn resolved_into<P: Platform<Surface = crate::os::OsSurface>>(
});
let surface = matches!(c.made, Made::Surface { .. }).then(|| {
let ostype = if bytes == 8 { *b"RGhA" } else { *b"w30r" };
let s = p
.surfaces()
.create(&SurfaceSpec {
pixel_format: u32::from_be_bytes(ostype),
alloc_size: length,
width,
height,
bytes_per_element: bytes,
bytes_per_row: width * bytes,
element_width: 1,
element_height: 1,
..SurfaceSpec::default()
})
.unwrap();
assert!(s.lock(0).is_success());
let base = s.base_address().as_ptr::<u8>();
// SAFETY: the surface's first `n` bytes, locked, which no texture uses yet.
unsafe { std::ptr::copy_nonoverlapping(prefill.as_ptr(), base, n) };
assert!(s.unlock(0).is_success());
let facts = facts_of(ostype, (width, height), &[]);
let s = StandIn::<P>::shared(d, facts, vec![(0, width * bytes)], length);
// SAFETY: the buffer's first `n` bytes, which no texture uses yet.
unsafe { std::ptr::copy_nonoverlapping(prefill.as_ptr(), s.base(), n) };
s
});
let shareable = matches!(c.made, Made::Shareable { .. })
.then(|| d.new_shared_texture(&desc).unwrap().unwrap());
let target = match (&surface, &shareable) {
(Some(s), _) => d
.new_texture_on_surface(&desc, Some(s), 0)
.unwrap()
.unwrap(),
(Some(s), _) => s.texture(&desc, 0).unwrap().unwrap(),
(None, Some(t)) if c.made == (Made::Shareable { opened: true }) => {
let handle = t.new_shared_texture_handle().unwrap().unwrap();
d.open_shared_texture(Some(&handle), 0).unwrap().unwrap()
@@ -5051,15 +5032,7 @@ fn resolved_into<P: Platform<Surface = crate::os::OsSurface>>(
unsafe { std::slice::from_raw_parts(b.contents().as_ptr::<u8>(), n) }.to_vec()
};
let resolved = match &surface {
Some(s) => {
assert!(s.lock(READ_ONLY).is_success());
// SAFETY: the surface's first `n` bytes, locked, after the command buffer
// completed.
let bytes = unsafe { std::slice::from_raw_parts(s.base_address().as_ptr::<u8>(), n) };
let bytes = bytes.to_vec();
assert!(s.unlock(READ_ONLY).is_success());
bytes
}
Some(s) => s.bytes(length),
None => read(&out, n),
};
let texels = usize::try_from(texels).unwrap();
@@ -11,8 +11,7 @@ use crate::core::testkit::capture::catch_death;
use super::super::NO_VIEW;
use super::*;
use crate::gpu::device::tests::dev;
use crate::os::OsSurface;
use crate::os::tests::bgra_surface;
use crate::gpu::resource::tests::StandIn;
/// The formats here.
const FORMATS: [u64; 4] = [263, 556, 651, 652];
@@ -34,10 +33,10 @@ type Case = (&'static str, fn(&mut TextureDesc));
/// `newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:`, and a Private placement
/// heap's `newTextureWithDescriptor:offset:` made a texture, in that order; and
/// `heapTextureSizeAndAlignWithDescriptor:`.
fn answers<P: Platform<Surface = OsSurface>>(
fn answers<P: Platform>(
d: &P::Device,
desc: &P::TextureDescriptor,
s: &OsSurface,
s: &StandIn<P>,
) -> (u64, [bool; 6], SizeAndAlign) {
let buffer = d
.new_buffer(BufferDesc {
@@ -63,9 +62,7 @@ fn answers<P: Platform<Surface = OsSurface>>(
let made = [
d.new_texture(OnFault::Return, desc).unwrap().is_some(),
d.new_shared_texture(desc).unwrap().is_some(),
d.new_texture_on_surface(desc, Some(s), 0)
.unwrap()
.is_some(),
s.texture(desc, 0).unwrap().is_some(),
buffer
.new_texture(OnFault::Return, desc, 0, 4096)
.unwrap()
@@ -144,7 +141,7 @@ fn textures_of_formats_metal_makes_none_of_are_nil_as_metals_are() {
];
let d = dev();
let p = platform();
let s = bgra_surface(16, 16);
let s = StandIn::<crate::platform::VulkanPlatform>::bgra(&dev(), 16, 16);
for format in FORMATS {
let own: &[Case] = match format {
556 => &[not_depth.as_slice(), multisample.as_slice()].concat(),
@@ -216,7 +213,7 @@ fn textures_of_formats_metal_makes_none_of_die_where_metal_asserts() {
];
let d = dev();
let p = platform();
let s = bgra_surface(16, 16);
let s = StandIn::<crate::platform::VulkanPlatform>::bgra(&dev(), 16, 16);
let buffer = d
.new_buffer(BufferDesc {
length: 1 << 16,
@@ -258,7 +255,7 @@ fn textures_of_formats_metal_makes_none_of_die_where_metal_asserts() {
),
(
"newTextureWithDescriptor:iosurface:plane:",
catch_death(|| d.new_texture_on_surface(&ours, Some(&s), 0)).map(drop),
catch_death(|| s.texture(&ours, 0)).map(drop),
),
(
"newTextureWithDescriptor:offset:bytesPerRow:",
+198 -160
View File
@@ -2131,20 +2131,20 @@ pub(crate) mod tests {
use std::alloc::{Layout, alloc_zeroed, dealloc};
use std::sync::atomic::{AtomicU32, Ordering};
use crate::core::num::ToUsize as _;
use crate::core::num::{ToU64 as _, ToUsize as _};
use crate::core::platform::Platform;
use crate::core::platform::descriptor::TextureDescriptor as _;
use crate::core::platform::device::{GpuDevice, NoCopyDeallocator};
use crate::core::platform::os::surface::{Surface, SurfacePlaneSpec, SurfaceSpec};
use crate::core::platform::types::MtlOrigin;
use crate::core::platform::values::{BufferDesc, HeapDesc, HeapMade, OptionSet, TextureDesc};
use crate::core::platform::values::{
BufferDesc, HeapDesc, HeapMade, OptionSet, SurfaceFacts, TextureDesc,
};
use crate::core::raise::death::DeathKind;
use crate::core::sync::Mutex;
use crate::core::testkit::capture::catch_death;
use super::*;
use crate::gpu::device::tests::dev;
use crate::os::tests::bgra_surface;
use crate::platform::tests::platform;
/// A no-copy buffer core makes over `pages` pages of zeros mapped read-only
@@ -2670,6 +2670,155 @@ pub(crate) mod tests {
.unwrap()
}
/// A buffer that stands for an IOSurface, as the reims-graphics device's surfaces reach this
/// platform (`Buffer::new_texture_over_surface_plane`): its first byte is the surface's base
/// address, its planes lie at [`StandIn::planes`], and a texture over one of them reads the
/// surface's facts besides.
pub(crate) struct StandIn<P: Platform> {
/// The buffer, of the surface's bytes.
pub(crate) buffer: P::Buffer,
/// What a texture over one of its planes reads besides the plane.
pub(crate) facts: SurfaceFacts,
/// Each plane's first byte and bytes per row: of a surface without planes, its one, at
/// 0 (`IOSurfaceGetBytesPerRow`).
pub(crate) planes: Vec<(u64, u64)>,
}
/// The facts of a surface of `ostype` whose plane 0 is `width` by `height`, and whose plane
/// 1, where `planes` has one, lies there; `planes` has none for a surface without planes, and
/// its matrix is none.
pub(crate) fn facts_of(
ostype: [u8; 4],
(width, height): (u64, u64),
planes: &[(u64, u64)],
) -> SurfaceFacts {
let (chroma_offset, chroma_bytes_per_row) = planes.get(1).copied().unwrap_or((0, 0));
SurfaceFacts {
pixel_format: u32::from_be_bytes(ostype),
plane_count: planes.len().to_u64(),
width,
height,
chroma_offset,
chroma_bytes_per_row,
ycbcr_matrix: None,
}
}
/// Fresh pages of the host's, of zeros, that hold at least `bytes` bytes: their first byte and
/// length, which [`free_pages`] frees once nothing lies over them.
pub(crate) fn host_pages(bytes: u64) -> (HostPtr, u64) {
use crate::core::platform::os::vm::HostVm as _;
let length = bytes.next_multiple_of(crate::os::OsVm::new().page_size());
(crate::os::allocate_aliasable(length).unwrap(), length)
}
/// The pages of [`host_pages`], freed.
pub(crate) fn free_pages(pages: HostPtr, length: u64) {
use crate::core::platform::os::vm::HostVm as _;
let freed = crate::remap::VulkanVm::new().deallocate(pages, length);
assert!(freed.is_success());
}
impl<P: Platform> StandIn<P> {
/// A stand-in over `buffer` of a surface of `facts` whose planes lie at `planes` (one at
/// 0, of the surface's bytes per row, for a surface without planes).
pub(crate) fn over(
buffer: P::Buffer,
facts: SurfaceFacts,
planes: Vec<(u64, u64)>,
) -> Self {
StandIn {
buffer,
facts,
planes,
}
}
/// A stand-in of `length` bytes of `d`'s `Shared` memory, zeros, of a surface of `facts`
/// whose planes lie at `planes`.
pub(crate) fn shared(
d: &P::Device,
facts: SurfaceFacts,
planes: Vec<(u64, u64)>,
length: u64,
) -> Self {
let buffer = (d.new_buffer_of_length(OnFault::Die, length, 0))
.unwrap()
.unwrap();
Self::over(buffer, facts, planes)
}
/// A 'BGRA' surface's stand-in of `width` by `height`, 4 bytes an element, rows of
/// `width × 4` bytes, zeros.
pub(crate) fn bgra(d: &P::Device, width: u64, height: u64) -> Self {
let facts = facts_of(*b"BGRA", (width, height), &[]);
Self::shared(d, facts, vec![(0, width * 4)], width * height * 4)
}
/// A 'BGRA' surface's stand-in of `size` (as [`StandIn::bgra`]) over the `length` bytes of
/// host pages at `pages` ([`host_pages`]), a no-copy buffer of `d`'s over them, as a
/// guest's surface lies over the guest's pages.
pub(crate) fn bgra_over(
d: &P::Device,
(width, height): (u64, u64),
pages: HostPtr,
length: u64,
) -> Self {
// SAFETY: the pages outlive the buffer, which the caller drops before freeing them.
let bytes = unsafe { HostRange::new(pages, length) };
let buffer = (d.new_buffer_over_host_memory(OnFault::Die, bytes, 0, None))
.unwrap()
.unwrap();
let facts = facts_of(*b"BGRA", (width, height), &[]);
Self::over(buffer, facts, vec![(0, width * 4)])
}
/// Plane `plane` as `newTextureWithDescriptor:iosurface:plane:` is given it, with the
/// surface's facts: a plane the surface lacks at 0.
pub(crate) fn plane(&self, plane: u64) -> SurfacePlane {
let at = usize::try_from(plane).ok().and_then(|p| self.planes.get(p));
let (offset, bytes_per_row) = at.copied().unwrap_or((0, 0));
SurfacePlane {
plane,
offset,
bytes_per_row,
planar: self.facts.plane_count != 0,
facts: Some(self.facts),
}
}
/// A texture of `desc` over plane `plane`, as the device's IOSurface creator makes one
/// over the surface the buffer stands for.
pub(crate) fn texture(
&self,
desc: &P::TextureDescriptor,
plane: u64,
) -> RaiseResult<Option<P::Texture>> {
use crate::core::platform::resource::Buffer as _;
(self.buffer).new_texture_over_surface_plane(OnFault::Return, desc, self.plane(plane))
}
/// The surface's base address: the buffer's first byte.
pub(crate) fn base(&self) -> *mut u8 {
use crate::core::platform::resource::Buffer as _;
self.buffer.contents().as_ptr::<u8>()
}
/// The surface's length: the buffer's.
#[cfg(target_os = "macos")]
pub(crate) fn length(&self) -> u64 {
use crate::core::platform::resource::Buffer as _;
self.buffer.length()
}
/// The surface's bytes from its base address to `length`, read once the work that wrote
/// them completed.
pub(crate) fn bytes(&self, length: u64) -> Vec<u8> {
// SAFETY: the buffer's Shared bytes, which no GPU work uses now.
unsafe { std::slice::from_raw_parts(self.base(), length.to_usize()) }.to_vec()
}
}
/// Two pages of zeroed host memory at a page boundary, and its layout.
fn pages() -> (*mut u8, Layout) {
let layout = Layout::from_size_align(32768, 16384).unwrap();
@@ -2892,18 +3041,21 @@ pub(crate) mod tests {
assert_eq!(heap(Some(at)).unwrap().gpu_address(), at);
}
/// Core's fill of a texture with the bytes of a buffer made on a surface reads the buffer's
/// NULL contents plus the offset, and dies at the fill as a NULL access, where Metal's read of
/// the bytes ends the process with a segmentation fault, of any length; one of a region of no
/// width and no height, whose bytes Metal never reads, fills nothing and goes on
/// Core's fill of a texture with the bytes of a buffer whose contents are NULL (a `Private`
/// one's) reads the buffer's NULL contents plus the offset, and dies at the fill as a NULL
/// access, where Metal's read of the bytes ends the process with a segmentation fault, of any
/// length; one of a region of no width and no height, whose bytes Metal never reads, fills
/// nothing and goes on
#[test]
fn a_fill_with_a_surface_buffers_bytes_dies() {
fn a_fill_with_a_null_buffers_bytes_dies() {
use crate::core::platform::blit::{BlitCmd, BlitEncoder as _};
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
let d = dev();
let s = bgra_surface(64, 32);
let b = d.new_buffer_on_surface(Some(&s)).unwrap().unwrap();
let b = (d.new_buffer_of_length(OnFault::Return, 64 * 32 * 4, 0x20))
.unwrap()
.unwrap();
assert!(b.contents().is_null());
let t = d
.new_texture(OnFault::Return, &bgra(8, 8, 0))
.unwrap()
@@ -3764,113 +3916,31 @@ pub(crate) mod tests {
}
}
/// A texture on a surface writes the surface's memory, and holds one reference of the
/// surface while it lives; its views share that reference. One over plane 1 of the surface,
/// which has no planes, dies where it is made
/// A texture on a surface, over the buffer that stands for it, writes the surface's memory,
/// and so does a view of it. One over plane 1 of the surface, which has no planes, dies where
/// it is made
#[test]
fn textures_on_surfaces() {
let d = dev();
let s = bgra_surface(64, 32);
let t = d
.new_texture_on_surface(&bgra(64, 32, 0), Some(&s), 0)
.unwrap()
.unwrap();
assert_eq!(s.retain_count(), 2);
let s = StandIn::<VulkanPlatform>::bgra(&d, 64, 32);
let t = s.texture(&bgra(64, 32, 0), 0).unwrap().unwrap();
let view = t.new_texture_view(70).unwrap().unwrap();
assert_eq!(s.retain_count(), 2);
assert_eq!(view.iosurface().unwrap().id(), s.id());
let bytes = pattern(64, 32);
fill(&t, &bytes);
// SAFETY: the surface's memory, rows of 256 bytes, which the texture's write finished.
let memory =
unsafe { std::slice::from_raw_parts(s.base_address().as_ptr::<u8>(), bytes.len()) };
assert_eq!(memory, &bytes[..]);
// The surface's memory, rows of 256 bytes, which the texture's write finished.
assert_eq!(s.bytes(64 * 32 * 4), bytes);
assert_eq!(read_back(&t), bytes);
let reversed: Vec<u8> = bytes.iter().rev().copied().collect();
fill(&view, &reversed);
assert_eq!(s.bytes(64 * 32 * 4), reversed);
drop((t, view));
assert_eq!(s.retain_count(), 1);
// A surface without planes has plane 0 only: a texture over its plane 1 dies where it
// is made, as Metal asserts there (`textures_over_planes_a_surface_lacks_are_metals`).
let site =
catch_death(|| d.new_texture_on_surface(&bgra(64, 32, 0), Some(&s), 1)).unwrap_err();
let site = catch_death(|| s.texture(&bgra(64, 32, 0), 1)).unwrap_err();
let sel = "newTextureWithDescriptor:iosurface:plane:";
assert_eq!((site.kind, site.file), (DeathKind::Abort, sel));
}
/// A texture over a surface released while a command buffer that copies it waits keeps the
/// surface's range of Metal's space until that command buffer completed, as Metal frees a
/// released resource's range (`metal_space::Hold`): a buffer of the range's size made
/// meanwhile lies elsewhere, and one made after the completion at the range
#[test]
fn a_surface_texture_keeps_its_range_until_its_command_buffer_completed() {
use crate::core::platform::blit::{BlitCmd, BlitEncoder as _};
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::event::{EventRef, SharedEvent as _};
use crate::core::platform::resource::Buffer as _;
use crate::core::platform::types::MtlSize;
use crate::core::rt::Pool;
let (p, d) = (platform(), dev());
// 64 by 64, 4 bytes a texel: a page, whose range is the space's 0x8000.
let side = 64;
let s = bgra_surface(side, side);
let desc = p.texture_descriptor(&TextureDesc {
pixel_format: 80,
width: side,
height: side,
usage: 1,
resource_options: Some(0),
..TextureDesc::default()
});
let q = d.new_command_queue().unwrap();
let event = d.new_shared_event().unwrap();
let out = d
.new_buffer_of_length(OnFault::Die, side * side * 4, 0)
.unwrap()
.unwrap();
let page = |d: &VulkanDevice| {
d.new_buffer_of_length(OnFault::Die, 0x4000, 0)
.unwrap()
.unwrap()
};
let (cb, at) = {
let _pool = Pool::here();
let t = d
.new_texture_on_surface(&desc, Some(&s), 0)
.unwrap()
.unwrap();
let at = t.space.address().unwrap();
let cb = q.command_buffer(OnFault::Die).unwrap().unwrap();
cb.encode_wait(Some(EventRef::Shared(&event)), 1).unwrap();
let e = cb.blit_encoder(OnFault::Die).unwrap().unwrap();
e.encode(
OnFault::Die,
BlitCmd::CopyTextureToBuffer {
source_texture: &t,
source_slice: 0,
source_level: 0,
source_origin: MtlOrigin::new(0, 0, 0),
source_size: MtlSize::new(side, side, 1),
destination_buffer: &out,
destination_offset: 0,
destination_bytes_per_row: side * 4,
destination_bytes_per_image: side * side * 4,
},
)
.unwrap();
e.encode(OnFault::Die, BlitCmd::EndEncoding).unwrap();
cb.commit(OnFault::Die).unwrap();
(cb, at)
};
let meanwhile = page(&d);
assert_ne!(meanwhile.gpu_address(), at, "made while the copy waits");
{
let _pool = Pool::here();
event.set_signaled_value(1).unwrap();
cb.wait_until_completed(OnFault::Die).unwrap();
assert!(cb.error().is_none(), "{:?}", cb.error());
}
assert_eq!(page(&d).gpu_address(), at, "made once the copy completed");
}
/// A texture of its own memory and a shareable texture, released while a command buffer
/// that copies it waits, keep their range of Metal's space until that command buffer
/// completed, as Metal frees a released resource's range (`metal_space::Hold`, the
@@ -3992,8 +4062,8 @@ pub(crate) mod tests {
/// Every texture takes a descriptor in Metal's mempool while it lives
/// (`metal_space::Elements`): one of memory of its own, a view, one over a buffer and one in a
/// heap, over a surface, a shareable one and one opened from its handle each count one, which
/// goes with it
/// heap, over a buffer that stands for a surface, a shareable one and one opened from its
/// handle each count one, which goes with it
#[test]
fn every_texture_takes_a_descriptor_while_it_lives() {
use crate::core::platform::resource::{Heap as _, Texture as _};
@@ -4024,8 +4094,8 @@ pub(crate) mod tests {
});
let heap = heap.unwrap().heap.unwrap();
let placed = heap.new_texture(&private, 0).unwrap().unwrap();
let s = bgra_surface(64, 64);
let on_surface = d.new_texture_on_surface(&shared, Some(&s), 0);
let s = StandIn::<VulkanPlatform>::bgra(&d, 64, 64);
let on_surface = s.texture(&shared, 0);
let shareable = d.new_shared_texture(&private).unwrap().unwrap();
let handle = shareable.new_shared_texture_handle().unwrap().unwrap();
let opened = d.open_shared_texture(Some(&handle), 0).unwrap().unwrap();
@@ -4035,50 +4105,20 @@ pub(crate) mod tests {
assert_eq!(live(), start);
}
/// A texture on a plane of a planar surface is over that plane's bytes, at its rows; a plane
/// past the surface's planes is nil, as on Metal
/// A texture on a plane of a planar surface, over the buffer that stands for it, is over that
/// plane's bytes, at its rows; a plane past the surface's planes is nil, as on Metal
#[test]
fn textures_on_surface_planes() {
let plane = |base: u64| SurfacePlaneSpec {
base,
offset: base,
width: 16,
height: 4,
size: 16 * 4 * 8,
bytes_per_row: 16 * 8,
bytes_per_element: 4,
element_width: 1,
element_height: 1,
..SurfacePlaneSpec::default()
};
let s = platform()
.surfaces()
.create(&SurfaceSpec {
planes: Some(vec![plane(0), plane(16384)]),
pixel_format: u32::from_be_bytes(*b"BGRA"),
alloc_size: 32768,
width: 16,
height: 4,
bytes_per_element: 4,
bytes_per_row: 16 * 8,
element_width: 1,
element_height: 1,
..SurfaceSpec::default()
})
.unwrap();
assert_eq!(s.plane_count(), 2);
let d = dev();
let t = d
.new_texture_on_surface(&bgra(16, 4, 0), Some(&s), 1)
.unwrap()
.unwrap();
let planes = vec![(0, 16 * 8), (16384, 16 * 8)];
let facts = facts_of(*b"BGRA", (16, 4), &planes);
let s = StandIn::<VulkanPlatform>::shared(&d, facts, planes, 32768);
let t = s.texture(&bgra(16, 4, 0), 1).unwrap().unwrap();
let bytes = pattern(16, 4);
fill(&t, &bytes);
// SAFETY: the surface's memory, which the texture's write finished: plane 1 at 16384,
// rows of 128 bytes of which the texture's 64 are the first.
let memory = unsafe {
std::slice::from_raw_parts(s.base_address().as_ptr::<u8>().add(16384), 4 * 128)
};
// The surface's memory, which the texture's write finished: plane 1 at 16384, rows of 128
// bytes of which the texture's 64 are the first.
let memory = &s.bytes(32768)[16384..];
for row in 0..4 {
assert_eq!(
memory[row * 128..row * 128 + 64],
@@ -4086,7 +4126,7 @@ pub(crate) mod tests {
);
}
assert_eq!(read_back(&t), bytes);
let none = d.new_texture_on_surface(&bgra(16, 4, 0), Some(&s), 2);
let none = s.texture(&bgra(16, 4, 0), 2);
assert!(none.unwrap().is_none());
}
@@ -4204,8 +4244,9 @@ pub(crate) mod tests {
}
/// A texture of a rotation other than 0 dies where Metal aborts: of a descriptor that is not
/// framebufferOnly, of a rotation past 4, and made other than over an IOSurface. Over one, a
/// framebufferOnly descriptor's rotations 1 to 4 are made at its size, holding the rotation,
/// framebufferOnly, of a rotation past 4, and made other than over an IOSurface. Over one
/// (the buffer that stands for it), a framebufferOnly descriptor's rotations 1 to 4 are made
/// at its size, holding the rotation,
/// over a surface that holds the frame it stores (a quarter turn's its height wide and its
/// width tall); a size query answers them as it answers 0. A quarter turn whose stored frame
/// runs past the surface dies where it is made: Metal makes it, and the runtime refuses it.
@@ -4215,11 +4256,11 @@ pub(crate) mod tests {
#[test]
fn rotated_textures_are_made_only_where_metal_makes_them() {
let d = dev();
let s = bgra_surface(64, 16);
let s = StandIn::<VulkanPlatform>::bgra(&d, 64, 16);
let on_surface = "newTextureWithDescriptor:iosurface:plane:";
for (rotation, framebuffer_only) in [(2, false), (1, false), (5, true), (u64::MAX, true)] {
let desc = rotated(rotation, framebuffer_only);
let site = catch_death(|| d.new_texture_on_surface(&desc, Some(&s), 0)).unwrap_err();
let site = catch_death(|| s.texture(&desc, 0)).unwrap_err();
assert_eq!(
(site.kind, site.file),
(DeathKind::Abort, on_surface),
@@ -4267,13 +4308,10 @@ pub(crate) mod tests {
}
let site = catch_death(|| d.heap_texture_size_and_align(&rotated(1, false))).unwrap_err();
assert_eq!(site.file, "heapTextureSizeAndAlignWithDescriptor:");
let tall = bgra_surface(64, 64);
let tall = StandIn::<VulkanPlatform>::bgra(&d, 64, 64);
for rotation in 1..=4 {
let desc = rotated(rotation, true);
let t = d
.new_texture_on_surface(&desc, Some(&tall), 0)
.unwrap()
.unwrap();
let t = tall.texture(&desc, 0).unwrap().unwrap();
let turned = plain(|| t.raw.rotation());
assert_eq!((t.width(), t.height(), turned), (64, 16, rotation));
let view = t.new_texture_view(81).unwrap().unwrap();
@@ -4300,7 +4338,7 @@ pub(crate) mod tests {
});
let sel = "newTextureViewWithPixelFormat:textureType:levels:slices:swizzle:";
assert_eq!(swizzled.unwrap_err().file, sel);
let made = catch_death(|| d.new_texture_on_surface(&desc, Some(&s), 0).map(drop));
let made = catch_death(|| s.texture(&desc, 0).map(drop));
match rotation {
2 => assert!(made.is_ok()),
_ => assert_eq!(made.unwrap_err().file, on_surface, "rotation {rotation}"),
@@ -4340,8 +4378,8 @@ pub(crate) mod tests {
for (sel, death) in deaths {
assert_eq!(death.unwrap_err().file, sel);
}
let s = bgra_surface(64, 16);
let on_surface = d.new_texture_on_surface(&desc, Some(&s), 0).unwrap();
let s = StandIn::<VulkanPlatform>::bgra(&d, 64, 16);
let on_surface = s.texture(&desc, 0).unwrap();
assert_eq!(on_surface.map(|t| plain(|| t.raw.rotation())), Some(0));
assert!(d.new_shared_texture(&private).unwrap().is_some());
let size = |desc: &VulkanTextureDescriptor| {
File diff suppressed because it is too large. Load diff
+16 -21
View File
@@ -685,7 +685,10 @@ pub(crate) mod tests {
use crate::core::raise::OnFault;
use super::*;
use crate::gpu::resource::tests::{guest_pages, heap_at, over_pages};
use crate::gpu::resource::tests::{
StandIn, free_pages, guest_pages, heap_at, host_pages, over_pages,
};
use crate::platform::VulkanPlatform;
/// A death over a slot whose state's slot writes cannot tell names why they cannot; one they
/// tell names the declaration that writes
@@ -838,11 +841,11 @@ pub(crate) mod tests {
}
/// What a bind keeps of a buffer's or a texture's memory, read without collecting ranges, is
/// what the memory collected answers: for a buffer of the device's memory, one placed in a
/// heap over the guest's memory (at its bytes and past the heap's), one on a surface, textures
/// placed in the heap, over a buffer, on surfaces over the guest's pages and over memory of
/// their own, and one of memory of its own. A heap's buffer and texture lie in no memory a
/// surface's write check looks for
/// what the memory collected answers: for a buffer of the device's memory and one placed in a
/// heap over the guest's memory (at its bytes and past the heap's), textures placed in the
/// heap, over a buffer, over a surface's plane of a buffer over the host's pages and of one of
/// the device's memory, and one of memory of its own. A heap's buffer and texture lie in no
/// memory a surface's write check looks for
#[test]
fn bound_memory_is_the_memory_collected() {
let (p, d) = (
@@ -876,21 +879,13 @@ pub(crate) mod tests {
.unwrap()
.unwrap();
let alone = d.new_texture(OnFault::Die, &bgra(0)).unwrap().unwrap();
let surface = crate::os::tests::bgra_surface(16, 16);
let (over, pages, length) = crate::os::tests::bgra_surface_over_at(16, 16, 0x40);
let on_surface = (d.new_texture_on_surface(&bgra(0), Some(&surface), 0))
.unwrap()
.unwrap();
let on_pages = (d.new_texture_on_surface(&bgra(0), Some(&over), 0))
.unwrap()
.unwrap();
let surface_buffer = d.new_buffer_on_surface(Some(&surface)).unwrap().unwrap();
let surface = StandIn::<VulkanPlatform>::bgra(&d, 16, 16);
let (pages, length) = host_pages(16 * 16 * 4);
let over = StandIn::<VulkanPlatform>::bgra_over(&d, (16, 16), pages, length);
let on_surface = surface.texture(&bgra(0), 0).unwrap().unwrap();
let on_pages = over.texture(&bgra(0), 0).unwrap().unwrap();
let agree = |when: &str| {
for (name, b) in [
("placed", &placed),
("own", &own),
("surface", &surface_buffer),
] {
for (name, b) in [("placed", &placed), ("own", &own)] {
assert_eq!(buffer_bound(b), buffer_memory(b).bound(), "{when}: {name}");
for bytes in [0..0x10, 0xff0..0x1010, size..size + 0x10, 0x10..0x10] {
assert_eq!(
@@ -917,7 +912,7 @@ pub(crate) mod tests {
agree("made");
assert!(!buffer_bound(&placed).meets && !texture_bound(&in_heap).meets);
drop((on_pages, over));
crate::os::tests::free(pages, length);
free_pages(pages, length);
}
/// A texture over a surface's plane reaches the plane's rows where the CPU lays them out and
@@ -4,15 +4,27 @@
//! halves and into floats. The same probes run for every member: a surface's shape is its
//! OSType's ([`Shape`]), and the texture's format is a parameter of each probe ([`probes`]).
//! Floats show a texel's value at full precision; a kernel that reads into halves rounds it.
use crate::core::platform::os::surface::{IoSurfaces as _, SurfacePlaneSpec, SurfaceSpec};
//! A surface is the buffer that stands for it ([`Surface`]), as the reims-graphics device's
//! surfaces reach this platform.
#[cfg(target_os = "macos")]
use crate::core::platform::values::SurfaceFacts;
#[cfg(target_os = "macos")]
use crate::gpu::device::VulkanDevice;
#[cfg(target_os = "macos")]
use crate::gpu::resource::tests::{StandIn, facts_of};
#[cfg(target_os = "macos")]
use crate::platform::VulkanPlatform;
use crate::os::{OsSurface, OsSurfaces};
/// A surface of the harness: the buffer that stands for it, with its facts and planes.
#[cfg(target_os = "macos")]
pub(crate) type Surface = StandIn<VulkanPlatform>;
/// How a surface of two planes lays out its samples: plane 0 the luma, plane 1 Cb and Cr
/// interleaved, each sample a code in the top bits of `container` bytes, or, `packed`, three
/// codes to a little-endian 32-bit word, at its bits 0, 10 and 20 (bits 30 and 31 unread): luma
/// code `x` of a row in word `x / 3`, the chroma pair `x` as codes `2 x` (Cb) and `2 x + 1`
/// (Cr).
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Shape {
/// The surface's OSType.
@@ -28,6 +40,7 @@ pub(crate) struct Shape {
pub packed: bool,
}
#[cfg(target_os = "macos")]
impl Shape {
/// The shape CoreVideo gives `ostype`, one of the two-plane OSTypes measured.
pub(crate) fn of(ostype: &[u8; 4]) -> Shape {
@@ -68,64 +81,30 @@ impl Shape {
}
}
/// The spec of a host-only surface of this shape whose luma plane is `size`: rows of a
/// multiple of 64 bytes and plane 1 at a multiple of 4096, as CoreVideo lays them out.
/// IOSurface makes none of a surface's bytes per row of 0, so the surface's are plane 0's.
/// A packed plane's element is a word of three luma codes (3 texels in 4 bytes), or two
/// words of three chroma pairs (3 texels in 8 bytes).
pub(crate) fn spec(&self, size: (u64, u64)) -> SurfaceSpec {
/// The layout of a surface of this shape whose luma plane is `size`: its facts, its planes
/// (each a first byte and bytes per row) and its length. Rows of a multiple of 64 bytes and
/// plane 1 at a multiple of 4096, as CoreVideo lays them out; a packed row holds a word of
/// three luma codes (3 texels in 4 bytes), or two words of three chroma pairs (3 texels in 8
/// bytes).
pub(crate) fn layout(&self, size: (u64, u64)) -> (SurfaceFacts, Vec<(u64, u64)>, u64) {
let (width, height) = size;
let (chroma_width, chroma_height) = self.chroma_size(size);
let (element, element_width) = match self.packed {
true => (4, 3),
false => (self.container, 1),
};
let (luma_row, chroma_row) = (
self.row_bytes(width).next_multiple_of(64),
self.row_bytes(chroma_width * 2).next_multiple_of(64),
);
let luma_size = luma_row * height;
let chroma_offset = luma_size.next_multiple_of(4096);
let chroma_size = chroma_row * chroma_height;
let plane =
|offset, (width, height), bytes_per_row, bytes_per_element, size| SurfacePlaneSpec {
base: offset,
offset,
width,
height,
size,
bytes_per_row,
bytes_per_element,
element_width,
element_height: 1,
..SurfacePlaneSpec::default()
};
SurfaceSpec {
planes: Some(vec![
plane(0, (width, height), luma_row, element, luma_size),
plane(
chroma_offset,
(chroma_width, chroma_height),
chroma_row,
element * 2,
chroma_size,
),
]),
pixel_format: u32::from_be_bytes(self.ostype),
alloc_size: (chroma_offset + chroma_size).next_multiple_of(16384),
width,
height,
bytes_per_element: element,
bytes_per_row: luma_row,
element_width,
element_height: 1,
..SurfaceSpec::default()
}
let chroma_offset = (luma_row * height).next_multiple_of(4096);
let planes = vec![(0, luma_row), (chroma_offset, chroma_row)];
let facts = facts_of(self.ostype, size, &planes);
let length = (chroma_offset + chroma_row * chroma_height).next_multiple_of(16384);
(facts, planes, length)
}
/// A host-only surface of this shape whose luma plane is `size` ([`Shape::spec`]).
pub(crate) fn surface(&self, size: (u64, u64)) -> OsSurface {
OsSurfaces::new().create(&self.spec(size)).unwrap()
/// A surface of this shape whose luma plane is `size` ([`Shape::layout`]), zeros, the buffer
/// that stands for it `d`'s.
pub(crate) fn surface(&self, d: &VulkanDevice, size: (u64, u64)) -> Surface {
let (facts, planes, length) = self.layout(size);
Surface::shared(d, facts, planes, length)
}
}
@@ -1,64 +1,28 @@
//! The measurement harness's macOS side: a surface's values (`IOSurfaceSetValue`), which only
//! IOSurface itself takes, the probe kernels and the surfaces they read.
//! The measurement harness's macOS side: the probe kernels and the surfaces they read.
use std::ffi::c_void;
use crate::core::platform::Handle as _;
use crate::core::platform::Platform;
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::compute::{ComputeCmd, ComputeEncoder as _};
use crate::core::platform::device::GpuDevice as _;
use crate::core::platform::resource::{Buffer as _, Library as _};
use crate::core::platform::types::{MtlSize, NsRange};
use crate::core::platform::values::{SamplerDesc, TextureDesc};
use crate::core::platform::values::{SamplerDesc, SurfaceMatrix, SurfacePlane, TextureDesc};
use crate::core::raise::OnFault;
use super::*;
use crate::os::OsSurface;
#[link(name = "IOSurface", kind = "framework")]
unsafe extern "C" {
fn IOSurfaceSetValue(buffer: *const c_void, key: *const c_void, value: *const c_void);
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFStringCreateWithBytes(
alloc: *const c_void,
bytes: *const u8,
num_bytes: isize,
encoding: u32,
is_external_representation: u8,
) -> *const c_void;
fn CFRelease(cf: *const c_void);
}
/// A CFString of `s`, +1.
fn cf_string(s: &str) -> *const c_void {
// SAFETY: `s`'s bytes, live for the call, which copies them.
unsafe {
CFStringCreateWithBytes(
std::ptr::null(),
s.as_ptr(),
isize::try_from(s.len()).unwrap(),
0x0800_0100,
0,
)
}
}
/// Sets `surface`'s `key` to the string `value` (`IOSurfaceSetValue`).
pub(crate) fn set_value(surface: &OsSurface, key: &str, value: &str) {
let (key, value) = (cf_string(key), cf_string(value));
let surface =
std::ptr::with_exposed_provenance::<c_void>(usize::try_from(surface.id().0).unwrap());
// SAFETY: a live IOSurfaceRef and two CFStrings, released after the call, which retains
// what it keeps.
unsafe {
IOSurfaceSetValue(surface, key, value);
CFRelease(key);
CFRelease(value);
}
/// Sets `surface`'s YCbCr matrix to the one `name` names, its `kIOSurfaceYCbCrMatrix` string, as
/// the guest's surfaces give it: any other string is `Other`.
pub(crate) fn set_matrix(surface: &mut Surface, name: &str) {
surface.facts.ycbcr_matrix = Some(match name {
"ITU_R_601_4" => SurfaceMatrix::Itu601,
"ITU_R_709_2" => SurfaceMatrix::Itu709,
"ITU_R_2020" => SurfaceMatrix::Itu2020,
"SMPTE_240M_1995" => SurfaceMatrix::Smpte240M1995,
"DCI_P3" => SurfaceMatrix::DciP3,
"P3_D65" => SurfaceMatrix::P3D65,
_ => SurfaceMatrix::Other,
});
}
/// The tests' kernels that read a texture (`ycbcr_probe.metal`).
@@ -76,59 +40,37 @@ fn shape_420(ostype: &[u8; 4]) -> Shape {
}
}
/// A host-only surface of `ostype` with the two planes of a `width` by `height` texture of
/// 505, rows of a multiple of 64 bytes and plane 1 at a multiple of 4096, as the measured
/// surfaces were laid out ([`Shape::spec`]).
pub(crate) fn surface_420(ostype: &[u8; 4], size: (u64, u64)) -> OsSurface {
shape_420(ostype).surface(size)
/// A surface of `ostype` with the two planes of a `width` by `height` texture of 505, rows of a
/// multiple of 64 bytes and plane 1 at a multiple of 4096, as the measured surfaces were laid
/// out ([`Shape::layout`]), the buffer that stands for it `d`'s.
pub(crate) fn surface_420(
d: &crate::gpu::device::VulkanDevice,
ostype: &[u8; 4],
size: (u64, u64),
) -> Surface {
shape_420(ostype).surface(d, size)
}
/// [`surface_420`], made over pages of its own the host allocates, as a guest's surface is
/// made over the guest's pages (`kIOSurfaceClientAddressRanges`), and those pages: their first
/// byte and length, which the caller frees once the surface is gone.
/// [`surface_420`], the buffer that stands for it a no-copy one of `d`'s over pages of their own
/// the host allocates, as a guest's surface lies over the guest's pages, and those pages: their
/// first byte and length, which the caller frees once the buffer is gone.
pub(crate) fn surface_420_over(
d: &crate::gpu::device::VulkanDevice,
ostype: &[u8; 4],
size: (u64, u64),
) -> (OsSurface, crate::core::host::HostPtr, u64) {
surface_420_over_at(ostype, size, 0)
}
/// [`surface_420_over`], its bytes `offset` bytes into its pages (`kIOSurfaceOffset`), its
/// planes' offsets too, which count from the pages' first byte.
pub(crate) fn surface_420_over_at(
ostype: &[u8; 4],
size: (u64, u64),
offset: u64,
) -> (OsSurface, crate::core::host::HostPtr, u64) {
use crate::core::host::PhysicalMemoryRange;
use crate::core::num::ToU64;
) -> (Surface, crate::core::host::HostPtr, u64) {
use crate::core::platform::HostRange;
use crate::core::platform::os::vm::HostVm as _;
let mut spec = spec_420(ostype, size);
let (facts, planes, length) = shape_420(ostype).layout(size);
let vm = crate::os::OsVm::new();
let page = vm.page_size();
for plane in spec.planes.iter_mut().flatten() {
plane.offset += offset;
plane.base += offset;
}
spec.offset = offset;
spec.alloc_size = (spec.alloc_size + offset).next_multiple_of(page);
let pages = vm.allocate_anywhere(spec.alloc_size).unwrap();
let first = pages.addr().to_u64();
spec.client_address_ranges = Some(
(0..spec.alloc_size / page)
.map(|i| PhysicalMemoryRange {
physical_address: first + i * page,
physical_length: page,
})
.collect(),
);
let s = OsSurfaces::new().create(&spec).unwrap();
(s, pages, spec.alloc_size)
}
/// The spec of [`surface_420`]'s surface.
fn spec_420(ostype: &[u8; 4], size: (u64, u64)) -> SurfaceSpec {
shape_420(ostype).spec(size)
let length = length.next_multiple_of(vm.page_size());
let pages = vm.allocate_anywhere(length).unwrap();
// SAFETY: the pages outlive the buffer, which the caller drops before freeing them.
let bytes = unsafe { HostRange::new(pages, length) };
let buffer = (d.new_buffer_over_host_memory(OnFault::Die, bytes, 0, None))
.unwrap()
.unwrap();
(Surface::over(buffer, facts, planes), pages, length)
}
/// A xorshift sequence from `seed`: the same 16-bit values on every run.
@@ -144,7 +86,7 @@ pub(crate) fn noise(seed: u64) -> impl FnMut() -> u16 {
/// Fills `surface`, of [`surface_420`]'s layout, with `noise(seed)`'s samples, the low 6 bits
/// too.
pub(crate) fn fill_noise(surface: &OsSurface, size: (u64, u64), seed: u64) {
pub(crate) fn fill_noise(surface: &Surface, size: (u64, u64), seed: u64) {
shape_420(b"x420").fill_noise(surface, size, seed);
}
@@ -530,17 +472,13 @@ impl Shape {
/// low 10 bits into its code's place in its word.
pub(crate) fn fill(
&self,
surface: &OsSurface,
surface: &Surface,
size: (u64, u64),
luma: impl Fn(u64, u64) -> u16,
chroma: impl Fn(u64, u64) -> (u16, u16),
) {
use crate::core::platform::os::surface::Surface as _;
let (y_plane, c_plane) = (
crate::os::plane(surface, 0).unwrap(),
crate::os::plane(surface, 1).unwrap(),
);
let base = surface.base_address().as_ptr::<u8>();
let (y_plane, c_plane) = (surface.plane(0), surface.plane(1));
let base = surface.base();
let element = self.container;
if self.packed {
return self.fill_packed(surface, size, luma, chroma);
@@ -581,14 +519,13 @@ impl Shape {
/// `10 (i mod 3)`.
fn fill_packed(
&self,
surface: &OsSurface,
surface: &Surface,
(width, height): (u64, u64),
luma: impl Fn(u64, u64) -> u16,
chroma: impl Fn(u64, u64) -> (u16, u16),
) {
use crate::core::platform::os::surface::Surface as _;
let base = surface.base_address().as_ptr::<u8>();
let write = |plane: &metal2vulkan_runtime::IoSurfacePlane, y: u64, i: u64, code: u16| {
let base = surface.base();
let write = |plane: &SurfacePlane, y: u64, i: u64, code: u16| {
let at = plane.offset + y * plane.bytes_per_row + i / 3 * 4;
let shift = 10 * (i % 3);
let at = usize::try_from(at).unwrap();
@@ -601,10 +538,7 @@ impl Shape {
word.write_unaligned((kept | code).to_le());
}
};
let (y_plane, c_plane) = (
crate::os::plane(surface, 0).unwrap(),
crate::os::plane(surface, 1).unwrap(),
);
let (y_plane, c_plane) = (surface.plane(0), surface.plane(1));
for y in 0..height {
for x in 0..width {
write(&y_plane, y, x, luma(x, y));
@@ -624,7 +558,7 @@ impl Shape {
/// sample's top bits with the low bits 0.
pub(crate) fn fill_codes(
&self,
surface: &OsSurface,
surface: &Surface,
size: (u64, u64),
luma: impl Fn(u64, u64) -> u16,
chroma: impl Fn(u64, u64) -> (u16, u16),
@@ -641,7 +575,7 @@ impl Shape {
}
/// Fills `surface` with `noise(seed)`'s samples, the low bits too.
pub(crate) fn fill_noise(&self, surface: &OsSurface, size: (u64, u64), seed: u64) {
pub(crate) fn fill_noise(&self, surface: &Surface, size: (u64, u64), seed: u64) {
let mut next = noise(seed);
let (width, height) = size;
let (chroma_width, chroma_height) = self.chroma_size(size);
@@ -2,29 +2,29 @@
//! Metal's ([`super::runtime_makes`]): what they read and sample, their IDs and usage, their
//! views, where the runtime cannot map their samplers, and what they show of writes of their
//! surfaces. The harness is [`super::measure`]'s.
use crate::core::platform::Platform;
use crate::core::platform::blit::{BlitCmd, BlitEncoder as _};
use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _};
use crate::core::platform::compute::{ComputeCmd, ComputeEncoder as _};
use crate::core::platform::device::GpuDevice as _;
use crate::core::platform::os::surface::Surface as _;
use crate::core::platform::resource::{Buffer as _, GpuResource as _, Library as _, Texture as _};
use crate::core::platform::types::{MtlOrigin, MtlSize, NsRange};
use crate::core::platform::values::TextureDesc;
use crate::core::platform::{Handle as _, Platform};
use crate::core::raise::OnFault;
use crate::core::raise::death::DeathKind;
use crate::core::testkit::capture::catch_death;
use metal2vulkan::metal::PixelFormat;
use super::measure::host::set_value;
use super::measure::Surface;
use super::measure::host::set_matrix;
use super::measure::{
self, PROBE, Shape, desc_505, fill_noise, float_bits, probe, probed, probed_texels, sampled,
sampled_floats, surface_420, surface_420_over,
};
use crate::gpu::device::VulkanDevice;
use crate::gpu::device::tests::dev;
use crate::gpu::resource::tests::StandIn;
use crate::gpu::resource::{VulkanComputePipeline, VulkanTexture};
use crate::os::{MATRIX_KEY, OsSurface};
use crate::platform::VulkanPlatform;
use crate::platform::tests::platform;
@@ -32,17 +32,11 @@ use crate::platform::tests::platform;
/// family's members.
const RGB8_420_2P: u64 = 540;
/// This platform's texture of `format` of `size` over `surface`.
fn ours(format: u64, surface: &OsSurface, size: (u64, u64)) -> VulkanTexture {
ours_on(&dev(), format, surface, size)
}
/// [`ours`] on the device `d`.
fn ours_on(d: &VulkanDevice, format: u64, surface: &OsSurface, size: (u64, u64)) -> VulkanTexture {
/// This platform's texture of `format` of `size` over `surface`, on the device the buffer that
/// stands for it is of.
fn ours(format: u64, surface: &Surface, size: (u64, u64)) -> VulkanTexture {
let desc = platform().texture_descriptor(&measure::desc(format, size));
d.new_texture_on_surface(&desc, Some(surface), 0)
.unwrap()
.unwrap()
surface.texture(&desc, 0).unwrap().unwrap()
}
/// The device whose samples of the family the comparisons with Metal's read: the platform's
@@ -152,9 +146,9 @@ fn family_samples_as_metals(format: u64) {
];
for matrix in matrices {
for (size, seed) in [((40, 24), 5), ((33, 17), 6)] {
let s = shape.surface(size);
let mut s = shape.surface(&dev(), size);
if let Some(m) = matrix {
set_value(&s, MATRIX_KEY, m);
set_matrix(&mut s, m);
}
shape.fill_noise(&s, size, seed);
let what = format!(
@@ -249,8 +243,8 @@ fn rows_overlap(format: u64, shape: &Shape, plane: u64, size: (u64, u64)) -> boo
..*shape
};
let row = own.row_bytes(size.0);
let planes = shape.spec(size).planes.unwrap();
let bytes_per_row = planes[usize::try_from(plane).unwrap()].bytes_per_row;
let (_, planes, _) = shape.layout(size);
let (_, bytes_per_row) = planes[usize::try_from(plane).unwrap()];
size.1 > 1 && row > 16 && bytes_per_row / 16 * 16 < row
}
@@ -262,7 +256,7 @@ fn rows_overlap(format: u64, shape: &Shape, plane: u64, size: (u64, u64)) -> boo
/// Metal's past it.
fn reads_as_metals_do(
format: u64,
(shape, s): (&Shape, &OsSurface),
(shape, s): (&Shape, &Surface),
plane: u64,
size: (u64, u64),
half_relayed: bool,
@@ -271,7 +265,7 @@ fn reads_as_metals_do(
let d = dev();
let desc = platform().texture_descriptor(&measure::desc(format, size));
*crate::answer::LAST_LINE.lock() = None;
let made = catch_death(|| d.new_texture_on_surface(&desc, Some(s), plane));
let made = catch_death(|| s.texture(&desc, plane));
let line = crate::answer::LAST_LINE.lock().take().unwrap_or_default();
let t = made.unwrap_or_else(|site| panic!("{what}: {site:?}: {line}"));
let t = t.unwrap().unwrap_or_else(|| panic!("nil: {what}"));
@@ -315,15 +309,15 @@ fn textures_over_other_ostypes_read_as_metals() {
let (_, own) = surfaces_of(format, true);
for ostype in OSTYPES.iter().filter(|o| !own.contains(o)) {
let shape = Shape::of(ostype);
let s = shape.surface(size);
let s = shape.surface(&dev(), size);
shape.fill_noise(&s, size, 9);
let what = format!("{format} over {}", String::from_utf8_lossy(&ostype[..]));
reads_as_metals_do(format, (&shape, &s), 0, size, false, &what);
}
for matrix in ["DCI_P3", "P3_D65"] {
let shape = Shape::of(own[0]);
let s = shape.surface(size);
set_value(&s, MATRIX_KEY, matrix);
let mut s = shape.surface(&dev(), size);
set_matrix(&mut s, matrix);
shape.fill_noise(&s, size, 10);
let what = format!(
"{format} over {} {matrix}",
@@ -335,7 +329,7 @@ fn textures_over_other_ostypes_read_as_metals() {
continue;
}
let desc = platform().texture_descriptor(&measure::desc(format, size));
let made = catch_death(|| dev().new_texture_on_surface(&desc, Some(&s), 0));
let made = catch_death(|| s.texture(&desc, 0));
let site = made.map(drop).unwrap_err();
let sel = "newTextureWithDescriptor:iosurface:plane:";
assert_eq!((site.kind, site.file), (DeathKind::Abort, sel), "{what}");
@@ -353,7 +347,7 @@ fn textures_over_plane_1_read_as_metals() {
for format in family() {
for ostype in OSTYPES {
let shape = Shape::of(ostype);
let s = shape.surface(size);
let s = shape.surface(&dev(), size);
shape.fill_noise(&s, size, 11);
let what = format!(
"{format} over plane 1 of {}",
@@ -408,9 +402,9 @@ type Probe = (State, Vec<u8>);
/// colour (alpha 1 at the border too), nearest samples under mirrored clamp to the edge,
/// repeat and mirrored repeat, and linear samples clamped to the edge, each into halves and
/// into floats.
fn sample_as_metals_do(format: u64, s: &OsSurface, size: (u64, u64), what: &str) {
fn sample_as_metals_do(format: u64, s: &Surface, size: (u64, u64), what: &str) {
let d = exact();
let t = ours_on(&d, format, s, size);
let t = ours(format, s, size);
assert_eq!(
(
t.pixel_format(),
@@ -421,10 +415,7 @@ fn sample_as_metals_do(format: u64, s: &OsSurface, size: (u64, u64), what: &str)
(format, 1, 0, 2),
"{what}"
);
assert_eq!(
(t.width(), t.height(), t.iosurface().map(|s| s.id())),
(size.0, size.1, Some(s.id()))
);
assert_eq!((t.width(), t.height()), (size.0, size.1));
type V = crate::platform::VulkanPlatform;
let ours_read = probed::<V>(&d, "read_texels", &t, size, None, None);
let ours_floats = measure::read_floats::<V>(&d, &t, size);
@@ -479,9 +470,9 @@ fn family_samples_in_fragments_as_metals(format: u64) {
];
for matrix in matrices {
let size = (33, 17);
let s = shape.surface(size);
let mut s = shape.surface(&dev(), size);
if let Some(m) = matrix {
set_value(&s, MATRIX_KEY, m);
set_matrix(&mut s, m);
}
shape.fill_noise(&s, size, 7);
let what = format!(
@@ -518,9 +509,9 @@ fn fragment_reads<P: Platform>(
/// [`sample_as_metals_do`]'s samples and gathers ([`cases`]) of a texture of `format` over `s`
/// in a fragment function ([`fragment_reads`]), compared with Metal's bit for bit.
fn samples_in_fragments_as_metals_do(format: u64, s: &OsSurface, size: (u64, u64), what: &str) {
fn samples_in_fragments_as_metals_do(format: u64, s: &Surface, size: (u64, u64), what: &str) {
let (p, d) = (platform(), exact());
let t = ours_on(&d, format, s, size);
let t = ours(format, s, size);
let (grid, cases) = cases(size);
let ours = fragment_reads::<VulkanPlatform>(&p, &d, &t, grid, &cases);
let keys = |(state, bytes): &Probe| {
@@ -630,9 +621,9 @@ fn views_in_srgb_twins_read_as_metals() {
Some("SMPTE_240M_1995"),
];
for matrix in matrices {
let s = shape.surface(size);
let mut s = shape.surface(&dev(), size);
if let Some(m) = matrix {
set_value(&s, MATRIX_KEY, m);
set_matrix(&mut s, m);
}
shape.fill_noise(&s, size, 8);
let what = format!(
@@ -733,7 +724,7 @@ fn own_format_views_are_metals() {
for format in family() {
let (_, ostypes) = surfaces_of(format, true);
let shape = Shape::of(ostypes[0]);
let s = shape.surface(size);
let s = shape.surface(&dev(), size);
shape.fill_noise(&s, size, 12);
let t = ours(format, &s, size);
for swizzle in [None, Some(BGRA)] {
@@ -751,7 +742,7 @@ fn own_format_views_are_metals() {
);
let array = view::<VulkanPlatform>(&t, format, (3, swizzle)).unwrap();
crate::metal_check!(array_key, (array.texture_type(), array.usage()));
let filtered = ours_on(&e, format, &s, size);
let filtered = self::ours(format, &s, size);
let filtered = view::<VulkanPlatform>(&filtered, format, (3, swizzle)).unwrap();
for sample in [None, Some((0, 0)), Some((1, 0)), Some((0, 1)), Some((0, 2))] {
let (on, subject) = match sample {
@@ -804,10 +795,10 @@ fn samples_under_every_mode_as_metals(format: u64, ostypes: [&[u8; 4]; 2]) {
let size = (40, 24);
for ostype in ostypes {
let shape = Shape::of(ostype);
let s = shape.surface(size);
let s = shape.surface(&dev(), size);
shape.fill_noise(&s, size, 7);
let d = exact();
let t = ours_on(&d, format, &s, size);
let t = ours(format, &s, size);
let grid = ((size.0 + 2) * 3, (size.1 + 2) * 3);
type V = crate::platform::VulkanPlatform;
for (read, filter) in [(0, 0), (0, 1), (1, 0), (2, 0)] {
@@ -906,9 +897,9 @@ fn the_default_filter_samples_within_its_bound_of_metals() {
let linear = (1, 0, true, 0);
let mut seen = Vec::new();
for (format, steps) in [(500, 2048.0_f32), (520, 8192.0)] {
let s = surface_420(b"420v", size);
let s = surface_420(&dev(), b"420v", size);
fill_noise(&s, size, 9);
let t = ours_on(&d, format, &s, size);
let t = ours(format, &s, size);
*LAST_LINE.lock() = None;
let strict = catch_death(|| sampled_floats::<V>(&d, &t, linear, grid, &bytes))
.err()
@@ -1011,10 +1002,10 @@ fn the_default_filter_samples_within_its_bound_of_metals() {
)]
fn the_guests_id_is_metals() {
use crate::core::platform::event::SharedEvent as _;
fn ids<P: Platform<Surface = OsSurface>>(
fn ids<P: Platform>(
d: &P::Device,
descriptor: impl Fn(&TextureDesc) -> P::TextureDescriptor,
s: &OsSurface,
s: &StandIn<P>,
size: (u64, u64),
read_held: bool,
) -> (Vec<u64>, Vec<u8>) {
@@ -1030,10 +1021,7 @@ fn the_guests_id_is_metals() {
};
let first = plain();
let desc = descriptor(&desc_505(size));
let t = d
.new_texture_on_surface(&desc, Some(s), 0)
.unwrap()
.unwrap();
let t = s.texture(&desc, 0).unwrap().unwrap();
let second = plain();
let held = match read_held {
true => held::<P>(d, &t, size),
@@ -1054,7 +1042,7 @@ fn the_guests_id_is_metals() {
(ids, held)
}
let size = (24, 16);
let s = surface_420(b"xf20", size);
let s = surface_420(&dev(), b"xf20", size);
fill_noise(&s, size, 8);
// Metal's first, before this platform's runtime makes any Metal texture of its own in
// the process, which would take IDs of Metal's pool.
@@ -1087,14 +1075,14 @@ fn the_guests_id_is_metals() {
#[test]
fn usage_bits_metal_takes_are_answered_as_metals() {
let size = (16, 8);
let s = surface_420(b"x420", size);
let s = surface_420(&dev(), b"x420", size);
for (usage, answered) in [(0x1_0005, 0x1_0005), (0x1_c00d, 0x1_c005)] {
let desc = TextureDesc {
usage,
..desc_505(size)
};
let t = dev()
.new_texture_on_surface(&platform().texture_descriptor(&desc), Some(&s), 0)
let t = s
.texture(&platform().texture_descriptor(&desc), 0)
.unwrap()
.unwrap();
assert_eq!(t.usage(), answered, "{usage:#x}");
@@ -1214,7 +1202,7 @@ fn held<P: Platform>(d: &P::Device, t: &P::Texture, (width, height): (u64, u64))
#[test]
fn sampling_a_mapped_texture_where_the_runtime_cannot_map_it_dies() {
let size = (16, 8);
let s = surface_420(b"x420", size);
let s = surface_420(&dev(), b"x420", size);
fill_noise(&s, size, 9);
let d = dev();
let p = platform();
@@ -1345,9 +1333,9 @@ fn constexpr_samplers_sample_as_metals() {
let mut differ = Vec::new();
for (format, ostype, in_place) in cases {
let shape = Shape::of(ostype);
let s = shape.surface(size);
let s = shape.surface(&dev(), size);
shape.fill_noise(&s, size, 11);
let t = ours_on(&d, format, &s, size);
let t = ours(format, &s, size);
for kernel in kernels {
let read = |bytes_read: Vec<u8>| -> Vec<[u32; 4]> {
(measure::float_texels(&bytes_read).into_iter())
@@ -1433,19 +1421,15 @@ enum Write {
/// `read_texels` of a texture of `format` over `s` after `write` wrote half the surface's luma,
/// on `p`'s device `d` (`descriptor` makes `p`'s texture descriptors).
fn after<P: Platform<Surface = OsSurface>>(
fn after<P: Platform>(
d: &P::Device,
(format, descriptor): (u64, impl Fn(&TextureDesc) -> P::TextureDescriptor),
s: &OsSurface,
s: &StandIn<P>,
(width, height): (u64, u64),
write: Write,
) -> Vec<u8> {
let t = d
.new_texture_on_surface(
&descriptor(&measure::desc(format, (width, height))),
Some(s),
0,
)
let t = s
.texture(&descriptor(&measure::desc(format, (width, height))), 0)
.unwrap()
.unwrap();
let fenced = matches!(write, Write::Fenced | Write::FencedCommandBuffer);
@@ -1459,10 +1443,7 @@ fn after<P: Platform<Surface = OsSurface>>(
resource_options: Some(if fenced { 0x100 } else { 0 }),
..TextureDesc::default()
};
let luma = d
.new_texture_on_surface(&descriptor(&luma), Some(s), 0)
.unwrap()
.unwrap();
let luma = s.texture(&descriptor(&luma), 0).unwrap().unwrap();
let library = d.new_library(PROBE).unwrap().unwrap().unwrap();
let kernel = |name| {
let f = library.new_function(OnFault::Die, name).unwrap().unwrap();
@@ -1581,7 +1562,7 @@ fn after<P: Platform<Surface = OsSurface>>(
}),
Write::Cpu => {
run(&read);
let base = s.base_address().as_ptr::<u8>();
let base = s.base();
let n = usize::try_from(width * 2).unwrap();
// SAFETY: plane 0's first row, inside the surface's allocation, which no GPU
// work uses now.
@@ -1622,7 +1603,7 @@ fn samples_see_the_writes_before_them() {
Write::FencedCommandBuffer,
] {
let surface = || {
let s = surface_420(b"x420", size);
let s = surface_420(&dev(), b"x420", size);
fill_noise(&s, size, 11);
s
};
@@ -1632,10 +1613,7 @@ fn samples_see_the_writes_before_them() {
let before = {
let d = dev();
let desc = p.texture_descriptor(&measure::desc(format, size));
let t = d
.new_texture_on_surface(&desc, Some(&unwritten), 0)
.unwrap()
.unwrap();
let t = unwritten.texture(&desc, 0).unwrap().unwrap();
probed::<VulkanPlatform>(&d, "read_texels", &t, size, None, None)
};
let ours = after::<VulkanPlatform>(
@@ -1663,19 +1641,19 @@ enum Before {
}
/// `read_texels` of a texture of 505 over `s`, after work `before` it zeroed the first luma
/// row through a buffer `newBufferWithIOSurface:` makes over `s`, on `p`'s device `d`.
fn through<P: Platform<Surface = OsSurface>>(
/// row through the buffer that stands for `s`, on `p`'s device `d`.
fn through<P: Platform>(
d: &P::Device,
descriptor: impl Fn(&TextureDesc) -> P::TextureDescriptor,
s: &OsSurface,
s: &StandIn<P>,
(width, height): (u64, u64),
before: Before,
) -> Vec<u8> {
let t = d
.new_texture_on_surface(&descriptor(&desc_505((width, height))), Some(s), 0)
let t = s
.texture(&descriptor(&desc_505((width, height))), 0)
.unwrap()
.unwrap();
let over = d.new_buffer_on_surface(Some(s)).unwrap().unwrap();
let over = &s.buffer;
let library = d.new_library(PROBE).unwrap().unwrap().unwrap();
let kernel = |name| {
let f = library.new_function(OnFault::Die, name).unwrap().unwrap();
@@ -1690,7 +1668,7 @@ fn through<P: Platform<Surface = OsSurface>>(
.unwrap()
.unwrap();
let q = d.new_command_queue().unwrap();
let (written, read) = ([Some(&over)], [Some(&out)]);
let (written, read) = ([Some(over)], [Some(&out)]);
let mut cb = q.command_buffer(OnFault::Die).unwrap().unwrap();
let mut e = cb.compute_encoder(OnFault::Die).unwrap().unwrap();
for cmd in [
@@ -1748,16 +1726,16 @@ fn through<P: Platform<Surface = OsSurface>>(
unsafe { std::slice::from_raw_parts(out.contents().as_ptr::<u8>(), n) }.to_vec()
}
/// A kernel's write of a surface's bytes through a buffer `newBufferWithIOSurface:` made over
/// it, of a surface over the guest's pages, reaches the surface through its own mapping:
/// Metal's read of a texture of 505 over it shows the write in the same command buffer, after
/// a barrier or in a later encoder, as in a later one, and so does this platform's
/// A kernel's write of a surface's bytes through a buffer over it, of a surface over the guest's
/// pages, reaches a texture over it: Metal's read of a texture of 505 over it shows the write in
/// the same command buffer, after a barrier or in a later encoder, as in a later one, and so does
/// this platform's, through the buffer that stands for the surface
#[test]
fn a_write_through_a_buffer_on_the_surface_shows_in_the_same_command_buffer() {
use crate::core::platform::os::vm::HostVm as _;
let size = (32, 16);
let read = |p: &dyn Fn(&OsSurface) -> Vec<u8>| {
let (s, pages, length) = surface_420_over(b"x420", size);
let read = |p: &dyn Fn(&Surface) -> Vec<u8>| {
let (s, pages, length) = surface_420_over(&dev(), b"x420", size);
fill_noise(&s, size, 13);
let read = p(&s);
drop(s);
@@ -1772,8 +1750,8 @@ fn a_write_through_a_buffer_on_the_surface_shows_in_the_same_command_buffer() {
all.map(|before| read(&|s| through::<VulkanPlatform>(&dev(), descriptor, s, size, before)));
let unwritten = read(&|s| {
let d = dev();
let t = d
.new_texture_on_surface(&p.texture_descriptor(&desc_505(size)), Some(s), 0)
let t = s
.texture(&p.texture_descriptor(&desc_505(size)), 0)
.unwrap()
.unwrap();
probed::<VulkanPlatform>(&d, "read_texels", &t, size, None, None)
@@ -1787,10 +1765,10 @@ fn a_write_through_a_buffer_on_the_surface_shows_in_the_same_command_buffer() {
/// dispatch as Metal's is
#[test]
fn a_texture_made_in_an_encoder_reads_as_metals() {
fn read<P: Platform<Surface = OsSurface>>(
fn read<P: Platform>(
d: &P::Device,
descriptor: impl Fn(&TextureDesc) -> P::TextureDescriptor,
s: &OsSurface,
s: &StandIn<P>,
(width, height): (u64, u64),
) -> Vec<u8> {
let library = d.new_library(PROBE).unwrap().unwrap().unwrap();
@@ -1810,8 +1788,8 @@ fn a_texture_made_in_an_encoder_reads_as_metals() {
let q = d.new_command_queue().unwrap();
let cb = q.command_buffer(OnFault::Die).unwrap().unwrap();
let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap();
let t = d
.new_texture_on_surface(&descriptor(&desc_505((width, height))), Some(s), 0)
let t = s
.texture(&descriptor(&desc_505((width, height))), 0)
.unwrap()
.unwrap();
let buffers = [Some(&out)];
@@ -1843,7 +1821,7 @@ fn a_texture_made_in_an_encoder_reads_as_metals() {
unsafe { std::slice::from_raw_parts(out.contents().as_ptr::<u8>(), n) }.to_vec()
}
let size = (24, 16);
let s = surface_420(b"x420", size);
let s = surface_420(&dev(), b"x420", size);
fill_noise(&s, size, 12);
// Metal's first, before this platform's runtime makes any texture of its own.
let p = platform();
@@ -1921,33 +1899,31 @@ impl Op {
}
/// The bytes of `surface`, all of its allocation.
fn bytes_of(surface: &OsSurface) -> Vec<u8> {
let length = usize::try_from(surface.alloc_size()).unwrap();
// SAFETY: the surface's allocation, read once the work that wrote it completed.
unsafe { std::slice::from_raw_parts(surface.base_address().as_ptr::<u8>(), length) }.to_vec()
fn bytes_of<P: Platform>(surface: &StandIn<P>) -> Vec<u8> {
surface.bytes(surface.length())
}
/// What `op` writes of a texture of `format` of `size` over plane 0 of `s` on `p`'s device `d`
/// (`other` a second surface of its shape): the bytes of `s`, of `other`, and of a `Shared`
/// buffer of 8 bytes a texel that held a pattern first, once the work completed.
pub(crate) fn written<P: Platform<Surface = OsSurface>>(
pub(crate) fn written<P: Platform>(
p: &P,
d: &P::Device,
op: Op,
format: u64,
surfaces: (&OsSurface, &OsSurface),
surfaces: (&StandIn<P>, &StandIn<P>),
size: (u64, u64),
) -> [Vec<u8>; 3] {
written_at(p, d, (op, 0), format, surfaces, size)
}
/// What `op` writes as [`written`] says, of a texture over plane `plane` of `s`.
fn written_at<P: Platform<Surface = OsSurface>>(
fn written_at<P: Platform>(
p: &P,
d: &P::Device,
(op, plane): (Op, u64),
format: u64,
(s, other): (&OsSurface, &OsSurface),
(s, other): (&StandIn<P>, &StandIn<P>),
size: (u64, u64),
) -> [Vec<u8>; 3] {
use crate::core::platform::HostRange;
@@ -1968,10 +1944,7 @@ fn written_at<P: Platform<Surface = OsSurface>>(
_ => 0x1,
};
let desc = p.texture_descriptor(&desc);
let t = d
.new_texture_on_surface(&desc, Some(s), plane)
.unwrap()
.unwrap();
let t = s.texture(&desc, plane).unwrap().unwrap();
let q = d.new_command_queue().unwrap();
let (w, h) = size;
let row = w * 8;
@@ -2031,10 +2004,7 @@ fn written_at<P: Platform<Surface = OsSurface>>(
destination_origin: origin,
}),
Op::Copy => {
let to = d
.new_texture_on_surface(&desc, Some(other), 0)
.unwrap()
.unwrap();
let to = other.texture(&desc, 0).unwrap().unwrap();
blit(BlitCmd::CopyTextureRegion {
source_texture: &t,
source_slice: 0,
@@ -2219,15 +2189,15 @@ fn written_at<P: Platform<Surface = OsSurface>>(
/// Two surfaces of `format`'s first OSType of its own bits and chroma, of `size`, filled with
/// noise of `seed` and of the next.
fn noisy_pair(format: u64, size: (u64, u64), seed: u64) -> (OsSurface, OsSurface) {
fn noisy_pair(format: u64, size: (u64, u64), seed: u64) -> (Surface, Surface) {
let (_, ostypes) = surfaces_of(format, true);
noisy_pair_of(ostypes[0], size, seed)
}
/// Two surfaces of `ostype`, of `size`, filled with noise of `seed` and of the next.
fn noisy_pair_of(ostype: &[u8; 4], size: (u64, u64), seed: u64) -> (OsSurface, OsSurface) {
fn noisy_pair_of(ostype: &[u8; 4], size: (u64, u64), seed: u64) -> (Surface, Surface) {
let shape = Shape::of(ostype);
let (s, other) = (shape.surface(size), shape.surface(size));
let (s, other) = (shape.surface(&dev(), size), shape.surface(&dev(), size));
shape.fill_noise(&s, size, seed);
shape.fill_noise(&other, size, seed + 1);
(s, other)
@@ -2494,11 +2464,10 @@ fn odd_render_targets_of_subsampled_formats_are_nil_as_metals() {
let f = metal2vulkan::metal::format::ycbcr_format(pf).unwrap();
let subsampled = f.subsampling.halved().contains(&true);
for size in [(33, 17), (33, 16), (32, 17)] {
let s = Shape::of(ostypes[0]).surface(size);
let s = Shape::of(ostypes[0]).surface(&dev(), size);
let mut desc = measure::desc(format, size);
desc.usage = 0x5;
let ours =
dev().new_texture_on_surface(&platform().texture_descriptor(&desc), Some(&s), 0);
let ours = s.texture(&platform().texture_descriptor(&desc), 0);
let what = format!("{format} of {size:?}");
assert_eq!(ours.unwrap().is_some(), !subsampled, "{what}");
}
@@ -2566,35 +2535,6 @@ fn writes_of_444_textures_are_metals() {
}
}
/// A kernel's `write()` into a texture over a surface of a 4:4:4 format of the family whose
/// writes the runtime refuses dies at the dispatch, naming the write and the format: the `_sRGB`
/// twins 523 and 527, whose planes Metal's changes
#[test]
fn writes_the_runtime_refuses_die() {
let size = (32, 16);
let refused = family().into_iter().filter(|&f| {
super::writes_refused(PixelFormat::try_from(u32::try_from(f).unwrap()).unwrap())
});
let refused: Vec<u64> = refused.collect();
assert_eq!(refused, [523, 527]);
for format in refused {
let pf = PixelFormat::try_from(u32::try_from(format).unwrap()).unwrap();
let (s, other) = noisy_pair(format, size, 9);
*crate::answer::LAST_LINE.lock() = None;
let site =
catch_death(|| written(&platform(), &dev(), Op::Kernel, format, (&s, &other), size))
.unwrap_err();
let line = crate::answer::LAST_LINE.lock().take().unwrap_or_default();
assert_eq!(
(site.kind, site.file),
(DeathKind::Abort, Op::Kernel.sel()),
"{format}: {line}"
);
assert!(line.contains(&format!("a texture of {pf:?}")), "{line}");
assert!(line.contains("the runtime refuses"), "{line}");
}
}
/// A kernel's `write()` into a texture of 503, 507, 542 or 545 over plane 1 of a surface, which
/// the runtime makes, dies at the dispatch, naming the runtime's refusal (`Format`): it stores
/// such a texture's writes over plane 0 alone, and Metal's over plane 1 are not measured
@@ -2634,7 +2574,7 @@ fn every_luma_code_of_505_reads_as_metals() {
let d = dev();
for ostype in [b"x420", b"xf20"] {
let shape = Shape::of(ostype);
let s = shape.surface(size);
let s = shape.surface(&dev(), size);
shape.fill_codes(
&s,
size,
@@ -9,7 +9,7 @@ use crate::core::platform::values::{BufferDesc, HeapDesc, OptionSet, TextureDesc
use crate::core::raise::OnFault;
use super::*;
use crate::os::tests::bgra_surface;
use crate::gpu::resource::tests::StandIn;
use crate::platform::tests::platform;
/// The two formats measured first (the module's docs): `YCBCR10_420_2P` (505) and
@@ -310,10 +310,10 @@ fn textures_die_where_made() {
/// [`textures_die_where_made`] of `format`.
fn die_where_made(format: u64) {
let d = dev();
let s = bgra_surface(16, 16);
let s = StandIn::<crate::platform::VulkanPlatform>::bgra(&dev(), 16, 16);
let desc = ycbcr(format, |_| {});
let ours = platform().texture_descriptor(&desc);
let site = catch_death(|| d.new_texture_on_surface(&ours, Some(&s), 0)).unwrap_err();
let site = catch_death(|| s.texture(&ours, 0)).unwrap_err();
assert_eq!(
(site.kind, site.file),
(
+1 -6
View File
@@ -43,10 +43,6 @@ pub(crate) use host_os::take_ram_devices;
/// (`os/linux/thread_counts.rs`).
#[cfg(all(test, target_os = "linux"))]
pub(crate) use host_os::thread_counts;
/// Whether a view of several runs of pages made now is mapped through dma-bufs, on Linux
/// (`os/linux/import.rs`).
#[cfg(all(test, target_os = "linux"))]
pub(crate) use host_os::views_through_dma_bufs;
pub(crate) use host_os::{
COPIES_READ_ONLY, Drawables, ImportMade, ImportView, TWINS_READ_ONLY, allocate_aliasable,
allocate_zeros, dma_buf_refusal, host_memory, host_memory_vouched, import_view, plane_shape,
@@ -77,8 +73,6 @@ pub(crate) use host_os::{
/// (`os/linux/dma_buf.rs`).
#[cfg(target_os = "linux")]
pub(crate) use host_os::{one_dma_buf_fits, one_dma_buf_of_fits, one_dma_buf_of_pieces_fits};
#[cfg(all(test, target_os = "macos"))]
pub(crate) use macos::MATRIX_KEY;
/// The Objective-C message layer the window's AppKit side sends through, on macOS
/// (`os/macos/msg.rs`).
#[cfg(target_os = "macos")]
@@ -160,6 +154,7 @@ impl Drop for PrivateMemory {
#[cfg(test)]
pub(crate) mod tests {
// The surface tests' helpers, which the crate's tests name here.
#[cfg(target_os = "macos")]
pub(crate) use super::surface::tests::*;
use super::*;
-2
View File
@@ -42,8 +42,6 @@ pub(crate) use host_ram::{
copies as copies_guest_ram, copy_from_host_ram, copy_runs_from_host_ram, copy_to_host_ram,
ram_over, take_devices as take_ram_devices,
};
#[cfg(test)]
pub(crate) use import::views_through_dma_bufs;
pub(crate) use import::{
COPIES_READ_ONLY, ImportMade, ImportView, TWINS_READ_ONLY, allocate_zeros, dma_buf_refusal,
host_memory, host_memory_vouched, import_view, learn_view_imports, shown_at,
@@ -140,20 +140,16 @@ fn pages_of(
mod tests {
use std::os::fd::AsRawFd as _;
use crate::core::host::PhysicalMemoryRange;
use crate::core::host::HostPtr;
use crate::core::num::ToUsize as _;
use crate::core::platform::os::surface::{IoSurfaces as _, Surface as _, SurfaceSpec};
use crate::core::platform::os::vm::HostVm as _;
use super::super::surface::LinuxSurfaces;
use super::super::vm::{LinuxVm, allocate_aliasable};
use super::*;
const BGRA: u32 = u32::from_be_bytes(*b"BGRA");
/// `count` fresh pages a view can be made of, each byte its page's index, and the ranges of
/// `count` fresh pages a view can be made of, each byte its page's index, and the runs of
/// them a guest's surface names, last first, so that its view is of pages out of order.
fn scattered_pages(count: u64) -> (u64, Vec<PhysicalMemoryRange>) {
fn scattered_pages(count: u64) -> (u64, Vec<(HostPtr, u64)>) {
let page = vm::page_size();
let at = allocate_aliasable(count * page).unwrap().addr().to_u64();
for i in 0..count {
@@ -166,31 +162,21 @@ mod tests {
);
}
}
let ranges = (0..count)
let runs = (0..count)
.rev()
.map(|i| PhysicalMemoryRange {
physical_address: at + i * page,
physical_length: page,
})
.map(|i| (HostPtr::from_addr((at + i * page).to_usize()), page))
.collect();
(at, ranges)
(at, runs)
}
fn over(ranges: &[PhysicalMemoryRange]) -> SurfaceSpec {
let page = vm::page_size();
SurfaceSpec {
pixel_format: BGRA,
alloc_size: ranges.len().to_u64() * page,
offset: 0x40,
width: 16,
height: 16,
bytes_per_element: 4,
bytes_per_row: 64,
element_width: 1,
element_height: 1,
client_address_ranges: Some(ranges.to_vec()),
..SurfaceSpec::default()
}
/// A view of `runs`' pages in their order, made as the device's views of a guest's pages are
/// (`remap_runs_shared_overwrite`): its first byte, freed with [`free`].
fn view_of(runs: &[(HostPtr, u64)]) -> u64 {
let vm = LinuxVm::new();
let length = runs.iter().map(|&(_, length)| length).sum();
let at = vm.allocate_anywhere(length).unwrap();
assert!(vm.remap_runs_shared_overwrite(at, runs).is_ok());
at.addr().to_u64()
}
fn read(at: u64) -> u8 {
@@ -224,20 +210,19 @@ mod tests {
}
}
/// A dma-buf of ranges of a surface's view holds the pages each lies in, in order, a page two
/// share once, and says where each range starts in it: a write there reaches the guest's page
/// the view shows at that range
/// A dma-buf of ranges of a view of a guest's pages holds the pages each lies in, in order, a
/// page two share once, and says where each range starts in it: a write there reaches the
/// guest's page the view shows at that range
#[test]
fn a_dma_buf_of_ranges_holds_their_pages_in_order() {
let page = vm::page_size();
let (at, ranges) = scattered_pages(4);
let s = LinuxSurfaces::new().create(&over(&ranges)).unwrap();
let base = s.base_address().addr();
let lent = NonNull::new(std::ptr::with_exposed_provenance_mut::<u8>(base)).unwrap();
let first = base.to_u64() - 0x40;
// From the surface's base address, 0x40 into its view's first page: a range in its first
// page, one in its third, and one starting in that third page's last bytes and ending in
// the fourth.
let (at, runs) = scattered_pages(4);
let first = view_of(&runs);
let base = first + 0x40;
let lent =
NonNull::new(std::ptr::with_exposed_provenance_mut::<u8>(base.to_usize())).unwrap();
// From 0x40 into the view's first page: a range in its first page, one in its third, and
// one starting in that third page's last bytes and ending in the fourth.
let wanted = [
(0x100, 0x200),
(2 * page, 0x100),
@@ -258,7 +243,7 @@ mod tests {
}
Err(why) => eprintln!("no dma-buf here, the rest checked: {why:?}"),
}
drop(s);
free(first, 4 * page);
free(at, 4 * page);
}
@@ -267,9 +252,8 @@ mod tests {
#[test]
fn a_dma_buf_of_host_memory_holds_the_pages_its_mapping_shows() {
let page = vm::page_size();
let (at, ranges) = scattered_pages(3);
let s = LinuxSurfaces::new().create(&over(&ranges)).unwrap();
let view = s.base_address().addr().to_u64() - 0x40;
let (at, runs) = scattered_pages(3);
let view = view_of(&runs);
let first =
NonNull::new(std::ptr::with_exposed_provenance_mut::<u8>(view.to_usize())).unwrap();
match dma_buf_of_host(first, 3 * page, &[(page + 0x80, 0x100)]) {
@@ -300,7 +284,7 @@ mod tests {
);
// SAFETY: the mapping made above, which nothing holds.
unsafe { libc::munmap(anonymous, page.to_usize()) };
drop(s);
free(view, 3 * page);
free(at, 3 * page);
}
+1 -52
View File
@@ -675,60 +675,9 @@ impl IoSurfaces<VulkanPlatform> for VulkanSurfaces {
#[cfg(test)]
mod tests {
use crate::core::num::ToU64;
use super::*;
use crate::os::tests::{bgra_surface, bgra_surface_over_at, free};
use crate::os::{surface_bytes_memory, surface_memory, surface_offset};
/// A surface over the guest's pages at an offset into its allocation (`kIOSurfaceOffset`)
/// has its base address that offset into its allocation, which is another mapping of the
/// pages: a write through its base address shows in the pages at the offset, and its
/// memory and its bytes' are found there
#[test]
fn an_offset_surface_is_at_its_offset_into_its_pages() {
use crate::core::platform::os::vm::HostVm as _;
for offset in [0x40, 0x1000, 0x4000] {
let (s, pages, length) =
crate::gpu::ycbcr::measure::surface_420_over_at(b"x420", (32, 16), offset);
let (first, base) = (
pages.addr().to_u64(),
s.base_address().as_ptr::<u8>().addr().to_u64(),
);
assert_eq!(s.alloc_size(), length, "{offset:#x}");
// SAFETY: the surface's first byte, which nothing else uses.
unsafe { s.base_address().as_ptr::<u8>().write(0xab) };
// SAFETY: the test's pages, mapped until they are freed below.
let at = unsafe {
pages
.as_ptr::<u8>()
.add(usize::try_from(offset).unwrap())
.read()
};
assert_eq!(
at, 0xab,
"{offset:#x}: the base address is the offset into the pages"
);
let memory = surface_memory(&s);
assert_eq!(
memory[0],
base - offset..base - offset + length,
"{offset:#x}"
);
let (mapped, read) = (first..first + length, 0x10..0x20);
assert_eq!(memory[1..], [mapped], "{offset:#x}");
assert_eq!(
surface_bytes_memory(&s, &[read]),
[
base + 0x10..base + 0x20,
first + offset + 0x10..first + offset + 0x20
],
"{offset:#x}"
);
drop(s);
MacVm::new().deallocate(pages, length);
}
}
use crate::os::{surface_memory, surface_offset};
/// The records of live surfaces outlast the dropping of those of surfaces gone, which runs
/// as the records grow past 64
@@ -285,6 +285,7 @@ pub(crate) mod tests {
}
/// A host-only 'BGRA' surface of `width` × `height`, 4 bytes an element, rows of `width × 4`.
#[cfg(target_os = "macos")]
pub(crate) fn bgra_surface(width: u64, height: u64) -> OsSurface {
let spec = SurfaceSpec {
pixel_format: u32::from_be_bytes(*b"BGRA"),
+1 -1
View File
@@ -1162,7 +1162,7 @@ pub(crate) mod tests {
#[test]
fn services() {
let p = platform();
let _ = (p.surfaces(), p.vm(), p.clock(), p.threads());
let _ = (p.vm(), p.clock(), p.threads());
assert!(format!("{p:?}").contains("VulkanPlatform"));
let page = if cfg!(target_os = "macos") {
16384
+22 -16
View File
@@ -3,7 +3,9 @@
//! Metal makes a texture with no GPU work: a texture over an IOSurface (as a guest display's
//! mapped present makes one) and a texture of memory of its own come back while a committed
//! kernel still runs. So does the runtime's: it records a new image's move to its first layout
//! in the device's next submission.
//! in the device's next submission. The surface is the buffer that stands for it
//! (`Buffer::new_texture_over_surface_plane`), as the reims-graphics device's surfaces reach this
//! platform.
//!
//! The kernel ([`SPIN`]) runs [`ROUNDS`] rounds of busy work, about half a second, then marks its
//! end in a word the test reads as each creation returns: still unmarked where the creation did
@@ -37,10 +39,9 @@ use reims_vgpu_vulkan::core::platform::command::{CommandBuffer, CommandQueue};
use reims_vgpu_vulkan::core::platform::compute::{ComputeCmd, ComputeEncoder};
use reims_vgpu_vulkan::core::platform::device::GpuDevice;
use reims_vgpu_vulkan::core::platform::os::clock::{Clock, MonoTime};
use reims_vgpu_vulkan::core::platform::os::surface::SurfaceSpec;
use reims_vgpu_vulkan::core::platform::resource::{Buffer, Library};
use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, MtlSize, NsRange};
use reims_vgpu_vulkan::core::platform::values::TextureDesc;
use reims_vgpu_vulkan::core::platform::values::{SurfaceFacts, SurfacePlane, TextureDesc};
use reims_vgpu_vulkan::core::raise::OnFault;
/// The kernel that keeps the GPU busy (`src/gpu/spin.metal`).
@@ -124,20 +125,25 @@ fn textures_while_a_kernel_runs<P: Platform>(p: &P, d: &P::Device) -> Seen {
cb.wait_until_scheduled().unwrap();
let (width, height) = (64, 16);
let surface = p
.surfaces()
.create(&SurfaceSpec {
let surface = d
.new_buffer_of_length(OnFault::Die, 0x4000, SHARED)
.unwrap()
.unwrap();
let plane = SurfacePlane {
plane: 0,
offset: 0,
bytes_per_row: width * 4,
planar: false,
facts: Some(SurfaceFacts {
pixel_format: u32::from_be_bytes(*b"BGRA"),
alloc_size: 0x4000,
plane_count: 0,
width,
height,
bytes_per_element: 4,
bytes_per_row: width * 4,
element_width: 1,
element_height: 1,
..SurfaceSpec::default()
})
.unwrap();
chroma_offset: 0,
chroma_bytes_per_row: 0,
ycbcr_matrix: None,
}),
};
let on_surface = p.texture_descriptor(&TextureDesc {
pixel_format: BGRA8,
width,
@@ -149,8 +155,8 @@ fn textures_while_a_kernel_runs<P: Platform>(p: &P, d: &P::Device) -> Seen {
let clock = p.clock();
let since = |at: MonoTime| Duration::from_nanos(clock.now_mono().as_nanos() - at.as_nanos());
let at = clock.now_mono();
let over = d
.new_texture_on_surface(&on_surface, Some(&surface), 0)
let over = surface
.new_texture_over_surface_plane(OnFault::Die, &on_surface, plane)
.unwrap()
.unwrap();
let made = |at: MonoTime| Made {