From 4585dc4e3387108e6b7a977d7bcf435f5d7aa284 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 08:42:27 -0800 Subject: [PATCH] :white_check_mark: 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. --- crates/reims-vgpu-vulkan/src/gpu/device.rs | 409 ------- .../src/gpu/device/tests/metal_tests.rs | 293 ++--- .../gpu/encode_render/tests/metal_tests.rs | 49 +- .../src/gpu/no_texture/tests/metal_tests.rs | 17 +- crates/reims-vgpu-vulkan/src/gpu/resource.rs | 358 +++--- .../src/gpu/resource/tests/metal_tests.rs | 1054 +---------------- crates/reims-vgpu-vulkan/src/gpu/writes.rs | 37 +- .../src/gpu/ycbcr/measure.rs | 83 +- .../src/gpu/ycbcr/measure/host.rs | 162 +-- .../src/gpu/ycbcr/sampling.rs | 232 ++-- .../src/gpu/ycbcr/tests/metal_tests.rs | 6 +- crates/reims-vgpu-vulkan/src/os.rs | 7 +- crates/reims-vgpu-vulkan/src/os/linux.rs | 2 - .../src/os/linux/device_lend.rs | 72 +- crates/reims-vgpu-vulkan/src/os/macos.rs | 53 +- crates/reims-vgpu-vulkan/src/os/surface.rs | 1 + crates/reims-vgpu-vulkan/src/platform.rs | 2 +- crates/reims-vgpu-vulkan/tests/new_images.rs | 38 +- 18 files changed, 611 insertions(+), 2264 deletions(-) diff --git a/crates/reims-vgpu-vulkan/src/gpu/device.rs b/crates/reims-vgpu-vulkan/src/gpu/device.rs index 9e89a8482..067c53096 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/device.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/device.rs @@ -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::().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::() - .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 diff --git a/crates/reims-vgpu-vulkan/src/gpu/device/tests/metal_tests.rs b/crates/reims-vgpu-vulkan/src/gpu/device/tests/metal_tests.rs index 15667bf26..1ef2ae0a5 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/device/tests/metal_tests.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/device/tests/metal_tests.rs @@ -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> { 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( 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::(&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::(&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> { 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::(&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::::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>| { *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>( +fn cleared( p: &P, d: &P::Device, format: u64, - surface: &crate::os::OsSurface, + surface: &StandIn

, (size, options): ((u64, u64), u64), color: crate::core::platform::types::ClearColor, length: u64, @@ -578,8 +578,8 @@ fn cleared>( 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>( 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::(); + 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>( +fn filled( p: &P, d: &P::Device, format: u64, - surface: &crate::os::OsSurface, + surface: &StandIn

, (size, options): ((u64, u64), u64), ([x, y], [w, h]): ([u64; 2], [u64; 2]), pattern: Pattern<'_>, @@ -665,13 +664,9 @@ fn filled>( 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>( cb.commit(OnFault::Die).unwrap(); cb.wait_until_completed(OnFault::Die).unwrap(); assert_eq!(cb.error(), None); - let base = surface.base_address().as_ptr::(); + 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>( +fn memory_fill_on( p: &P, d: &P::Device, (format, size, memory): (u64, (u64, u64), Memory), @@ -789,7 +784,6 @@ fn memory_fill_on { - let made = crate::gpu::ycbcr::measure::Shape::of(ostype).surface(size); - length = made.alloc_size(); - write(made.base_address().as_ptr::(), 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::

::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 s.base_address(), - (_, Some(b)) => b.contents(), + (Some(s), _) => s.base(), + (_, Some(b)) => b.contents().as_ptr::(), _ => 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::(), 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 { - use crate::core::platform::os::surface::Surface as _; - let base = surface.base_address().as_ptr::(); - 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(surface: &StandIn

, length: u64) -> Vec { + 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 { /// 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>( +fn surface_copies( p: &P, d: &P::Device, format: u64, - (a, b): (&crate::os::OsSurface, &crate::os::OsSurface), + (a, b): (&StandIn

, &StandIn

), size: (u64, u64), length: u64, ) -> [Vec; 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: &P, - d: &P::Device, - format: u64, - surface: &crate::os::OsSurface, - ) { + fn within(p: &P, d: &P::Device, format: u64, surface: &StandIn

) { 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::

(&q, copy_region::

((&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::::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::::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: &P, - d: &P::Device, - desc: &TextureDesc, - ) -> Vec { + fn made(p: &P, d: &P::Device, desc: &TextureDesc) -> Vec { let format = |t: Option| 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::

(d); - let surface = crate::os::tests::bgra_surface(16, 16); + let surface = StandIn::

::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::(&d); - let surface = crate::os::tests::bgra_surface(16, 16); + let surface = StandIn::::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::::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

, heap: &P::Heap, ) -> Vec { 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::::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::::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::(); - 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>( +fn read_through_another( p: &P, d: &P::Device, - surface: &crate::os::OsSurface, + surface: &StandIn

, ((width, height), order): ((u64, u64), Order), texels: &[u8], ) -> Vec { @@ -2700,12 +2656,8 @@ fn read_through_another ((u64, u64), Vec) { /// 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::::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::::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), diff --git a/crates/reims-vgpu-vulkan/src/gpu/encode_render/tests/metal_tests.rs b/crates/reims-vgpu-vulkan/src/gpu/encode_render/tests/metal_tests.rs index 1191f874c..fa5783a67 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/encode_render/tests/metal_tests.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/encode_render/tests/metal_tests.rs @@ -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: &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>( +fn resolved_into( 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>( }); 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::(); - // 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::

::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>( unsafe { std::slice::from_raw_parts(b.contents().as_ptr::(), 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::(), 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(); diff --git a/crates/reims-vgpu-vulkan/src/gpu/no_texture/tests/metal_tests.rs b/crates/reims-vgpu-vulkan/src/gpu/no_texture/tests/metal_tests.rs index ccdc38b5e..ccd0e459d 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/no_texture/tests/metal_tests.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/no_texture/tests/metal_tests.rs @@ -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>( +fn answers( d: &P::Device, desc: &P::TextureDescriptor, - s: &OsSurface, + s: &StandIn

, ) -> (u64, [bool; 6], SizeAndAlign) { let buffer = d .new_buffer(BufferDesc { @@ -63,9 +62,7 @@ fn answers>( 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::::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::::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:", diff --git a/crates/reims-vgpu-vulkan/src/gpu/resource.rs b/crates/reims-vgpu-vulkan/src/gpu/resource.rs index 899aeca8b..2cbe7b355 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/resource.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/resource.rs @@ -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 { + /// 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 StandIn

{ + /// 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> { + 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::() + } + + /// 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 { + // 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::::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::(), 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 = 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::::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::::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::().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::::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::::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::::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| { diff --git a/crates/reims-vgpu-vulkan/src/gpu/resource/tests/metal_tests.rs b/crates/reims-vgpu-vulkan/src/gpu/resource/tests/metal_tests.rs index 335926a50..4aebec4b2 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/resource/tests/metal_tests.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/resource/tests/metal_tests.rs @@ -7,7 +7,12 @@ use crate::core::platform::values::{ use super::*; use crate::gpu::device::tests::uploading_depth; -use crate::os::OsSurface; + +/// A 'BGRA' surface of `width` by `height`: the buffer that stands for it, the process's +/// device's ([`StandIn::bgra`]). +fn bgra_stand_in(width: u64, height: u64) -> StandIn { + StandIn::bgra(&dev(), width, height) +} /// A heap's texture's making, where a device that clamps a 32-bit float depth into `[0, 1]` /// (`gpu::device`'s `clamps_depth`: MoltenVK) dies of `restricted-depth-upload` in strict mode @@ -400,97 +405,6 @@ fn textures_and_buffers_answer_as_metals_across_descriptors() { ); } -/// newBufferWithIOSurface: makes a Shared buffer over the surface's memory that holds one -/// reference of the surface while it lives, whose contents are NULL, as Metal's; iosurface -/// answers it, +1 -#[test] -fn buffers_on_surfaces() { - let d = dev(); - let s = bgra_surface(64, 32); - assert_eq!(s.retain_count(), 1); - let b = d.new_buffer_on_surface(Some(&s)).unwrap().unwrap(); - assert_eq!(s.retain_count(), 2); - let seen = (b.contents(), b.length(), b.storage_mode()); - assert_eq!(seen, (HostPtr::NULL, s.alloc_size(), 0)); - let again = b.iosurface().unwrap(); - assert_eq!(again.id(), s.id()); - assert_eq!(s.retain_count(), 3); - drop(again); - drop(b); - assert_eq!(s.retain_count(), 1); -} - -/// Every buffer over a surface answers the surface's address, as on Metal (where it runs, two -/// live ones answer one address, and so does one made after the first's release while a -/// command buffer that fills it waits): a buffer made while another holds the address shares -/// a live one's range, which stays while one holds it. One made while none lives, after the -/// last's release while a command buffer that fills it waits, dies at -/// newBufferWithIOSurface:, naming the surface, as the runtime holds the released one's range -/// until that command buffer completed and shares a range with a live buffer alone. Then a -/// buffer over the surface lies at the address again -#[test] -fn buffers_over_a_surface_share_its_address() { - 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 _}; - fn waiting_fill( - d: &P::Device, - buffer: &P::Buffer, - ) -> (P::CommandBuffer, P::SharedEvent) { - let q = d.new_command_queue().unwrap(); - let gate = d.new_shared_event().unwrap(); - let cb = q.command_buffer(OnFault::Return).unwrap().unwrap(); - cb.encode_wait(Some(EventRef::Shared(&gate)), 1).unwrap(); - let e = cb.blit_encoder(OnFault::Return).unwrap().unwrap(); - let fill = BlitCmd::FillBuffer { - buffer, - range: NsRange::new(0, 16), - value: 0x5c, - }; - e.encode(OnFault::Return, fill).unwrap(); - e.encode(OnFault::Return, BlitCmd::EndEncoding).unwrap(); - cb.commit(OnFault::Return).unwrap(); - (cb, gate) - } - fn completed((cb, gate): (P::CommandBuffer, P::SharedEvent)) { - gate.set_signaled_value(1).unwrap(); - cb.wait_until_completed(OnFault::Return).unwrap(); - assert!(cb.error().is_none(), "{:?}", cb.error()); - } - let d = dev(); - let s = bgra_surface(64, 64); - let first = d.new_buffer_on_surface(Some(&s)).unwrap().unwrap(); - let at = first.gpu_address(); - let second = d.new_buffer_on_surface(Some(&s)).unwrap().unwrap(); - assert_eq!(second.gpu_address(), at, "the first live"); - drop(first); - let third = d.new_buffer_on_surface(Some(&s)).unwrap().unwrap(); - assert_eq!( - third.gpu_address(), - at, - "the first released, the second live" - ); - drop(third); - let waiting = waiting_fill::(&d, &second); - drop(second); - *crate::answer::LAST_LINE.lock() = None; - let site = catch_death(|| drop(d.new_buffer_on_surface(Some(&s)))).unwrap_err(); - let line = crate::answer::LAST_LINE.lock().take().unwrap_or_default(); - assert_eq!( - (site.kind, site.file), - (DeathKind::Abort, "newBufferWithIOSurface:"), - "{line}" - ); - let named = format!( - "a buffer over IOSurface {:#x} while a released one", - s.id().0 - ); - assert!(line.contains(&named), "{line}"); - completed::(waiting); - let again = d.new_buffer_on_surface(Some(&s)).unwrap().unwrap(); - assert_eq!(again.gpu_address(), at, "made once the fill completed"); -} - /// A 2D array over a no-copy buffer of host memory made by /// `newLinearTextureWithDescriptor:offset:bytesPerRow:bytesPerImage:` is Metal's, byte for /// byte: its slices as made, after the CPU rewrote the memory (both alias it), and the memory @@ -508,98 +422,6 @@ fn array_over_host_memory_is_metals() { } } -/// newBufferWithIOSurface: of a surface over the guest's pages at an offset into its -/// allocation (`kIOSurfaceOffset`) reads as Metal's does: as long as the allocation, from the -/// surface's base address, its last bytes, past the allocation's end, 0 -#[test] -fn buffers_on_offset_surfaces_read_as_metals() { - use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _}; - use crate::core::platform::compute::{ComputeCmd, ComputeEncoder as _}; - use crate::core::platform::os::vm::HostVm as _; - use crate::core::platform::resource::Library as _; - // `copy_words` of the surface's buffer, on `d`: its length, and each 32-bit word of it. - fn copied>(d: &P::Device, s: &OsSurface) -> (u64, Vec) { - let b = d.new_buffer_on_surface(Some(s)).unwrap().unwrap(); - let length = b.length(); - let library = d - .new_library(crate::gpu::ycbcr::measure::PROBE) - .unwrap() - .unwrap() - .unwrap(); - let f = library - .new_function(OnFault::Die, "copy_words") - .unwrap() - .unwrap(); - let copies = d - .new_compute_pipeline_state_for_function(Some(&f)) - .unwrap() - .unwrap(); - let out = d - .new_buffer_of_length(OnFault::Die, length, 0) - .unwrap() - .unwrap(); - 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 buffers = [Some(&b), Some(&out)]; - for cmd in [ - ComputeCmd::SetComputePipelineState { - state: Some(&copies), - }, - ComputeCmd::SetBuffers { - buffers: &buffers, - offsets: &[0, 0], - range: NsRange::new(0, 2), - }, - ComputeCmd::DispatchThreads { - threads_per_grid: MtlSize::new(length / 4, 1, 1), - threads_per_threadgroup: MtlSize::new(64, 1, 1), - }, - ComputeCmd::EndEncoding, - ] { - e.encode(OnFault::Die, cmd).unwrap(); - } - cb.commit(OnFault::Die).unwrap(); - cb.wait_until_completed(OnFault::Die).unwrap(); - let n = usize::try_from(length / 4).unwrap(); - // SAFETY: a Shared buffer's words, read after the command buffer completed. - let words = unsafe { std::slice::from_raw_parts(out.contents().as_ptr::(), n) }; - (length, words.to_vec()) - } - for offset in [0, 0x40, 0x1000, 0x4000] { - let (s, pages, length) = crate::os::tests::bgra_surface_over_at(64, 32, offset); - // Each word of the pages holds its own offset there, its top bit set. - for at in (0..length).step_by(4) { - // SAFETY: a word of the test's pages, which no GPU work uses now. - unsafe { - pages - .as_ptr::() - .add(usize::try_from(at).unwrap()) - .cast::() - .write(0x8000_0000 | u32::try_from(at).unwrap()); - } - } - // Metal's first, before this platform's runtime makes any buffer of its own. - let (ours, words) = copied::(&dev(), &s); - assert_eq!(ours, length, "{offset:#x}: the allocation's size"); - let past = usize::try_from((length - offset) / 4).unwrap(); - assert_eq!( - words[0], - 0x8000_0000 | u32::try_from(offset).unwrap(), - "{offset:#x}" - ); - assert!( - words[past..].iter().all(|&w| w == 0), - "{offset:#x}: 0 past the allocation" - ); - let key = format!("{offset:#x}"); - let metals = crate::metal_matches_raw!(key, (ours, words)); - assert!(metals, "{offset:#x}: Metal's"); - drop(s); - crate::remap::VulkanVm::new().deallocate(pages, length); - } -} - /// The answers of setPurgeableState: to KeepCurrent, Volatile, NonVolatile, Empty, /// KeepCurrent and NonVolatile in turn, of each of `P`'s resources: Shared buffers of 256 /// bytes and 16 KiB; Shared textures of 8 by 8 and 256 by 256 BGRA8Unorm, a view of the larger, @@ -1392,63 +1214,6 @@ fn views_need_no_pixel_format_view_usage() { assert!(handle.is_none(), "a texture over a buffer is not shareable"); } -/// How a command buffer reaches a surface ([`surface_references`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Reach { - /// A blit's copy of a texture on it into a buffer. - Blit, - /// A kernel's `read()` of a texture on it, bound at a slot. - Kernel, - /// A kernel's `read()` of a view of a texture on it, bound at a slot. - View, - /// A kernel's `read()` of a texture on it through an argument buffer holding its - /// resource ID, made resident with `useResource:usage:`. - Resident, - /// A render pass that clears a texture on it and stores it. - Attachment, - /// A blit's copy of a buffer on it (`newBufferWithIOSurface:`) into another buffer. - SurfaceBuffer, - /// Not at all: a texture on it is made and released, and the command buffer's kernel - /// reads a texture on another surface. - Unused, - /// A kernel's `read()` of a texture of the format (raw) over plane 0 of it, a two-plane - /// surface of the OSType, bound at a slot. - KernelYcbcr(u64, [u8; 4]), - /// Not at all, as for `Unused`, the texture on it one of the format (raw) over plane 0 - /// of it, a two-plane surface of the OSType. - UnusedYcbcr(u64, [u8; 4]), - /// A draw's `sample()` of a texture on it, bound at a fragment slot, into a target on - /// another surface. - Sampled(Pipeline), - /// A draw into a texture on it, a render pass's color attachment it clears and stores. - Drawn(Pipeline), -} - -/// The `VkPipeline` a draw of [`Reach::Sampled`] or [`Reach::Drawn`] takes. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Pipeline { - /// Made before the command buffer: the state drew the same in one before. - Before, - /// Made at the draw: the state's first draw, through a triangle fill mode of lines, a - /// key its creation does not predict. The test draws on a device whose shader cache is - /// its own and empty (`device_with_own_cache`), as a fresh machine's. - AtTheDraw, -} - -#[link(name = "IOSurface", kind = "framework")] -unsafe extern "C" { - fn IOSurfaceGetUseCount(buffer: *const std::ffi::c_void) -> i32; -} - -/// `s`'s IOSurface's retain count (`CFGetRetainCount`, which core's unmap reads: Busy unless -/// 1) and its use count (`IOSurfaceGetUseCount`). -fn surface_counts(s: &OsSurface) -> (i64, i32) { - let at = - std::ptr::with_exposed_provenance::(usize::try_from(s.id().0).unwrap()); - // SAFETY: a live IOSurfaceRef, which `s` holds. - (s.retain_count(), unsafe { IOSurfaceGetUseCount(at) }) -} - /// Waits until `q`'s command buffers that completed have let go of what they retained, as /// Metal lets go of it: on the queue's completion queue, after the command buffer's waiters /// returned (`-[IOGPUMetalCommandBuffer didCompleteWithStartTime:endTime:error:]` releases its @@ -1468,739 +1233,6 @@ fn let_go(q: &P::CommandQueue) { cb.wait_until_completed(OnFault::Die).unwrap(); } -/// [`surface_counts`] of a 16 by 16 surface (`BGRA8Unorm`, or two planes for the YCbCr -/// reaches) as a command buffer of `d`'s reaches it as `reach` says: with the texture or -/// buffer on it made; once the command buffer committed waiting for an event, every other -/// handle to the texture or buffer released; after it completed and its queue let go of what -/// it retained ([`let_go`]), the command buffer still held; and once the command buffer is -/// released. Each step runs in an autorelease pool of its own, popped before the counts are -/// read. With them, how many pipelines `made` counts were made from the command buffer's -/// encoding until it completed. -fn surface_references>( - p: &P, - d: &P::Device, - reach: Reach, - made: &dyn Fn(&P::Device) -> u64, -) -> ([(i64, i32); 4], u64) { - use crate::core::platform::blit::{BlitCmd, BlitEncoder as _, ResourceRef}; - use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _}; - use crate::core::platform::compute::{ComputeCmd, ComputeEncoder as _}; - use crate::core::platform::descriptor::RenderPassDescriptor as _; - use crate::core::platform::event::{EventRef, SharedEvent as _}; - use crate::core::platform::render::{RenderCmd, RenderEncoder as _}; - use crate::core::platform::resource::{Buffer as _, Library as _, Texture as _}; - use crate::core::platform::values::{ColorAttachmentSet, RenderPipelineDesc}; - use crate::core::rt::Pool; - - use crate::gpu::ycbcr::measure::{PROBE, sampler}; - use crate::gpu::ycbcr::measure::{Shape, desc as ycbcr_desc}; - let side = 16; - let ycbcr = match reach { - Reach::KernelYcbcr(format, ostype) | Reach::UnusedYcbcr(format, ostype) => { - Some((format, ostype)) - } - _ => None, - }; - let s = match ycbcr { - Some((_, ostype)) => Shape::of(&ostype).surface((side, side)), - None => bgra_surface(side, side), - }; - let other = bgra_surface(side, side); - let desc = p.texture_descriptor(&TextureDesc { - pixel_format: 80, - width: side, - height: side, - usage: 5, - resource_options: Some(0), - ..TextureDesc::default() - }); - let on_s = match ycbcr { - Some((format, _)) => p.texture_descriptor(&ycbcr_desc(format, (side, side))), - None => desc.clone_ref(), - }; - 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 * 8, 0) - .unwrap() - .unwrap(); - let args = d - .new_buffer_of_length(OnFault::Die, 64, 0) - .unwrap() - .unwrap(); - let library = d.new_library(PROBE).unwrap().unwrap().unwrap(); - let state = |name| { - let f = library.new_function(OnFault::Die, name).unwrap().unwrap(); - d.new_compute_pipeline_state_for_function(Some(&f)) - .unwrap() - .unwrap() - }; - let (read, held) = (state("read_texels"), state("read_held")); - let elsewhere = d - .new_texture_on_surface(&desc, Some(&other), 0) - .unwrap() - .unwrap(); - // A draw's state, sampler and probe (`sample_fragment`'s: each fragment's texel centre, - // in rows of `side`). - let render = |name| { - let function = |name| library.new_function(OnFault::Die, name).unwrap().unwrap(); - let (vertex, fragment) = (function("cover_vertex"), function(name)); - d.new_render_pipeline_state(&RenderPipelineDesc { - label: None, - vertex: &vertex, - fragment: &fragment, - color0_pixel_format: 80, - resource_index: None, - }) - .unwrap() - .unwrap() - }; - let drawing = match reach { - Reach::Sampled(_) => Some(render("sample_fragment")), - Reach::Drawn(_) => Some(render("gradient_fragment")), - _ => None, - }; - let nearest = sampler::

(d, (0, 0, false), 0); - if let Reach::Sampled(_) = reach { - let probe: [u32; 6] = [ - 0.5f32.to_bits(), - 0.5f32.to_bits(), - 1f32.to_bits(), - 1f32.to_bits(), - u32::try_from(side).unwrap(), - u32::try_from(side).unwrap(), - ]; - // SAFETY: a Shared buffer of 64 bytes, which no command uses yet. - unsafe { - std::ptr::copy_nonoverlapping(probe.as_ptr(), args.contents().as_ptr::(), 6) - }; - } - let draw = |cb: &P::CommandBuffer, target: &P::Texture, sampled: Option<&P::Texture>, lines| { - let pass = p.render_pass_descriptor(); - let attachment = ColorAttachmentSet { - texture: Some(Some(target)), - load_action: Some(2), - store_action: Some(1), - ..ColorAttachmentSet::default() - }; - pass.set_color_attachment(OnFault::Die, 0, &attachment) - .unwrap(); - let e = cb.render_encoder(OnFault::Die, &pass).unwrap().unwrap(); - let buffers = [Some(&out), Some(&args)]; - let samplers = [Some(&nearest)]; - let mut cmds = vec![RenderCmd::SetRenderPipelineState { - pipeline_state: drawing.as_ref(), - }]; - if lines { - cmds.push(RenderCmd::SetTriangleFillMode { fill_mode: 1 }); - } - if let Some(t) = sampled { - cmds.extend([ - RenderCmd::SetFragmentTexture { - texture: Some(t), - index: 0, - }, - RenderCmd::SetFragmentSamplerStates { - samplers: &samplers, - range: NsRange::new(0, 1), - }, - RenderCmd::SetFragmentBuffers { - buffers: &buffers, - offsets: &[0, 0], - range: NsRange::new(0, 2), - }, - ]); - } - cmds.push(RenderCmd::DrawPrimitives { - primitive_type: 3, - vertex_start: 0, - vertex_count: 3, - }); - cmds.push(RenderCmd::EndEncoding); - for cmd in cmds { - e.encode(OnFault::Die, cmd).unwrap(); - } - }; - // The same draw before, into and of textures on no surface, completed and released. - if let Reach::Sampled(Pipeline::Before) | Reach::Drawn(Pipeline::Before) = reach { - let _pool = Pool::here(); - let plain = || d.new_texture(OnFault::Die, &desc).unwrap().unwrap(); - let (target, sampled) = (plain(), plain()); - let cb = q.command_buffer(OnFault::Die).unwrap().unwrap(); - let sampled = matches!(reach, Reach::Sampled(_)).then_some(&sampled); - draw(&cb, &target, sampled, false); - cb.commit(OnFault::Die).unwrap(); - cb.wait_until_completed(OnFault::Die).unwrap(); - assert!(cb.error().is_none(), "{reach:?}: {:?}", cb.error()); - } - let made_before = made(d); - let mut seen = [(0, 0); 4]; - let cb = { - let _pool = Pool::here(); - let cb = q.command_buffer(OnFault::Die).unwrap().unwrap(); - cb.encode_wait(Some(EventRef::Shared(&event)), 1).unwrap(); - let (t, b) = match reach { - Reach::SurfaceBuffer => (None, d.new_buffer_on_surface(Some(&s)).unwrap()), - _ => (d.new_texture_on_surface(&on_s, Some(&s), 0).unwrap(), None), - }; - assert!( - t.is_some() || b.is_some(), - "{reach:?}: nothing made on the surface" - ); - seen[0] = surface_counts(&s); - let view = match reach { - Reach::View => t.as_ref().unwrap().new_texture_view(80).unwrap(), - _ => None, - }; - let kernel = |e: &P::ComputeEncoder, state, texture, resident: Option<&P::Texture>| { - let buffers = [Some(&out), Some(&args)]; - let resources = [resident.map(ResourceRef::Texture)]; - let mut cmds = vec![ - ComputeCmd::SetComputePipelineState { state: Some(state) }, - ComputeCmd::SetBuffers { - buffers: &buffers, - offsets: &[0, 0], - range: NsRange::new(0, 2), - }, - ]; - if let Some(texture) = texture { - cmds.push(ComputeCmd::SetTexture { - texture: Some(texture), - index: 0, - }); - } - if resident.is_some() { - cmds.push(ComputeCmd::UseResources { - resources: &resources, - usage: 1, - }); - } - cmds.push(ComputeCmd::DispatchThreads { - threads_per_grid: MtlSize::new(side, side, 1), - threads_per_threadgroup: MtlSize::new(8, 8, 1), - }); - cmds.push(ComputeCmd::EndEncoding); - for cmd in cmds { - e.encode(OnFault::Die, cmd).unwrap(); - } - }; - match reach { - Reach::Blit | Reach::SurfaceBuffer => { - let e = cb.blit_encoder(OnFault::Die).unwrap().unwrap(); - let copy = match &t { - Some(t) => 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, - }, - None => BlitCmd::CopyBufferToBuffer { - source_buffer: b.as_ref(), - source_offset: 0, - destination_buffer: Some(&out), - destination_offset: 0, - size: side * side * 4, - }, - }; - e.encode(OnFault::Die, copy).unwrap(); - e.encode(OnFault::Die, BlitCmd::EndEncoding).unwrap(); - } - Reach::Attachment => { - let pass = p.render_pass_descriptor(); - let attachment = ColorAttachmentSet { - texture: Some(t.as_ref()), - load_action: Some(2), - store_action: Some(1), - ..ColorAttachmentSet::default() - }; - pass.set_color_attachment(OnFault::Die, 0, &attachment) - .unwrap(); - let e = cb.render_encoder(OnFault::Die, &pass).unwrap().unwrap(); - e.encode(OnFault::Die, RenderCmd::EndEncoding).unwrap(); - } - Reach::Resident => { - let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap(); - let t = t.as_ref().unwrap(); - // SAFETY: a Shared buffer of 64 bytes, which no command uses yet. - unsafe { args.contents().as_ptr::().write(t.gpu_resource_id()) }; - kernel(&e, &held, None, Some(t)); - } - Reach::Kernel | Reach::KernelYcbcr(..) => { - let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap(); - kernel(&e, &read, t.as_ref(), None); - } - Reach::View => { - let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap(); - kernel(&e, &read, view.as_ref(), None); - } - Reach::Unused | Reach::UnusedYcbcr(..) => { - let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap(); - kernel(&e, &read, Some(&elsewhere), None); - } - Reach::Sampled(drawn) => { - draw(&cb, &elsewhere, t.as_ref(), drawn == Pipeline::AtTheDraw); - } - Reach::Drawn(drawn) => { - draw(&cb, t.as_ref().unwrap(), None, drawn == Pipeline::AtTheDraw); - } - } - cb.commit(OnFault::Die).unwrap(); - cb - }; - seen[1] = surface_counts(&s); - { - let _pool = Pool::here(); - event.set_signaled_value(1).unwrap(); - cb.wait_until_completed(OnFault::Die).unwrap(); - assert!(cb.error().is_none(), "{reach:?}: {:?}", cb.error()); - let_go::

(&q); - } - seen[2] = surface_counts(&s); - let made = made(d) - made_before; - { - let _pool = Pool::here(); - drop(cb); - } - seen[3] = surface_counts(&s); - (seen, made) -} - -/// A command buffer holds a surface's IOSurface as Metal's does, measured by its retain -/// count (which core's unmap reads: Busy unless 1) and its use count: from its commit until -/// it completed, through a texture on the surface that a blit copies, a kernel reads at a -/// slot or through an argument buffer made resident, a render pass stores, or a draw samples -/// at a fragment slot or draws into as its attachment (its `VkPipeline` made before the -/// command buffer, or at the draw), a buffer on it a blit copies, and a texture of -/// `YCBCR10_420_2P` (505) or `RGB10_420_2P` (543) over an 'x420' surface, or of -/// `RGB8_420_2P` (540) over a '420v' one, a kernel reads; not at all -/// through any of those textures, made and released, that it never names, whose retain -/// is back to 1 at once. A kernel's read of a view of the texture holds the IOSurface too; -/// Metal's view takes a reference of its own, 3 while the command buffer runs where this -/// platform's view shares its texture's, 2. Either way unmap answers Busy until the command -/// buffer completed. Neither Metal's command buffer nor this platform's changes the use count -/// -/// On this platform the kernel's read through the argument buffer made resident dies at the -/// dispatch naming `half-texel-conversion` ([`crate::answer::DIES`]): the runtime announces the -/// kind for a `half` read of an argument buffer's texture, whose format the function does not -/// know and whose texel it converts by a rounding Metal's may not be. That case runs last here. -/// -/// Metal lets go of what a completed command buffer retained after its waiters returned, the -/// more often once MoltenVK has worked on Metal's device -/// (`texture_identifiers_are_reused_as_metals`): the counts after the completion are read once -/// its queue let go of it ([`let_go`]) -#[test] -#[cfg_attr( - target_os = "macos", - ignore = "MoltenVK: the runtime records device-denormals, a death in strict mode; Mac-only test, off everywhere; ledger: MoltenVK strict deaths" -)] -fn a_command_buffer_holds_a_surface_as_metals_does() { - let ycbcr = [(505, *b"x420"), (543, *b"x420"), (540, *b"420v")]; - let named = [ - Reach::Blit, - Reach::Kernel, - Reach::Resident, - Reach::Attachment, - Reach::SurfaceBuffer, - Reach::Sampled(Pipeline::Before), - Reach::Sampled(Pipeline::AtTheDraw), - Reach::Drawn(Pipeline::Before), - Reach::Drawn(Pipeline::AtTheDraw), - ]; - let named = named - .into_iter() - .chain(ycbcr.map(|(f, o)| Reach::KernelYcbcr(f, o))); - let unnamed = [Reach::Unused] - .into_iter() - .chain(ycbcr.map(|(f, o)| Reach::UnusedYcbcr(f, o))); - let cases: Vec<_> = named - .map(|reach| (reach, [(2, 0), (2, 0), (1, 0), (1, 0)])) - .chain(unnamed.map(|reach| (reach, [(2, 0), (1, 0), (1, 0), (1, 0)]))) - .chain([(Reach::View, [(2, 0), (2, 0), (1, 0), (1, 0)])]) - .collect(); - let (p, d) = (platform(), dev()); - let made = |d: &VulkanDevice| d.raw.work_counts().variant_pipelines_made; - // The draws' device: a shader cache of its own, empty, as a fresh machine's. - let (own, _cache) = crate::gpu::device::tests::metal_tests::device_with_own_cache(); - for &(reach, want) in &cases { - if reach == Reach::Resident { - continue; - } - let on = match reach { - Reach::Sampled(_) | Reach::Drawn(_) => &own, - _ => &d, - }; - let (ours, made) = - surface_references::(&p, on, reach, &made); - assert_eq!(ours, want, "{reach:?}"); - match reach { - Reach::Sampled(Pipeline::AtTheDraw) | Reach::Drawn(Pipeline::AtTheDraw) => { - assert_eq!(made, 1, "{reach:?}: its pipeline made at the draw"); - } - Reach::Sampled(_) | Reach::Drawn(_) => { - assert_eq!(made, 0, "{reach:?}: its pipeline made before"); - } - _ => {} - } - } - let kind = metal2vulkan_runtime::Degradation::HalfTexelConversion; - let site = crate::answer::dies_of(kind, || { - surface_references::(&p, &d, Reach::Resident, &made) - }); - assert_eq!(site.file, "dispatchThreads:threadsPerThreadgroup:"); - // The device before the directory of its shader cache, which it uses while it lives: a - // pattern's bindings drop last first. - drop(own); -} - -/// What holds a surface beside a command buffer's own uses of it ([`surface_holds`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Beside { - /// Another queue's command buffer, committed after a kernel read a texture on it and - /// before the texture's release, which reads a texture on another surface: counts once - /// the texture is released, the other command buffer waiting for an event; once it - /// completed; once it is released. - Pending, - /// As `Pending`, the other command buffer's kernel reading its texture through an - /// argument buffer holding its resource ID, made resident with `useResource:usage:`. - PendingArgument, - /// As `Pending`, the other command buffer's kernel reaching a buffer of the device's - /// own through an address it loads (`reach.metal`), naming no texture. - PendingReach, - /// A completed handler of the command buffer whose kernel read a texture on it, the - /// texture released before the commit: counts inside the handler as it begins and - /// 100 ms later; once the wait for the completion returned; 200 ms later; once the - /// command buffer is released. - Handler, - /// Two textures on it, the first read by a kernel, the second never used: counts once - /// the command buffer completed and is released; once the first is released; once - /// the second is. - Two, -} - -/// [`surface_counts`] of a 16 by 16 `BGRA8Unorm` surface at the steps `beside` names, each -/// step in an autorelease pool of its own. A wait for a command buffer's completion waits until -/// its queue let go of what it retained too ([`let_go`]). -fn surface_holds>( - p: &P, - d: &P::Device, - beside: Beside, -) -> Vec<(i64, i32)> { - use crate::core::platform::blit::ResourceRef; - use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _}; - use crate::core::platform::compute::{ComputeCmd, ComputeEncoder as _}; - use crate::core::platform::event::{EventRef, SharedEvent as _}; - use crate::core::platform::resource::{Buffer as _, Library as _, Texture as _}; - use crate::core::rt::Pool; - - use crate::gpu::ycbcr::measure::PROBE; - let side = 16; - let s = Arc::new(bgra_surface(side, side)); - let other = bgra_surface(side, side); - let desc = p.texture_descriptor(&TextureDesc { - pixel_format: 80, - width: side, - height: side, - usage: 5, - resource_options: Some(0), - ..TextureDesc::default() - }); - let (q, q2) = ( - d.new_command_queue().unwrap(), - d.new_command_queue().unwrap(), - ); - let event = d.new_shared_event().unwrap(); - let out = d - .new_buffer_of_length(OnFault::Die, side * side * 8, 0) - .unwrap() - .unwrap(); - let library = d.new_library(PROBE).unwrap().unwrap().unwrap(); - let state = |name| { - let f = library.new_function(OnFault::Die, name).unwrap().unwrap(); - d.new_compute_pipeline_state_for_function(Some(&f)) - .unwrap() - .unwrap() - }; - let (read, held) = (state("read_texels"), state("read_held")); - let args = d - .new_buffer_of_length(OnFault::Die, 64, 0) - .unwrap() - .unwrap(); - let elsewhere = d - .new_texture_on_surface(&desc, Some(&other), 0) - .unwrap() - .unwrap(); - let reading_how = |q: &P::CommandQueue, texture: &P::Texture, wait: bool, argument: bool| { - let cb = q.command_buffer(OnFault::Die).unwrap().unwrap(); - if wait { - cb.encode_wait(Some(EventRef::Shared(&event)), 1).unwrap(); - } - let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap(); - let buffers = [Some(&out), Some(&args)]; - let resources = [Some(ResourceRef::Texture(texture))]; - let mut cmds = vec![ - ComputeCmd::SetComputePipelineState { - state: Some(match argument { - true => &held, - false => &read, - }), - }, - ComputeCmd::SetBuffers { - buffers: &buffers, - offsets: &[0, 0], - range: NsRange::new(0, 2), - }, - ]; - if argument { - // SAFETY: a Shared buffer of 64 bytes, which no command uses yet. - unsafe { - args.contents() - .as_ptr::() - .write(texture.gpu_resource_id()) - }; - cmds.push(ComputeCmd::UseResources { - resources: &resources, - usage: 1, - }); - } else { - cmds.push(ComputeCmd::SetTexture { - texture: Some(texture), - index: 0, - }); - } - for cmd in cmds.into_iter().chain([ - ComputeCmd::DispatchThreads { - threads_per_grid: MtlSize::new(side, side, 1), - threads_per_threadgroup: MtlSize::new(8, 8, 1), - }, - ComputeCmd::EndEncoding, - ]) { - e.encode(OnFault::Die, cmd).unwrap(); - } - cb - }; - let reading = |q, texture, wait| reading_how(q, texture, wait, false); - // The command buffer, and the buffer its kernel reaches through the address it loads, - // which no command names, so the caller holds it until the command buffer completed. - let reaching = |q: &P::CommandQueue| { - const REACH: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/reach.metallib")); - let library = d.new_library(REACH).unwrap().unwrap().unwrap(); - let f = library - .new_function(OnFault::Die, "reach") - .unwrap() - .unwrap(); - let state = d - .new_compute_pipeline_state_for_function(Some(&f)) - .unwrap() - .unwrap(); - let page = || { - d.new_buffer_of_length(OnFault::Die, 4096, 0) - .unwrap() - .unwrap() - }; - let (addresses, words, reached) = (page(), page(), page()); - // SAFETY: a Shared buffer of a page, which no command uses yet. - unsafe { - addresses - .contents() - .as_ptr::() - .write(reached.gpu_address()) - }; - let cb = q.command_buffer(OnFault::Die).unwrap().unwrap(); - cb.encode_wait(Some(EventRef::Shared(&event)), 1).unwrap(); - let e = cb.compute_encoder(OnFault::Die).unwrap().unwrap(); - for cmd in [ - ComputeCmd::SetComputePipelineState { - state: Some(&state), - }, - ComputeCmd::SetBuffers { - buffers: &[Some(&addresses), Some(&words)], - offsets: &[0, 0], - range: NsRange::new(0, 2), - }, - ComputeCmd::DispatchThreadgroups { - threadgroups_per_grid: MtlSize::new(1, 1, 1), - threads_per_threadgroup: MtlSize::new(1, 1, 1), - }, - ComputeCmd::EndEncoding, - ] { - e.encode(OnFault::Die, cmd).unwrap(); - } - (cb, reached) - }; - let done = |q: &P::CommandQueue, cb: &P::CommandBuffer| { - cb.wait_until_completed(OnFault::Die).unwrap(); - assert!(cb.error().is_none(), "{beside:?}: {:?}", cb.error()); - let_go::

(q); - }; - let on_s = || { - d.new_texture_on_surface(&desc, Some(&s), 0) - .unwrap() - .unwrap() - }; - let mut seen = Vec::new(); - match beside { - Beside::Pending | Beside::PendingArgument | Beside::PendingReach => { - let t = { - let _pool = Pool::here(); - on_s() - }; - { - let _pool = Pool::here(); - let cb = reading(&q, &t, false); - cb.commit(OnFault::Die).unwrap(); - done(&q, &cb); - } - let (cb, reached) = { - let _pool = Pool::here(); - let argument = beside == Beside::PendingArgument; - let (cb, reached) = match beside { - Beside::PendingReach => { - let (cb, reached) = reaching(&q2); - (cb, Some(reached)) - } - _ => (reading_how(&q2, &elsewhere, true, argument), None), - }; - cb.commit(OnFault::Die).unwrap(); - (cb, reached) - }; - { - let _pool = Pool::here(); - drop(t); - } - seen.push(surface_counts(&s)); - { - let _pool = Pool::here(); - event.set_signaled_value(1).unwrap(); - done(&q2, &cb); - } - seen.push(surface_counts(&s)); - { - let _pool = Pool::here(); - drop(cb); - drop(reached); - } - seen.push(surface_counts(&s)); - } - Beside::Handler => { - let inside = Arc::new(Mutex::new(Vec::new())); - let cb = { - let _pool = Pool::here(); - let t = on_s(); - let cb = reading(&q, &t, false); - drop(t); - let (s, inside) = (Arc::clone(&s), Arc::clone(&inside)); - let handler = move |_| { - inside.lock().push(surface_counts(&s)); - std::thread::sleep(std::time::Duration::from_millis(100)); - inside.lock().push(surface_counts(&s)); - }; - cb.add_completed_handler(OnFault::Die, Box::new(handler)) - .unwrap(); - cb.commit(OnFault::Die).unwrap(); - cb - }; - { - let _pool = Pool::here(); - done(&q, &cb); - } - let after = surface_counts(&s); - std::thread::sleep(std::time::Duration::from_millis(200)); - seen.extend(inside.lock().drain(..)); - seen.push(after); - seen.push(surface_counts(&s)); - { - let _pool = Pool::here(); - drop(cb); - } - seen.push(surface_counts(&s)); - } - Beside::Two => { - let (t, unused) = { - let _pool = Pool::here(); - (on_s(), on_s()) - }; - { - let _pool = Pool::here(); - let cb = reading(&q, &t, false); - cb.commit(OnFault::Die).unwrap(); - done(&q, &cb); - } - seen.push(surface_counts(&s)); - { - let _pool = Pool::here(); - drop(t); - } - seen.push(surface_counts(&s)); - { - let _pool = Pool::here(); - drop(unused); - } - seen.push(surface_counts(&s)); - } - } - seen -} - -/// [`surface_holds`] of each case on this platform and on Metal's, which agree, and are its -/// `want`. Metal lets go of what a completed command buffer retained after its waiters -/// returned, the more often once MoltenVK has worked on Metal's device -/// (`texture_identifiers_are_reused_as_metals`), so [`surface_holds`] reads the counts after a -/// completion once its queue let go of it ([`let_go`]). -fn holds_as_metals(cases: &[(Beside, &[(i64, i32)])]) { - let (p, d) = (platform(), dev()); - for &(beside, want) in cases { - let ours = surface_holds::(&p, &d, beside); - assert_eq!(ours, want, "{beside:?}"); - } -} - -/// Nothing beside a command buffer's own uses holds a surface's IOSurface, as on Metal: not -/// a command buffer of another queue that never names it, waiting while the texture on it -/// a completed one read is released, whose kernel reads a texture at a slot; not a second -/// texture on it, whose release lets go of its own reference only. A command buffer's -/// completed handler runs while it still holds the IOSurface, on Metal as here, and lets it go -/// once the handler returned. Where that other command buffer's kernel reads its texture -/// through an argument buffer, Metal holds nothing either, and this platform dies at the -/// dispatch naming `half-texel-conversion` ([`crate::answer::DIES`]): the runtime announces the -/// kind for a `half` read of an argument buffer's texture, whose format the function does not -/// know and whose texel it converts by a rounding Metal's may not be -#[test] -#[cfg_attr( - target_os = "macos", - ignore = "MoltenVK: the runtime records native-half-conversion, a death in strict mode; Mac-only test, off everywhere; ledger: MoltenVK strict deaths" -)] -fn nothing_beside_a_command_buffer_holds_a_surface() { - let none = [(1, 0); 3]; - let handled = [(2, 0), (2, 0), (1, 0), (1, 0), (1, 0)]; - holds_as_metals(&[ - (Beside::Pending, &none[..]), - (Beside::Handler, &handled[..]), - (Beside::Two, &[(3, 0), (2, 0), (1, 0)][..]), - ]); - let kind = metal2vulkan_runtime::Degradation::HalfTexelConversion; - let site = crate::answer::dies_of(kind, || { - surface_holds::( - &platform(), - &dev(), - Beside::PendingArgument, - ) - }); - assert_eq!(site.file, "dispatchThreads:threadsPerThreadgroup:"); -} - -/// A command buffer of another queue that never names a surface, waiting while the texture -/// on it a completed one read is released, holds nothing of it where its kernel reaches a -/// buffer through an address it loads, as on Metal -#[test] -fn a_command_buffer_reaching_an_address_holds_no_surface_it_never_names() { - holds_as_metals(&[(Beside::PendingReach, &[(1, 0); 3][..])]); -} - /// The address of a one-page buffer made and released on `d`: where the next range lies. pub(crate) fn next_range(d: &P::Device) -> u64 { use crate::core::platform::resource::Buffer as _; @@ -2473,10 +1505,8 @@ fn views_metal_answers_nil_are_nil() { } /// The surface's bytes, after the work that wrote them completed. -fn surface_bytes(s: &OsSurface) -> Vec { - let n = usize::try_from(s.alloc_size()).unwrap(); - // SAFETY: the surface's memory, which no command uses now. - unsafe { std::slice::from_raw_parts(s.base_address().as_ptr::(), n) }.to_vec() +fn surface_bytes(s: &StandIn

) -> Vec { + s.bytes(s.length()) } /// What a render pass of [`rotated_uses`] draws. @@ -2508,7 +1538,7 @@ impl Drawn { /// texture into a buffer, the surface's bytes after the CPU replaced an 8 by 4 region at /// (4, 2) of the texture, the surface's bytes after a pass of load action `load` that draws /// `drawn`, and a kernel's `read()` after the pass. -fn rotated_uses>( +fn rotated_uses( p: &P, d: &P::Device, rotation: u64, @@ -2523,14 +1553,14 @@ fn rotated_uses>( use crate::gpu::ycbcr::measure::{PROBE, probed}; let side = drawn.side(); - let s = bgra_surface(side, side); + let s = StandIn::

::bgra(d, side, side); // Each texel names its place: (x, y, 7, 200). let fill: Vec = (0..side * side) .flat_map(|i| [(i % side) as u8, (i / side) as u8, 7, 200]) .collect(); // SAFETY: the surface's memory, of `side` rows of `side` texels, which no command uses. unsafe { - std::ptr::copy_nonoverlapping(fill.as_ptr(), s.base_address().as_ptr::(), fill.len()); + std::ptr::copy_nonoverlapping(fill.as_ptr(), s.base(), fill.len()); } let desc = p.texture_descriptor(&TextureDesc { pixel_format: 80, @@ -2542,10 +1572,7 @@ fn rotated_uses>( rotation: Some(rotation), ..TextureDesc::default() }); - let t = d - .new_texture_on_surface(&desc, Some(&s), 0) - .unwrap() - .unwrap(); + let t = s.texture(&desc, 0).unwrap().unwrap(); let mut seen = vec![( "read", probed::

(d, "read_texels", &t, (side, side), None, None), @@ -2683,19 +1710,19 @@ fn rotated_textures_read_copy_and_store_as_metals() { /// A texture of `rotation` over a square `BGRA8Unorm` surface of `side` whose texels name /// their places (as [`rotated_uses`] fills it), made on `p`'s device `d` with `ShaderRead`, /// `RenderTarget` and `PixelFormatView` usage, and the surface. -fn rotated_named>( +fn rotated_named( p: &P, d: &P::Device, side: u64, rotation: u64, -) -> (OsSurface, P::Texture) { - let s = bgra_surface(side, side); +) -> (StandIn

, P::Texture) { + let s = StandIn::

::bgra(d, side, side); let fill: Vec = (0..side * side) .flat_map(|i| [(i % side) as u8, (i / side) as u8, 7, 200]) .collect(); // SAFETY: the surface's memory, of `side` rows of `side` texels, which no command uses. unsafe { - std::ptr::copy_nonoverlapping(fill.as_ptr(), s.base_address().as_ptr::(), fill.len()); + std::ptr::copy_nonoverlapping(fill.as_ptr(), s.base(), fill.len()); } let desc = p.texture_descriptor(&TextureDesc { pixel_format: 80, @@ -2707,17 +1734,14 @@ fn rotated_named>( rotation: Some(rotation), ..TextureDesc::default() }); - let t = d - .new_texture_on_surface(&desc, Some(&s), 0) - .unwrap() - .unwrap(); + let t = s.texture(&desc, 0).unwrap().unwrap(); (s, t) } /// The surface's bytes after a pass of load action `load` that draws `drawn` (as /// [`rotated_uses`]'s pass does) through a view in `view` of a texture of `rotation` /// ([`rotated_named`]), its pipeline state of the view's format, on `p`'s device `d`. -fn rotated_view_pass>( +fn rotated_view_pass( p: &P, d: &P::Device, rotation: u64, @@ -2782,12 +1806,7 @@ fn rotated_view_pass>( /// The surface's bytes after a pass that clears a 4-sample texture of `format` and resolves /// it into a texture of `rotation` ([`rotated_named`], 32 by 32), or into its view in /// `format` where that is not the texture's, on `p`'s device `d`. -fn rotated_resolve>( - p: &P, - d: &P::Device, - rotation: u64, - format: u64, -) -> Vec { +fn rotated_resolve(p: &P, d: &P::Device, rotation: u64, format: u64) -> Vec { use crate::core::platform::command::{CommandBuffer as _, CommandQueue as _}; use crate::core::platform::descriptor::RenderPassDescriptor as _; use crate::core::platform::render::{RenderCmd, RenderEncoder as _}; @@ -3093,8 +2112,8 @@ fn textures_metal_aborts_making_die() { let site = catch_death(|| d.new_texture(OnFault::Return, &empty)).unwrap_err(); assert_eq!((site.kind, site.file), (DeathKind::Abort, sel)); } - let s = bgra_surface(8, 8); - let site = catch_death(|| d.new_texture_on_surface(&bgra(0, 8, 0), Some(&s), 0)).unwrap_err(); + let s = bgra_stand_in(8, 8); + let site = catch_death(|| s.texture(&bgra(0, 8, 0), 0)).unwrap_err(); assert_eq!(site.file, "newTextureWithDescriptor:iosurface:plane:"); let stencil_view_format = bgra(8, 8, 0x20); stencil_view_format.set_pixel_format(261); @@ -3793,10 +2812,10 @@ fn of_usage(usage: u64) -> TextureDesc { /// `desc_on` gives), a Shared buffer's two creators' (of `desc_on` too) and a Private /// placement heap's; a swizzled view's of the first (blue and red swapped); and the heap's /// size query. -fn usages>( +fn usages( d: &P::Device, (desc, desc_on): (&P::TextureDescriptor, &P::TextureDescriptor), - s: &OsSurface, + s: &StandIn

, ) -> ([u64; 8], u64, SizeAndAlign) { let buffer = d .new_buffer(BufferDesc { @@ -3823,10 +2842,7 @@ fn usages>( .unwrap() .unwrap() .usage(), - d.new_texture_on_surface(desc_on, Some(s), 0) - .unwrap() - .unwrap() - .usage(), + s.texture(desc_on, 0).unwrap().unwrap().usage(), buffer .new_texture(OnFault::Return, desc_on, 0, 256) .unwrap() @@ -3864,7 +2880,7 @@ fn usages>( fn usage_bits_metal_takes_are_answered_as_metals() { let d = dev(); let p = platform(); - let s = bgra_surface(16, 16); + let s = bgra_stand_in(16, 16); let usage_of_all = |u: u64| [u & !0x8; 8]; for usage in [0x1_0005, 0x1_0015, 0x4005, 0x8005, 0xd, 0x1_c01d] { let (desc, desc_on) = (of_usage(usage), of_usage(usage)); @@ -4034,7 +3050,7 @@ fn pvrtc_heap_sizes_are_metals() { fn usage_bits_metal_does_not_define_die_where_textures_are_made() { let d = dev(); let p = platform(); - let s = bgra_surface(16, 16); + let s = bgra_stand_in(16, 16); let heap = private_heap(); let buffer = d .new_buffer(BufferDesc { @@ -4070,7 +3086,7 @@ fn usage_bits_metal_does_not_define_die_where_textures_are_made() { ), ( "newTextureWithDescriptor:iosurface:plane:", - catch_death(|| d.new_texture_on_surface(&desc_on, Some(&s), 0)).map(drop), + catch_death(|| s.texture(&desc_on, 0)).map(drop), ), ( "newTextureWithDescriptor:offset:bytesPerRow:", @@ -4109,9 +3125,7 @@ fn usage_bits_metal_does_not_define_die_where_textures_are_made() { d.new_texture(OnFault::Return, &desc).unwrap().is_some(), d.new_shared_texture(&desc).unwrap().is_some(), d.heap_texture_size_and_align(&desc).unwrap().size > 0, - d.new_texture_on_surface(&desc_on, Some(&s), 0) - .unwrap() - .is_some(), + s.texture(&desc_on, 0).unwrap().is_some(), buffer .new_texture(OnFault::Return, &desc_on, 0, 256) .unwrap() @@ -4131,7 +3145,7 @@ fn usage_bits_metal_does_not_define_die_where_textures_are_made() { /// surface and shareable, beside a buffer, a heap, a sampler state, a command queue, a nil /// texture and a release, then, after another release, one on another thread and one on this /// thread again. -fn texture_identifiers_on>( +fn texture_identifiers_on( d: &P::Device, desc: &dyn Fn(&TextureDesc) -> P::TextureDescriptor, ) -> Vec<(&'static str, u64, u64)> @@ -4209,11 +3223,11 @@ where over.unique_identifier(), over.gpu_resource_id(), )); - let surface = bgra_surface(4, 4); - let on = d - .new_texture_on_surface(&shared, Some(&surface), 0) - .unwrap() - .unwrap(); + // The buffer stands for the surface too, so the sequence makes no object of its own for + // it, as Metal's makes none for a surface. + let bgra = crate::gpu::resource::tests::facts_of(*b"BGRA", (4, 4), &[]); + let surface = StandIn::

::over(buffer.clone_ref(), bgra, vec![(0, 16)]); + let on = surface.texture(&shared, 0).unwrap().unwrap(); ids.push(( "a texture over a surface", on.unique_identifier(), diff --git a/crates/reims-vgpu-vulkan/src/gpu/writes.rs b/crates/reims-vgpu-vulkan/src/gpu/writes.rs index 5398b9985..a8a9c8db3 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/writes.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/writes.rs @@ -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::::bgra(&d, 16, 16); + let (pages, length) = host_pages(16 * 16 * 4); + let over = StandIn::::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 diff --git a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure.rs b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure.rs index 69a56de32..4f4e27f67 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure.rs @@ -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; /// 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) } } diff --git a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure/host.rs b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure/host.rs index f0a3de5b1..b7194893e 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure/host.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/measure/host.rs @@ -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::(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::(); + 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::(); - 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); diff --git a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/sampling.rs b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/sampling.rs index 32918fbd3..1c6276bc2 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/sampling.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/sampling.rs @@ -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); /// 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::(&d, "read_texels", &t, size, None, None); let ours_floats = measure::read_floats::(&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( /// [`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::(&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::(&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::(&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::(&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>( + fn ids( d: &P::Device, descriptor: impl Fn(&TextureDesc) -> P::TextureDescriptor, - s: &OsSurface, + s: &StandIn

, size: (u64, u64), read_held: bool, ) -> (Vec, Vec) { @@ -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::

(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(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| -> 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>( +fn after( d: &P::Device, (format, descriptor): (u64, impl Fn(&TextureDesc) -> P::TextureDescriptor), - s: &OsSurface, + s: &StandIn

, (width, height): (u64, u64), write: Write, ) -> Vec { - 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>( 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>( }), Write::Cpu => { run(&read); - let base = s.base_address().as_ptr::(); + 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::(&d, "read_texels", &t, size, None, None) }; let ours = after::( @@ -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>( +/// row through the buffer that stands for `s`, on `p`'s device `d`. +fn through( d: &P::Device, descriptor: impl Fn(&TextureDesc) -> P::TextureDescriptor, - s: &OsSurface, + s: &StandIn

, (width, height): (u64, u64), before: Before, ) -> Vec { - 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>( .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>( unsafe { std::slice::from_raw_parts(out.contents().as_ptr::(), 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| { - let (s, pages, length) = surface_420_over(b"x420", size); + let read = |p: &dyn Fn(&Surface) -> Vec| { + 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::(&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::(&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>( + fn read( d: &P::Device, descriptor: impl Fn(&TextureDesc) -> P::TextureDescriptor, - s: &OsSurface, + s: &StandIn

, (width, height): (u64, u64), ) -> Vec { 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::(), 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 { - 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::(), length) }.to_vec() +fn bytes_of(surface: &StandIn

) -> Vec { + 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>( +pub(crate) fn written( p: &P, d: &P::Device, op: Op, format: u64, - surfaces: (&OsSurface, &OsSurface), + surfaces: (&StandIn

, &StandIn

), size: (u64, u64), ) -> [Vec; 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>( +fn written_at( p: &P, d: &P::Device, (op, plane): (Op, u64), format: u64, - (s, other): (&OsSurface, &OsSurface), + (s, other): (&StandIn

, &StandIn

), size: (u64, u64), ) -> [Vec; 3] { use crate::core::platform::HostRange; @@ -1968,10 +1944,7 @@ fn written_at>( _ => 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>( 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>( /// 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 = 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, diff --git a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/tests/metal_tests.rs b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/tests/metal_tests.rs index a3c255651..db5f59c4c 100644 --- a/crates/reims-vgpu-vulkan/src/gpu/ycbcr/tests/metal_tests.rs +++ b/crates/reims-vgpu-vulkan/src/gpu/ycbcr/tests/metal_tests.rs @@ -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::::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), ( diff --git a/crates/reims-vgpu-vulkan/src/os.rs b/crates/reims-vgpu-vulkan/src/os.rs index 74130e26a..6e85f7112 100644 --- a/crates/reims-vgpu-vulkan/src/os.rs +++ b/crates/reims-vgpu-vulkan/src/os.rs @@ -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::*; diff --git a/crates/reims-vgpu-vulkan/src/os/linux.rs b/crates/reims-vgpu-vulkan/src/os/linux.rs index 3d457be19..d16cbadc8 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux.rs @@ -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, diff --git a/crates/reims-vgpu-vulkan/src/os/linux/device_lend.rs b/crates/reims-vgpu-vulkan/src/os/linux/device_lend.rs index 78b44cb50..32c9d832b 100644 --- a/crates/reims-vgpu-vulkan/src/os/linux/device_lend.rs +++ b/crates/reims-vgpu-vulkan/src/os/linux/device_lend.rs @@ -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) { + 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::(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::(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::(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); } diff --git a/crates/reims-vgpu-vulkan/src/os/macos.rs b/crates/reims-vgpu-vulkan/src/os/macos.rs index 1dba2aec1..237b91731 100644 --- a/crates/reims-vgpu-vulkan/src/os/macos.rs +++ b/crates/reims-vgpu-vulkan/src/os/macos.rs @@ -675,60 +675,9 @@ impl IoSurfaces 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::().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::().write(0xab) }; - // SAFETY: the test's pages, mapped until they are freed below. - let at = unsafe { - pages - .as_ptr::() - .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 diff --git a/crates/reims-vgpu-vulkan/src/os/surface.rs b/crates/reims-vgpu-vulkan/src/os/surface.rs index b243ce7a7..39d0a18cb 100644 --- a/crates/reims-vgpu-vulkan/src/os/surface.rs +++ b/crates/reims-vgpu-vulkan/src/os/surface.rs @@ -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"), diff --git a/crates/reims-vgpu-vulkan/src/platform.rs b/crates/reims-vgpu-vulkan/src/platform.rs index a766204df..9ed339f85 100644 --- a/crates/reims-vgpu-vulkan/src/platform.rs +++ b/crates/reims-vgpu-vulkan/src/platform.rs @@ -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 diff --git a/crates/reims-vgpu-vulkan/tests/new_images.rs b/crates/reims-vgpu-vulkan/tests/new_images.rs index c07f5cdf1..6754636ca 100644 --- a/crates/reims-vgpu-vulkan/tests/new_images.rs +++ b/crates/reims-vgpu-vulkan/tests/new_images.rs @@ -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: &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: &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 {