diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 13b47a3be..520264cf5 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -416,7 +416,7 @@ pub(super) enum PagesHold { /// A live buffers' table's hold on host pages (`PagesHold::Host`), counted /// (`HostPages::listed`): one left as the buffer is released is a table a command buffer that may -/// reach the pages unnamed holds, past Metal's release (`HostPages::announce_listed`). +/// reach the pages unnamed holds, past Metal's release (`HostPages::released_listed`). pub(super) struct ListedPages(Arc); impl ListedPages { @@ -581,13 +581,30 @@ impl HostPages { /// buffer's included), its listing let go of: a live buffers' table that still lists them is a /// command buffer's, one that may reach them unnamed (its first submission's, a host step's, /// or one a root table recorded before its first submission holds, `live_buffers.rs`), and - /// the pages stay, their deallocator waiting, until it lets go of it, where Metal's runs at - /// the release. Announced once per device (`Degradation::HostDeallocatorDelayed`). - fn announce_listed(&self, device: &Device) { + /// the pages stay until it lets go of it. Where the caller gave a keep-alive, that keeps the + /// pages mapped until the import is freed, so the deallocator runs here, at Metal's moment + /// ([`HostPages::run_kept`]), and the import keeps the keep-alive unless it keeps another's. + /// Else the deallocator waits for the pages to go, where Metal's runs at the release: + /// announced once per device (`Degradation::HostDeallocatorDelayed`). + fn released_listed(&self, device: &Device) { let Some(release) = self.release.get() else { return; }; - if !release.deallocates() || self.listed.load(Ordering::Acquire) == 0 { + if self.listed.load(Ordering::Acquire) == 0 { + return; + } + // The exit guard runs no deallocator and drops no keep-alive: the pages' drop keeps them. + let Some(busy) = exit_guard::enter() else { + return; + }; + drop(busy); + if let Some(keep_alive) = release.keep_alive() { + // These pages still lie in the import, and another buffer lying there may have let go + // of its keep-alive here too: only a keep-alive the import keeps covers this one. + self.run_kept(release, keep_alive, false); + return; + } + if !release.deallocates() { return; } device.shared().counts.host_deallocator_delayed(); @@ -596,12 +613,39 @@ impl HostPages { ( format!("a no-copy buffer of {length} bytes"), "a command buffer that may reach its pages unnamed (a live buffers' table it \ - holds lists them) holds them as it is released" + holds lists them) holds them as it is released, and the caller gave no \ + keep-alive" .to_owned(), ) }); } + /// Run `release`'s deallocator now, at Metal's moment, the caller's `keep_alive` keeping the + /// pages mapped until the import is freed: the import keeps it, unless it keeps another's + /// already, or `others` (another buffer lies in the import, whose own contract keeps the same + /// bytes mapped until it is freed); then it is dropped after the deallocator, which may read + /// the bytes. + fn run_kept(&self, release: &Release, keep_alive: ProgramObject, others: bool) { + let counts = &self.import.device.shared().counts; + let covered = { + let mut kept = lock(&self.import.kept); + match others || kept.is_some() { + true => Some(keep_alive), + false => { + // Counted before the free can take it. + counts.host_keep_alive_kept(); + *kept = Some(keep_alive); + None + } + } + }; + release.run(); + if let Some(keep_alive) = covered { + counts.host_keep_alive_covered(); + exit_guard::program_release(move || drop(keep_alive)); + } + } + /// Release the pages to `release` when they go. pub(super) fn release_to(&self, release: Release) { // A refused set leaves the deallocator unrun, as a refused call does: never reached, @@ -990,27 +1034,10 @@ impl Drop for HostPages { // The caller's keep-alive keeps the pages mapped until the import is freed: the // deallocator runs now, at Metal's moment. Where another buffer lies in the import, // or the import keeps another's keep-alive, that keeps the same bytes mapped until it - // is freed: this one goes now too, after the deallocator, which may read the bytes. - Some(keep_alive) => { - let counts = &import.device.shared().counts; - let covered = { - let mut kept = lock(&import.kept); - match others || kept.is_some() { - true => Some(keep_alive), - false => { - // Counted before the free can take it. - counts.host_keep_alive_kept(); - *kept = Some(keep_alive); - None - } - } - }; - release.run(); - if let Some(keep_alive) = covered { - counts.host_keep_alive_covered(); - exit_guard::program_release(move || drop(keep_alive)); - } - } + // is freed: this one goes now too, after the deallocator, which may read the bytes. (A + // buffer released while a table listed its pages ran this at its release, + // `released_listed`, and left the import a keep-alive: none is left here.) + Some(keep_alive) => self.run_kept(&release, keep_alive, others), // Another buffer lies in the import, whose contract keeps the pages mapped: the // deallocator runs now, as with an import of its own (`host_aliases.rs`). None if others => release.run(), @@ -1064,7 +1091,7 @@ impl Pages { self.memory.placement.settle(); // SAFETY: the caller's. unsafe { release::object(shared.vk(), self.raw) }; - let after = lock(&shared.memory).free_then(shared.vk(), &self.memory.placement, after); + let after = lock(&shared.memory).release_then(shared.vk(), &self.memory.placement, after); drop(busy); device.note_import_freed(self.memory.placement.size()); after @@ -1225,7 +1252,7 @@ impl Drop for BufferShared { own.range_token.release(); if let Lie::Host(cell) = &own.lie { if let Lying::In(pages) = cell.lying() { - pages.announce_listed(&self.device); + pages.released_listed(&self.device); } } } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index f5b5aaf4a..0e8cae3e6 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -3134,7 +3134,7 @@ impl CommandBufferShared { let _running = Running::enter(self.marker(Step::Release)); // Its live buffers' tables first: a buffer whose last hold goes below then counts // only the tables of other command buffers, which may still reach its pages, as - // holding them past its release (`HostPages::announce_listed`); this one's wait ends + // holding them past its release (`HostPages::released_listed`); this one's wait ends // here, at its completion, where Metal's hold of what it retained ends too. let resident = lock(&self.state).resident.take(); drop(resident); diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 11d52c4fd..f3c201cc4 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -1495,7 +1495,7 @@ degradations! { /// them is held: a command buffer submitted before a texture over them was released may /// still read that texture through its resource ID, and its image holds the import until /// the command buffer completes (`heap_sets.rs`); - /// - with or without one, while a live buffers' table that lists them is held: a command + /// - with no keep-alive, while a live buffers' table that lists them is held: a command /// buffer whose commands may reach the buffer unnamed holds its first submission's table /// and its host steps' until it completes, and one a rebind encoded again, or a host /// step recorded, before its first submission until then (`live_buffers.rs`); @@ -1504,6 +1504,9 @@ degradations! { /// (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`: MoltenVK), while the /// batches submitted before the import's memory went are in flight (`freed_memory.rs`). /// + /// With a keep-alive the deallocator runs at the release, as Metal's, and the import keeps + /// the keep-alive, which keeps the pages mapped, until it is freed: not announced. + /// /// Announced once per device, on the thread that lets go of the buffer last, whatever /// `DeviceOptions::announce_each` says: that may be a runtime thread, as a command /// buffer that used the buffer completes, outside any program call or host step. @@ -1647,6 +1650,17 @@ degradations! { VisibilityCountPerColor = "visibility-count-per-color", Precision, "the result is Metal's count multiplied by the colors the draw writes; a `Boolean` \ result is Metal's"; + /// A texture's first move over a no-copy buffer's host pages (or a rebind's new pages) + /// changed bytes the host kept across it, on pages the process maps without write + /// permission when the host writes them back: on Linux, pages made read-only after the + /// buffer was made (Linux refuses read-only pages at the import); on macOS also pages + /// read-only from the start, which Metal reads (a GPU write into them fails its command + /// buffer). Not observed on RADV, which fails the command buffers submitted after a page + /// of an import loses write permission (`HostMemory::new`). Announced once per device, on + /// the thread that makes the submission; the payload counts the bytes. + UnrestoredFirstMoveBytes = "unrestored-first-move-bytes", Precision, + "those bytes keep what the image's move from `UNDEFINED` wrote, where Metal's \ + texture leaves its pages as they were"; } notes { F16FmaDoubleRounding = "f16-fma-double-rounding"; @@ -1808,6 +1822,14 @@ degradations! { /// depth and stencil. Recorded bound: groups past the first may differ at discard or /// depth edges if the driver compiles the variants differently; nothing broader. ColorAttachmentGroups = "color-attachment-groups"; + /// A tessellation pipeline drawn through the device's tessellation stages, on a device + /// whose tessellator is not Apple's (every one but MoltenVK on an Apple GPU): the device's + /// tessellator orders each patch's triangles, picks their first corners and joins its + /// rings where Vulkan leaves that to the implementation, not as Metal's tessellator does. + /// The domain points are Metal's; flat varyings, interpolation across another + /// triangulation and the order a patch's triangles blend in may differ. On a device + /// without `tessellationShader` the emulation draws Metal's order and records none. + TessellationTriangleOrder = "tessellation-triangle-order"; } } diff --git a/crates/metal2vulkan-runtime/src/device/submit.rs b/crates/metal2vulkan-runtime/src/device/submit.rs index 4c4a53d19..7a916ff60 100644 --- a/crates/metal2vulkan-runtime/src/device/submit.rs +++ b/crates/metal2vulkan-runtime/src/device/submit.rs @@ -20,6 +20,7 @@ use super::functions::Vk; use super::relay::By; use super::{lock, Device}; +use crate::degradation::Degradation; use crate::error::{vulkan, Error}; use crate::exit_guard::{self, Call}; use crate::release; @@ -315,9 +316,11 @@ impl Device { /// made by the host before a submission takes the rest of the first work: once every /// submission made before on each `VkQueue` completed ([`drain_submitted`]), each image's /// bytes are read through the host pointer, the moves alone are submitted and waited for, and - /// the bytes are written back, every one. Nothing where no such move waits. The bytes the - /// move may write are its image's own: "Image layout transitions may perform read and write - /// accesses on all memory bound to the image subresource range"; and a linear image's + /// the bytes the moves changed are written back (`KeptBytes::write_back`: none where they + /// changed none; a run on pages the process cannot write stays as the move left it, announced + /// once as `Degradation::UnrestoredFirstMoveBytes`). Nothing where no such move waits. The + /// bytes the move may write are its image's own: "Image layout transitions may perform read and + /// write accesses on all memory bound to the image subresource range"; and a linear image's /// subresource in `GENERAL` is host-accessible, its memory "interpreted" as its subresource /// layout lays it, so the host's writes are what the image then holds. /// @@ -405,8 +408,19 @@ impl Device { } firsts.internal_completed(value); shared.internal_done.reached(value); - kept.write_back(); + let restored = kept.write_back(); drop(held); + shared.counts.first_move_restored(restored.stored); + if restored.unwritable > 0 { + self.degrade_once(Degradation::UnrestoredFirstMoveBytes, || { + ( + format!("{} bytes of host pages", restored.unwritable), + "a texture's first move changed them, and the process maps their pages \ + without write permission, so the host could not put back the bytes it kept" + .to_owned(), + ) + }); + } Ok(()) } diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 6797cf493..624768502 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -148,7 +148,9 @@ impl HostMemory { /// On Linux a buffer over a page this process maps without write permission is refused /// (`Unsupported`, `HostMemory`), though Metal reads such pages: Linux drivers pin imported /// pages for writing, and one (ANV) imported a read-only page and then lost the device at the - /// GPU's first read. Some drivers also refuse shared memory (RADV refused anonymous shared + /// GPU's first read. So on Linux the pages also stay writable while they are imported: RADV + /// failed every command buffer submitted after a page of an import was made read-only + /// (`mprotect`). Some drivers also refuse shared memory (RADV refused anonymous shared /// memory and mappings of shared memory objects, `memfd` mappings among them); private memory /// imports everywhere measured. [`HostMemory::with_dma_buf`] imports such memory where the /// device imports dma-bufs. @@ -395,22 +397,97 @@ pub(super) fn import_refused(error: vk::Result) -> Error { /// refused as not implemented here. #[cfg(target_os = "linux")] pub(super) fn refuse_unwritable(window: &ImportWindow) -> Result<(), Error> { + match host_writable(window.start, window.start + window.size) { + Some(true) => Ok(()), + Some(false) => Err(not_importable()), + None => Err(Error::Unsupported(Unsupported::not_implemented( + Feature::HostMemory, + ))), + } +} + +/// Whether the process maps `[start, end)` without a gap, each page with write permission, as the +/// kernel answers now: on Linux for the mappings over it ([`queried_writable`]), or from the lines +/// of `/proc/self/maps` where the kernel predates the query ([`writable`]); `None` when that file +/// cannot be opened. +#[cfg(target_os = "linux")] +pub(crate) fn host_writable(start: u64, end: u64) -> Option { use std::io::BufRead; - let maps = std::fs::File::open("/proc/self/maps") - .map_err(|_| Error::Unsupported(Unsupported::not_implemented(Feature::HostMemory)))?; - let end = window.start + window.size; - let writable = match queried_writable(&maps, window.start, end) { + let maps = std::fs::File::open("/proc/self/maps").ok()?; + Some(match queried_writable(&maps, start, end) { Some(writable) => writable, None => { let lines = std::io::BufReader::new(maps).lines().map_while(Result::ok); - writable(lines, window.start, end) + writable(lines, start, end) } - }; - if writable { - Ok(()) - } else { - Err(not_importable()) + }) +} + +/// Whether the process maps `[start, end)` without a gap, each page with write permission, as the +/// kernel answers now: on Apple's systems the current protection of each region of the task's map +/// over it (`mach_vm_region`, `VM_REGION_BASIC_INFO_64`); `None` where the kernel fails the query +/// otherwise than for a missing region. +#[cfg(target_vendor = "apple")] +pub(crate) fn host_writable(start: u64, end: u64) -> Option { + /// `VM_REGION_BASIC_INFO_COUNT_64`: the `int`s of `vm_region_basic_info_data_64_t` (of + /// ``, under its `#pragma pack(4)`), whose first is the region's current + /// protection. + const BASIC_INFO_COUNT_64: usize = 9; + /// `VM_REGION_BASIC_INFO_64`. + const BASIC_INFO_64: i32 = 9; + /// `KERN_INVALID_ADDRESS`: no region at or above the address. + const INVALID_ADDRESS: i32 = 1; + /// `VM_PROT_WRITE`. + const PROT_WRITE: i32 = 0x02; + unsafe extern "C" { + /// The task's own port, `mach_task_self()`'s answer (``). + static mach_task_self_: u32; + fn mach_vm_region( + task: u32, + address: *mut u64, + size: *mut u64, + flavor: i32, + info: *mut i32, + count: *mut u32, + object_name: *mut u32, + ) -> i32; } + let mut covered = start; + while covered < end { + let (mut address, mut size) = (covered, 0u64); + let mut info = [0i32; BASIC_INFO_COUNT_64]; + let mut count = BASIC_INFO_COUNT_64 as u32; + let mut object_name = 0u32; + // SAFETY: `mach_task_self_` is set as the task starts and only read after; every pointer + // is to a local of the type and size the call reads and writes; `count` holds `info`'s + // size in `int`s. + let result = unsafe { + mach_vm_region( + mach_task_self_, + &mut address, + &mut size, + BASIC_INFO_64, + info.as_mut_ptr(), + &mut count, + &mut object_name, + ) + }; + if result != 0 { + return (result == INVALID_ADDRESS).then_some(false); + } + // The call answers the region at the address, or the first above it: a gap. + if address > covered || info[0] & PROT_WRITE == 0 { + return Some(false); + } + covered = address.saturating_add(size); + } + Some(true) +} + +/// No answer on other systems. +#[cfg(not(any(target_os = "linux", target_vendor = "apple")))] +pub(crate) fn host_writable(_start: u64, _end: u64) -> Option { + None } /// `struct procmap_query` of Linux's `include/uapi/linux/fs.h` (Linux 6.11): the argument of diff --git a/crates/metal2vulkan-runtime/src/live_buffers.rs b/crates/metal2vulkan-runtime/src/live_buffers.rs index cf7ab3635..4d45467b7 100644 --- a/crates/metal2vulkan-runtime/src/live_buffers.rs +++ b/crates/metal2vulkan-runtime/src/live_buffers.rs @@ -37,10 +37,12 @@ //! resolves against the table current as it runs, which the command buffer holds from then on //! too (`CommandBuffer::residency`): the commands the step records may reach its buffers. So a //! buffer released while a submitted command buffer may reach it keeps its memory until that -//! command buffer completed, announced (`host-deallocator-delayed`): Metal's deallocator runs at -//! the release, and the command buffer's later accesses reach nothing (the M3 Max under macOS -//! 27.0.1, probe `dealloc-probe4`), where Vulkan frees no memory that submitted commands may -//! still use (`VUID-vkFreeMemory-memory-00677`). One the command buffer's commands name goes as +//! command buffer completed: Metal's deallocator runs at the release, and the command buffer's +//! later accesses reach nothing (the M3 Max under macOS 27.0.1, probe `dealloc-probe4`), where +//! Vulkan frees no memory that submitted commands may still use +//! (`VUID-vkFreeMemory-memory-00677`). With the caller's keep-alive the deallocator runs at the +//! release all the same, and the import keeps the keep-alive; without one it waits, announced +//! (`host-deallocator-delayed`). One the command buffer's commands name goes as //! it completes, where Metal's goes too, announced only where another submitted command buffer's //! table lists it: a command buffer lets go of its tables before what it retained //! (`CommandBufferShared::complete`). One released while only command buffers not diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index 309a3e1f7..b375d343c 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -1196,12 +1196,12 @@ impl Memory { /// Return `placement`'s memory, freeing its block when it empties. pub(super) fn free(&mut self, device: &ash::Device, placement: &Placement) { - drop(self.free_then(device, placement, None)); + drop(self.release_then(device, placement, None)); } /// [`free`](Self::free), and `after` goes once the block is freed: given back for the caller /// to let go of with no lock held, unless the block waits with it (`freed_memory.rs`). - pub(super) fn free_then( + pub(super) fn release_then( &mut self, device: &ash::Device, placement: &Placement, diff --git a/crates/metal2vulkan-runtime/src/tests/first_moves.rs b/crates/metal2vulkan-runtime/src/tests/first_moves.rs index c23570ba4..71110f86e 100644 --- a/crates/metal2vulkan-runtime/src/tests/first_moves.rs +++ b/crates/metal2vulkan-runtime/src/tests/first_moves.rs @@ -28,3 +28,165 @@ fn a_staged_decode_alone_leaves_the_texels_to_cpu_copies() { assert!(!firsts.texels_wait(at(&decoding))); assert!(firsts.texels_wait(at(&copied))); } + +/// The runs of changed bytes are exact: each as long as it runs, across the comparison's 64-byte +/// blocks, and none where nothing changed. +#[test] +fn the_changed_runs_are_the_bytes_that_differ() { + use crate::texture::first_move::changed_runs; + let kept: Vec = (0..300u32).map(|i| (i * 7) as u8).collect(); + assert_eq!(changed_runs(&kept, &kept), Vec::new()); + let mut now = kept.clone(); + for at in [0, 1, 2, 63, 64, 130, 299] { + now[at] ^= 0x5a; + } + assert_eq!( + changed_runs(&kept, &now), + vec![0..3, 63..65, 130..131, 299..300] + ); + let mut now = kept.clone(); + now[10..250].iter_mut().for_each(|byte| *byte = !*byte); + assert_eq!(changed_runs(&kept, &now), vec![10..250]); +} + +/// Fresh private pages, `pages` of them, read and write, holding `fill`; unmapped as it drops. +#[cfg(any(target_os = "linux", target_vendor = "apple"))] +struct Pages { + at: *mut u8, + len: usize, + page: usize, +} + +#[cfg(any(target_os = "linux", target_vendor = "apple"))] +impl Pages { + fn new(pages: usize, fill: u8) -> Pages { + // SAFETY: `sysconf` reads a system constant. + let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap(); + let len = pages * page; + // SAFETY: a fresh private mapping, unmapped as `Pages` drops. + let at = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_PRIVATE | libc::MAP_ANON, + -1, + 0, + ) + }; + assert_ne!(at, libc::MAP_FAILED); + let at = at.cast::(); + // SAFETY: the mapping's own bytes. + unsafe { at.write_bytes(fill, len) }; + Pages { at, len, page } + } + + /// Make page `index` read-only. + fn read_only(&self, index: usize) { + // SAFETY: a page of this mapping. + let done = unsafe { + libc::mprotect( + self.at.add(index * self.page).cast(), + self.page, + libc::PROT_READ, + ) + }; + assert_eq!(done, 0, "mprotect"); + } + + fn bytes(&self) -> Vec { + // SAFETY: the mapping's own bytes, readable. + unsafe { std::slice::from_raw_parts(self.at, self.len) }.to_vec() + } + + fn write(&self, at: usize, byte: u8) { + // SAFETY: a byte of the mapping, on a page still writable. + unsafe { self.at.add(at).write(byte) }; + } +} + +#[cfg(any(target_os = "linux", target_vendor = "apple"))] +impl Drop for Pages { + fn drop(&mut self) { + // SAFETY: the mapping is this value's. + unsafe { libc::munmap(self.at.cast(), self.len) }; + } +} + +/// The kernel's answer for the process's own pages: a fresh mapping is writable until a page of it +/// is made read-only, and pages no longer mapped are not (`host_memory::host_writable`, on Linux +/// and Apple's systems). +#[cfg(any(target_os = "linux", target_vendor = "apple"))] +#[test] +fn the_kernel_says_which_of_the_process_s_pages_are_writable() { + use crate::host_memory::host_writable; + let pages = Pages::new(3, 0); + let (at, page) = (pages.at as u64, pages.page as u64); + assert_eq!(host_writable(at, at + 3 * page), Some(true)); + assert_eq!(host_writable(at + 5, at + 6), Some(true)); + pages.read_only(1); + assert_eq!(host_writable(at, at + page), Some(true)); + assert_eq!(host_writable(at, at + 3 * page), Some(false)); + assert_eq!(host_writable(at + page + 9, at + page + 10), Some(false)); + assert_eq!(host_writable(at + 2 * page, at + 3 * page), Some(true)); + drop(pages); + assert_eq!(host_writable(at, at + page), Some(false)); +} + +/// The write back of a first move's kept bytes (`KeptBytes::write_back`, through `put_back`) +/// stores only what the move changed. Over read-only pages it changed nothing on, it stores +/// nothing, so it cannot fault: the reims-vgpu crash (`SIGBUS` on MoltenVK, a texture over guest +/// pages the host maps read-only) stored every byte. Changed bytes on writable pages are put back; +/// changed bytes on a read-only page stay as they are and are counted, which the caller announces +/// (`Degradation::UnrestoredFirstMoveBytes`, a site no lane can meet: no driver's move is made to +/// change bytes on purpose). +#[cfg(any(target_os = "linux", target_vendor = "apple"))] +#[test] +fn the_write_back_stores_only_what_the_move_changed_and_only_where_the_host_may_write() { + use crate::texture::first_move::{put_back, Restored}; + // Unchanged, read-only: nothing stored, no fault. + let pages = Pages::new(2, 0x3c); + let kept = pages.bytes(); + pages.read_only(0); + pages.read_only(1); + // SAFETY: the mapping's bytes, readable; nothing else writes them. + let restored = unsafe { put_back(pages.at, &kept) }; + assert_eq!(restored, Restored::default()); + assert_eq!(pages.bytes(), kept); + // Changed on writable pages: every changed byte put back, and only those counted. + let pages = Pages::new(2, 0x3c); + let kept = pages.bytes(); + for at in [0, 1, 70, pages.page + 3] { + pages.write(at, 0xa5); + } + // SAFETY: as above. + let restored = unsafe { put_back(pages.at, &kept) }; + assert_eq!( + restored, + Restored { + stored: 4, + unwritable: 0 + } + ); + assert_eq!(pages.bytes(), kept); + // Changed on both pages, the second then made read-only: the first's put back, the second's + // left and counted. + let pages = Pages::new(2, 0x3c); + let kept = pages.bytes(); + for at in [5, pages.page + 7, pages.page + 8] { + pages.write(at, 0xa5); + } + pages.read_only(1); + // SAFETY: as above. + let restored = unsafe { put_back(pages.at, &kept) }; + assert_eq!( + restored, + Restored { + stored: 1, + unwritable: 2 + } + ); + let now = pages.bytes(); + assert_eq!(now[5], 0x3c); + assert_eq!(&now[pages.page + 7..pages.page + 9], &[0xa5, 0xa5]); +} diff --git a/crates/metal2vulkan-runtime/src/texture/first_move.rs b/crates/metal2vulkan-runtime/src/texture/first_move.rs index a820808dd..25e5e31a6 100644 --- a/crates/metal2vulkan-runtime/src/texture/first_move.rs +++ b/crates/metal2vulkan-runtime/src/texture/first_move.rs @@ -66,14 +66,21 @@ //! once every submission made before on each `VkQueue` completed (each batch's last barrier //! makes its writes available to the host), it reads the bytes the image's subresources reach //! through the host pointer, submits the moves alone (and a barrier that makes their writes -//! available to the host) and waits for them, then writes the bytes back, every one: a linear -//! image's subresource in `GENERAL` is host-accessible, and the host's writes are what it then -//! holds. No GPU command writes the bytes, so none writes back a cache line that also holds -//! another's bytes: ANV did, the texels' copies back undoing the CPU's writes of the bytes -//! beside them in their 64-byte lines (Mesa 26.2.4, the lane's +//! available to the host) and waits for them, then writes back the bytes the moves changed +//! ([`KeptBytes::write_back`]), so the memory holds every byte read: a linear image's +//! subresource in `GENERAL` is host-accessible, and the host's writes are what it then holds. A +//! move that changed nothing has nothing stored, so pages the process cannot write stay +//! untouched (Metal makes a buffer over read-only pages, and MoltenVK imports them in place; +//! Linux refuses them at the import, `host_memory.rs`). Changed bytes on pages the process maps +//! without write permission when the write back comes (a program's later `mprotect`) keep what +//! the move wrote, announced once (`Degradation::UnrestoredFirstMoveBytes`). No GPU command +//! writes the bytes, so none writes back a cache line that also holds another's bytes: ANV did, +//! the texels' copies back undoing the CPU's writes of the bytes beside them in their 64-byte +//! lines (Mesa 26.2.4, the lane's //! `a_cpu_write_during_a_texture_s_first_move_stays_outside_its_bytes`). A CPU write to the bytes //! between their read and their write back is undone: once per image, in the submission that -//! makes its move. Counted: `WorkCounts::first_move_keeps` and `first_move_kept_bytes`. +//! makes its move. Counted: `WorkCounts::first_move_keeps`, `first_move_kept_bytes` and +//! `first_move_restored_bytes`. //! - **The work.** A barrier from every command before (memory other commands wrote), then the //! buffers' fills with zeros, then their copies of staged bytes after a barrier, then a //! barrier carrying each image's move (after the fills: an image placed in a new heap moves @@ -103,6 +110,7 @@ use super::super::creation; use super::super::device::lock; use super::super::error::{internal, vulkan, Error, MemoryKind}; use super::super::exit_guard::{self, Call}; +use super::super::host_memory::host_writable; use super::super::image_barrier::{image_barrier, ImageDst}; use super::super::memory::{Mapped, Memory, MemoryClass, Placement}; use super::super::release; @@ -115,6 +123,7 @@ use crate::device::functions::Vk; use ash::vk; use metal2vulkan::vk::Format; use std::any::Any; +use std::ops::Range; use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering}; use std::sync::{Arc, Mutex, MutexGuard, Weak}; @@ -146,7 +155,7 @@ pub(crate) struct FirstMove { /// The bytes an image bound to host pages is bound to, which its move from `UNDEFINED` may /// discard, kept across it by the host ([`FirstMove::keeping`]; the module docs): read through /// the host pointer once every submission before completed, the move submitted alone and waited -/// for, then written back, every byte of them. +/// for, then written back where the move changed them ([`KeptBytes::write_back`]). pub(crate) struct Keep { /// The host address of the first byte the image is bound to. at: Mapped, @@ -161,18 +170,97 @@ pub(crate) struct Keep { pub(crate) struct KeptBytes(Vec<(Mapped, Vec)>); impl KeptBytes { - /// Write each keep's bytes back where they lie: once their moves completed, their writes - /// available to the host, before any submission after them, while the pages they lie in are - /// held (with the moves, `Taken::submitted_internally`). - pub(crate) fn write_back(self) { - for (at, bytes) in self.0 { - // SAFETY: the bytes lie in host pages the caller holds, mapped for as long; the move - // that may have written them completed and its writes were made available to the - // host, so no write of the device's lands over these. A CPU write to them meanwhile - // is the program's (the known gap the module docs name). - unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), at.as_ptr(), bytes.len()) }; + /// Put each keep's bytes back where their moves changed them: once the moves completed, their + /// writes available to the host, before any submission after them, while the pages they lie + /// in are held (with the moves, `Taken::submitted_internally`). Only the bytes that differ + /// from those read are stored ([`changed_runs`]), so the pages end holding every byte read, + /// and a move that changed none stores nothing: the pages may be ones the process cannot + /// write (Metal makes a buffer over read-only pages, and MoltenVK imports them). A run of + /// changed bytes is stored where the process maps its pages writable now + /// (`host_memory::host_writable`), else left as the move left it and counted for the caller + /// to announce ([`Restored::unwritable`]). + pub(crate) fn write_back(self) -> Restored { + let mut restored = Restored::default(); + for (at, kept) in self.0 { + // SAFETY: the bytes lie in host pages the caller holds, mapped and readable for as + // long; the moves that may have written them completed and their writes were made + // available to the host. A CPU write to them meanwhile is the program's (the known gap + // the module docs name). + let one = unsafe { put_back(at.as_ptr(), &kept) }; + restored.stored += one.stored; + restored.unwritable += one.unwritable; + } + restored + } +} + +/// Store `kept` again at `at` where the bytes there now differ from it ([`changed_runs`]), each +/// run where the process maps its pages writable now (`host_memory::host_writable`, asked once +/// for the span of every run, then run by run where that span is not all writable). +/// +/// # Safety +/// +/// The `kept.len()` bytes at `at` are mapped and readable for the call, and nothing writes them +/// meanwhile but the program, whose write is a race as on Metal. +pub(crate) unsafe fn put_back(at: *mut u8, kept: &[u8]) -> Restored { + let runs = { + // SAFETY: the caller's. + let now = unsafe { std::slice::from_raw_parts(at.cast_const(), kept.len()) }; + changed_runs(kept, now) + }; + let mut restored = Restored::default(); + let (Some(first), Some(last)) = (runs.first(), runs.last()) else { + return restored; + }; + let address = |offset: usize| at as u64 + offset as u64; + let all = host_writable(address(first.start), address(last.end)) == Some(true); + for run in runs { + let len = run.len() as u64; + if all || host_writable(address(run.start), address(run.end)) == Some(true) { + // SAFETY: the caller's, and the process maps the run's pages writable. + unsafe { + std::ptr::copy_nonoverlapping( + kept[run.clone()].as_ptr(), + at.add(run.start), + run.len(), + ); + } + restored.stored += len; + } else { + restored.unwritable += len; } } + restored +} + +/// What [`KeptBytes::write_back`] put back of the bytes the moves changed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Restored { + /// The changed bytes it stored again (`WorkCounts::first_move_restored_bytes`). + pub(crate) stored: u64, + /// The changed bytes on pages the process does not map writable, which keep what the move + /// wrote (`Degradation::UnrestoredFirstMoveBytes`). + pub(crate) unwritable: u64, +} + +/// The ranges of bytes where `now` differs from `kept`, in order, each as long as it runs. +pub(crate) fn changed_runs(kept: &[u8], now: &[u8]) -> Vec> { + /// The bytes compared at once before a byte-by-byte look. + const BLOCK: usize = 64; + let mut runs: Vec> = Vec::new(); + for (block, (kept, now)) in kept.chunks(BLOCK).zip(now.chunks(BLOCK)).enumerate() { + if kept == now { + continue; + } + for (i, _) in (kept.iter().zip(now).enumerate()).filter(|(_, (k, n))| k != n) { + let at = block * BLOCK + i; + match runs.last_mut() { + Some(run) if run.end == at => run.end = at + 1, + _ => runs.push(at..at + 1), + } + } + } + runs } /// How a first move writes Metal's pattern into the first `levels` levels of its image, of diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 7de2438d8..717ce8946 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -135,6 +135,7 @@ pub(crate) struct Counters { pitched_host_image_refusals_recalled: AtomicU64, first_move_keeps: AtomicU64, first_move_kept_bytes: AtomicU64, + first_move_restored_bytes: AtomicU64, shared_alias_images: AtomicU64, shared_alias_moves_waited: AtomicU64, modifier_feature_queries: AtomicU64, @@ -839,6 +840,15 @@ impl Counters { } } + /// The host stored `bytes` of the kept bytes again, those first moves changed + /// (`texture/first_move.rs`'s `KeptBytes::write_back`). + pub(crate) fn first_move_restored(&self, bytes: u64) { + if bytes > 0 { + self.first_move_restored_bytes + .fetch_add(bytes, Ordering::Relaxed); + } + } + /// A texture over host pages took the `VkImage` another texture of the same image over the /// same bytes made (`texture/shared_alias.rs`). pub(crate) fn shared_alias_taken(&self) { @@ -1444,15 +1454,16 @@ pub struct WorkCounts { /// texture over them went, through the texture's image), until the import is freed, or, on a /// device whose driver has `RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`, for the /// batches submitted before the import's memory went, until they completed (with a keep-alive - /// it runs at the release there); or, with or without one, for a live buffers' table that - /// listed their pages, which a command buffer that may reach them unnamed held, until it let - /// go of it (`live_buffers.rs`). + /// it runs at the release there); or, given none, for a live buffers' table that listed their + /// pages, which a command buffer that may reach them unnamed held, until it let go of it + /// (`live_buffers.rs`; with a keep-alive it runs at the release there too). pub host_deallocators_delayed: u64, /// Keep-alives of no-copy buffers and heaps (`KeepAlive`) held now past their release: each /// by the import of its pages, whose last buffer it was while something else (a texture's - /// image a submitted command buffer may still read) held the import, until the import is - /// freed. One per import at most: a later keep-alive over the same import is dropped at its - /// release (`host_keep_alives_covered`). + /// image a submitted command buffer may still read) held the import, or that a live buffers' + /// table a command buffer that may reach them unnamed holds listed as it was released, until + /// the import is freed. One per import at most: a later keep-alive over the same import is + /// dropped at its release (`host_keep_alives_covered`). pub host_keep_alives_kept: u64, /// Keep-alives dropped at their buffer's release, after its deallocator ran, because the /// import of its pages stays mapped without them: another no-copy buffer made over the same @@ -1515,11 +1526,14 @@ pub struct WorkCounts { /// First moves of images over a no-copy buffer's host pages (or a rebind's new pages) across /// which the host kept the bytes the image is bound to, which a move from `UNDEFINED` may /// discard: read through the host pointer once the submissions before completed, the move - /// submitted alone and waited for, the bytes written back. One per image moved, a rebind's - /// too. + /// submitted alone and waited for, the bytes it changed written back. One per image moved, a + /// rebind's too. pub first_move_keeps: u64, - /// The bytes those moves kept, each read and written back once. + /// The bytes those moves kept, each read once, and read again after the move. pub first_move_kept_bytes: u64, + /// The kept bytes a move changed that the host stored again: none where the driver's moves + /// change no byte of the memory bound to the image. + pub first_move_restored_bytes: u64, /// Textures over a no-copy buffer's host pages that took the `VkImage` another texture of the /// same image over the same bytes of the same import made, which the import or a texture /// holds, rather than make one (and move it, keep its texels or, over dma-buf pages, ask the @@ -1801,6 +1815,7 @@ impl Device { .load(Ordering::Relaxed), first_move_keeps: counters.first_move_keeps.load(Ordering::Relaxed), first_move_kept_bytes: counters.first_move_kept_bytes.load(Ordering::Relaxed), + first_move_restored_bytes: counters.first_move_restored_bytes.load(Ordering::Relaxed), shared_alias_images: counters.shared_alias_images.load(Ordering::Relaxed), shared_alias_moves_waited: counters.shared_alias_moves_waited.load(Ordering::Relaxed), modifier_feature_queries: counters.modifier_feature_queries.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 3e195c462..41859a806 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -8857baee97e7014c05b93b67177b12c9bb7c2a315b1e138ffa8f427cd7d82e6a +175e1d9361c7937492fd886cf5c28c14223c60892fb2c52448eab26896dc44dd diff --git a/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs b/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs index af7cec2cd..880f393ed 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs @@ -408,6 +408,7 @@ fn a_restricted_context_runs_only_on_a_device_that_has_and_reports_its_profile() metal2vulkan::device::DriverWorkaround::ClippedTrianglesSplitPixelFragments, metal2vulkan::device::DriverWorkaround::MeshIndexComponentStoresMisplaced, metal2vulkan::device::DriverWorkaround::ClippedCoverageNotMetals, + metal2vulkan::device::DriverWorkaround::TessellatorNotMetals, ] ); let mut swiftshader_native = native.clone(); @@ -420,6 +421,7 @@ fn a_restricted_context_runs_only_on_a_device_that_has_and_reports_its_profile() [ metal2vulkan::device::DriverWorkaround::BufferAtomicsUncontained, metal2vulkan::device::DriverWorkaround::ClippedCoverageNotMetals, + metal2vulkan::device::DriverWorkaround::TessellatorNotMetals, ] ); assert!(matches!( diff --git a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs index d0d8e0349..5052f1082 100644 --- a/crates/metal2vulkan-validation/src/observation_contract/comparison.rs +++ b/crates/metal2vulkan-validation/src/observation_contract/comparison.rs @@ -148,6 +148,9 @@ impl UlpTable { /// `TessellationFactorInstance`: unbounded until Metal readings settle a tessellation /// pipeline's winding and factor rules: another vertex order, level, or culled patch changes /// whole primitives, not lanes. +/// - `TessellationTriangleOrder`: unbounded: the device's tessellator's triangle order, first +/// corners and ring triangulation change flat varyings, interpolated values and blend order by +/// whole primitives, not lanes. /// - `Fp8Value`: unbounded until a Metal device that implements 8-bit float conversions reads /// them: Metal on Apple M3 returns the carrier byte's integer extension, which differs from the /// format's value by any amount. @@ -280,6 +283,7 @@ pub fn allowance(note: PrecisionNote) -> Allowance { | N::TessellationFactorEdgeCases | N::TessellationFactorScale | N::TessellationFactorInstance + | N::TessellationTriangleOrder | N::Fp8Value | N::MultisamplePosition | N::RasterizationRateMap diff --git a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs index fbda441c0..d430d803e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/degrade_notices.rs @@ -411,7 +411,8 @@ pub(super) fn on_device_with( /// Every kind is taken by a lane test's site: listed above, or a stage's precision note or /// reconvergence; no kind is in two lists, and no list names a kind twice. `misplaced-notice` -/// ([`MISPLACED`]) alone is taken by the runtime's own test instead, as no lane can meet it. +/// ([`MISPLACED`]) and `unrestored-first-move-bytes` ([`UNRESTORED`]) are taken by the runtime's +/// own tests instead, as no lane can meet them. #[test] fn every_kind_has_a_site_a_lane_test_takes() { let stage_kinds = Degradation::ALL.iter().copied().filter(|kind| { @@ -515,6 +516,7 @@ fn every_kind_has_a_site_a_lane_test_takes() { &KEPT_BYTES, &DELAYED_DEALLOCATORS, &MISPLACED, + &UNRESTORED, &DEPTH_DENORMALS, &SIGNED_DEPTH_TESTS, &FIRST_SPARSE, @@ -735,6 +737,13 @@ fn an_anisotropy_past_the_devices_largest_is_announced_once() { /// takes its site, as a build without debug assertions does. const MISPLACED: [Degradation; 1] = [Degradation::MisplacedNotice]; +/// The kind a first move's write back announces where the move changed kept bytes on pages the +/// process no longer maps writable. No lane meets it: no measured driver's move changes a byte of +/// the memory bound to the image, and none can be made to. The runtime's own test +/// `the_write_back_stores_only_what_the_move_changed_and_only_where_the_host_may_write` takes its +/// site (the write back over read-only pages it changed), as such a move would. +const UNRESTORED: [Degradation; 1] = [Degradation::UnrestoredFirstMoveBytes]; + /// The kind Metal's private option bit takes ([`the_private_option_bit_is_ignored_once`]). const PRIVATE_OPTION: [Degradation; 1] = [Degradation::PrivateResourceOption]; diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs index 84a9706d5..10a239d4e 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs @@ -239,7 +239,7 @@ impl Mapping { } /// Make the mapping read-only. - fn protect_read_only(&self) { + pub(super) fn protect_read_only(&self) { // SAFETY: the mapping is this object's. let done = unsafe { libc::mprotect(self.at.as_ptr().cast(), self.len, libc::PROT_READ) }; assert_eq!(done, 0, "mprotect"); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/patches.rs b/crates/metal2vulkan-validation/src/runtime_lane/patches.rs index 88b11dd53..b8149af88 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/patches.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/patches.rs @@ -27,6 +27,7 @@ use metal2vulkan::pipeline::{ RenderPipelineDescriptor, StageSource, TessellationDescriptor, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; +use metal2vulkan::vk::DriverId; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Degradation, Device, DeviceOptions, @@ -62,28 +63,44 @@ pub(super) fn options_of(path: Path) -> impl FnOnce(&mut DeviceOptions) { } } -/// `check` on the lane device of `path` and its name; then the validation layer was silent, and on -/// the emulated path the device announced the emulation once. +/// `check` on the lane device of `path` and its name; then the validation layer was silent, on +/// the emulated path the device announced the emulation once, and the device's triangle order +/// (`tessellation-triangle-order`) was announced at most once, only on the native path of a +/// device whose tessellator is not Apple's (MoltenVK on an Apple GPU hands the patches to Metal's): +/// the emulation draws Metal's order. pub(super) fn on_path(path: Path, check: impl FnOnce(Device, &str)) { let cache = ScratchCache::new().unwrap(); let messages = Messages::default(); + let apple_tessellator; { let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), options_of(path)).unwrap(); + let description = &device.properties().description; + apple_tessellator = + description.driver_id == Some(DriverId::MOLTENVK) && description.vendor_id == 0x106B; let name = device.name().to_owned(); check(device, &name); } - if path == Path::Emulated { - let announced = messages - .take_notices() + let notices = messages.take_notices(); + let announced = |kind: Degradation| { + notices .iter() .filter(|m| { m.degradation .as_ref() - .is_some_and(|d| EMULATED_TESSELLATION.contains(&d.degradation)) + .is_some_and(|d| d.degradation == kind) }) - .count(); - assert_eq!(announced, 1, "the emulation's notice"); + .count() + }; + if path == Path::Emulated { + let emulated: usize = EMULATED_TESSELLATION.iter().map(|&k| announced(k)).sum(); + assert_eq!(emulated, 1, "the emulation's notice"); + } + let order = announced(Degradation::TessellationTriangleOrder); + if path == Path::Emulated || apple_tessellator { + assert_eq!(order, 0, "the triangle order on {path:?}"); + } else { + assert!(order <= 1, "the triangle order announced {order} times"); } let reported = messages.take(); assert!( diff --git a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs index 22069bfda..d39e5ee31 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/pitched_surfaces.rs @@ -885,8 +885,10 @@ fn first_move_keeps_the_bytes( at most the last row's pitch ({span} to {rows})", surface.what ); + let restored = after.first_move_restored_bytes - before.first_move_restored_bytes; eprintln!( - "FIRST-MOVE-KEEP on {}: {}, {use_}: {} ({kept} kept, {bytes} bytes)", + "FIRST-MOVE-KEEP on {}: {}, {use_}: {} ({kept} kept, {bytes} bytes, {restored} \ + restored)", device.name(), surface.what, if aliased { "aliased" } else { "shadowed" }, @@ -943,6 +945,158 @@ fn a_texture_s_first_move_keeps_the_bytes_it_lies_over() { }); } +/// A texture that only reads, of `layout`, over a no-copy buffer whose pages the process maps +/// read-only by its first use: made read-only after the buffer was made (Linux refuses read-only +/// pages at the import, `a_read_only_page_is_refused_on_linux_and_read_elsewhere`, but not later), +/// or, where `from_the_start`, before it (a guest's pages the host maps read-only, which MoltenVK +/// imports in place). Its first use makes the image's first move, across which the host keeps the +/// bytes the image is bound to and stores back only those the move changed +/// (`texture/first_move.rs`'s `KeptBytes::write_back`): a store into the read-only pages would end +/// the process (`SIGBUS` on macOS, `SIGSEGV` on Linux), as every byte's store did. The read gives +/// the pages' texels and every byte of the pages stays, unless the move changed some, which the +/// device then announces (`unrestored-first-move-bytes`). Printed (`FIRST-MOVE-READ-ONLY`): the +/// form and the kept and restored bytes. Whether it was aliased; `None` where the device makes no +/// buffer over the pages. +fn first_move_over_read_only_pages( + device: &Device, + messages: &Messages, + layout: Layout, + from_the_start: bool, +) -> Option { + let queue = device.new_command_queue().unwrap(); + let reads = reading(device, layout.pf, "tob_read"); + let len = layout.len().next_multiple_of(GUEST_PAGE); + let mapping = Mapping::anonymous(len); + let mut pages = counting(len, 7); + lay( + &layout, + &mut pages, + &texels_of(&layout, (layout.row() * layout.h) as usize, 1), + ); + mapping.write(0, &pages); + if from_the_start { + mapping.protect_read_only(); + } + // SAFETY: the mapping outlives the buffer and the texture (dropped first), and nothing writes + // the buffer. + let made = unsafe { + no_copy( + device, + mapping.pointer(), + len, + ResourceOptions::default(), + None, + ) + }; + let buffer = match made { + Ok(buffer) => buffer, + Err(error) if not_importable(&error) => { + eprintln!("FIRST-MOVE-READ-ONLY: no buffer over the pages: {error:?}"); + return None; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + if !from_the_start { + mapping.protect_read_only(); + } + let mut d = TextureDescriptor::texture_2d(layout.pf, layout.w, layout.h, false); + d.usage = TextureUsage::SHADER_READ; + d.resource_options = buffer.resource_options(); + let before = device.work_counts(); + let texture = buffer + .new_texture_with_iosurface_plane(&d, IoSurfacePlane::new(0, layout.bpr, false)) + .unwrap(); + let aliased = device.work_counts().shadowed_textures == before.shadowed_textures; + let what = format!( + "{} ({}), read-only {}", + layout.name, + layout.pf.name(), + if from_the_start { + "from the start" + } else { + "after the buffer" + } + ); + let read = drawn(&queue, &layout, &reads, &texture, None); + let (count, first) = differing(&read, &rows(&layout, &pages), layout.texel); + let after = device.work_counts(); + let kept = after.first_move_kept_bytes - before.first_move_kept_bytes; + let restored = after.first_move_restored_bytes - before.first_move_restored_bytes; + let unrestored = messages + .take_notices() + .into_iter() + .filter_map(|message| message.degradation) + .any(|notice| notice.degradation == Degradation::UnrestoredFirstMoveBytes); + eprintln!( + "FIRST-MOVE-READ-ONLY on {}: {what}: {} ({kept} bytes kept, {restored} restored, \ + unrestored announced {unrestored})", + device.name(), + if aliased { "aliased" } else { "shadowed" }, + ); + let keeps = after.first_move_keeps - before.first_move_keeps; + assert_eq!( + keeps, + u64::from(aliased), + "{what}: {keeps} first moves kept their bytes (aliased {aliased})" + ); + if !unrestored { + assert!( + count == 0, + "{what}: {count} texels read differ from the pages', the first at texel {first:?}" + ); + let now = mapping.read(0..len); + assert!( + now == pages, + "{what}: the read-only pages changed: {}", + padding_changes(&layout, &now, &pages) + ); + } + drop((texture, buffer)); + drop(mapping); + Some(aliased) +} + +/// [`first_move_over_read_only_pages`] over [`PACKED`], with the pages made read-only after the +/// buffer, and off Linux also before it, on one device of the policy's default. Where the device +/// imports host memory, at least one texture is aliased, or no keep over read-only pages was +/// checked. On Linux only lavapipe and NVIDIA's driver keep an import running once its pages lose +/// write permission (`HostMemory::new`'s Linux contract: RADV failed the command buffers submitted +/// after it), so only they take the case. +#[test] +fn a_texture_over_read_only_pages_takes_its_first_move() { + on_shared_device(Some(PaddedReadsPolicy::Alias), |device, messages| { + let driver = device.properties().description.driver_id; + let keeps_running = matches!( + driver, + Some(DriverId::MESA_LLVMPIPE | DriverId::NVIDIA_PROPRIETARY) + ); + if cfg!(target_os = "linux") && !keeps_running { + eprintln!( + "FIRST-MOVE-READ-ONLY on {}: {driver:?} is held to the writable pages of \ + HostMemory::new's Linux contract", + device.name() + ); + return; + } + let mut aliased = 0; + for layout in PACKED { + for from_the_start in [false, true] { + if from_the_start && cfg!(target_os = "linux") { + continue; + } + match first_move_over_read_only_pages(device, messages, layout, from_the_start) { + Some(alias) => aliased += u64::from(alias), + None => return, + } + } + } + assert!( + aliased > 0, + "no texture over read-only pages was aliased, so no keep over them was checked" + ); + }); +} + /// How long the CPU waits after the commit before its writes beside a texture /// ([`a_cpu_write_during_the_first_move_stays_outside`]), one fresh texture each: the first move /// runs when the device reaches the submission, which takes a time of its own on each device, so diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs index 516baa787..3b8fd5a3f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs @@ -23,10 +23,11 @@ //! keeps the table and the pages it took then for every later batch (the split: a wait for an //! event after an encoder), named or resident (table 3: a running command buffer reads the old //! pages until it completes). The old pages' deallocator runs once it completed; so does a -//! released buffer's that its table lists, announced once (Metal's runs at the release), while a -//! buffer released beside it that no submitted table lists goes at once. One released after a rebind encoded a pending command buffer -//! again goes at that command buffer's first submission, before it completes, its deallocator -//! free to read it. One a submitted command buffer's command names goes as that command buffer +//! released buffer's that its table lists, announced once (Metal's runs at the release), unless +//! the caller gave a keep-alive, which keeps the pages mapped while the deallocator runs at the +//! release, while a buffer released beside it that no submitted table lists goes at once. One +//! released after a rebind encoded a pending command buffer again goes at that command buffer's +//! first submission, before it completes, its deallocator free to read it. One a submitted command buffer's command names goes as that command buffer //! completes, as Metal's does, unannounced. //! //! The walker (`walk-a-device-pointer-chain-through-a-loop-phi`, an owned case) reaches its @@ -53,11 +54,11 @@ use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{ColorAttachmentDescriptor, RenderPipelineDescriptor, StageSource}; use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use metal2vulkan_runtime::{ - Buffer, ClearColor, CommandBuffer, CommandBufferError, CommandBufferStatus, CommandQueue, - CommitFailure, Deallocator, Degradation, Device, EventRef, FailedEncoders, Heap, HeapType, - LoadAction, PipelineOptions, Region, RenderCommandEncoder, RenderPassDescriptor, - RenderPipelineState, ResourceOptions, StoreAction, Submission, SubmissionCheck, - TextureDescriptor, + Buffer, BufferContents, BufferDescriptor, ClearColor, CommandBuffer, CommandBufferError, + CommandBufferStatus, CommandQueue, CommitFailure, Deallocator, Degradation, Device, EventRef, + FailedEncoders, Heap, HeapType, HostMemory, KeepAlive, LoadAction, PipelineOptions, Region, + RenderCommandEncoder, RenderPassDescriptor, RenderPipelineState, ResourceOptions, StoreAction, + Submission, SubmissionCheck, TextureDescriptor, }; use std::collections::BTreeMap; use std::num::NonZeroU64; @@ -306,6 +307,44 @@ pub(super) fn member_over(device: &Device, value: u32) -> Option<(Buffer, Arc); + +impl Drop for DropFlag { + fn drop(&mut self) { + self.0.store(true, Ordering::SeqCst); + } +} + +/// A no-copy buffer over a node of `value`, its deallocator's runs in a `Seen` of its own, whose +/// keep-alive holds the mapping and sets the flag returned as it drops; `None`, printed, where the +/// device imports no host memory. +fn kept_member_over(device: &Device, value: u32) -> Option<(Buffer, Arc, Arc)> { + let seen = Arc::new(Seen::default()); + let dropped = Arc::new(AtomicBool::new(false)); + let mapping = pages(buffer_len(), 0, &node(value)); + let pointer = mapping.pointer(); + // The mapping goes first, then the flag is set. + let keep_alive: KeepAlive = Box::new((mapping, DropFlag(Arc::clone(&dropped)))); + // SAFETY: the keep-alive releases the mapping, after the buffer's last use of it. + let memory = unsafe { HostMemory::new(pointer) }; + let contents = BufferContents::NoCopy { + memory, + deallocator: Some(recording(&seen, ())), + keep_alive: Some(keep_alive), + }; + let descriptor = + BufferDescriptor::new(buffer_len() as u64, ResourceOptions::default(), contents); + match device.new_buffer_with_descriptor(descriptor) { + Ok(buffer) => Some((buffer, seen, dropped)), + Err(error) if not_importable(&error) => { + eprintln!("REBIND-REACH: the device imports no host memory: {error:?}"); + None + } + Err(error) => panic!("new_buffer_with_descriptor: {error:?}"), + } +} + /// Rebind `buffer` to fresh pages holding a node of `value`. pub(super) fn rebind_to(buffer: &Buffer, value: u32) -> Arc { let seen = Arc::new(Seen::default()); @@ -1276,11 +1315,32 @@ fn a_command_buffer_first_submitted_before_a_rebind_keeps_its_pages_in_every_lat /// GPU never saw; an event wait between two batches holds the command buffer here.) #[test] fn a_released_buffer_s_pages_wait_for_the_submitted_command_buffer_whose_table_lists_it() { + released_while_listed(false); +} + +/// A no-copy buffer given a keep-alive, released while a command buffer whose first batch was +/// submitted holds the table that lists it, runs its deallocator at the release, as Metal's runs +/// (probe `dealloc-probe4`), unannounced: the import of its pages keeps the keep-alive, which +/// keeps them mapped for that command buffer's walk, until it is freed after the command buffer +/// completes. +#[test] +fn a_released_buffer_s_keep_alive_holds_its_listed_pages_while_its_deallocator_runs_at_once() { + released_while_listed(true); +} + +/// The release of a no-copy buffer a submitted command buffer's table lists, with a keep-alive +/// or without one, and of one beside it that no submitted table lists. +fn released_while_listed(keep_alive: bool) { on_device_noticed(|device, messages| { let queue = device.new_command_queue().unwrap(); let walker = public_case(POINTER_WALKER).unwrap(); let outputs = Outputs::new(device, &queue, &walker); - let Some((listed, listed_seen)) = member_over(device, A) else { + let made = match keep_alive { + true => kept_member_over(device, A), + false => member_over(device, A) + .map(|(buffer, seen)| (buffer, seen, Arc::new(AtomicBool::new(false)))), + }; + let Some((listed, listed_seen, kept_dropped)) = made else { return; }; gpu_read(&queue, &listed, 0..16); @@ -1316,17 +1376,30 @@ fn a_released_buffer_s_pages_wait_for_the_submitted_command_buffer_whose_table_l } let before = device.work_counts(); drop(listed); - assert_eq!( - device.work_counts().host_deallocators_delayed - before.host_deallocators_delayed, - 1, - "the release waits for the submitted table" - ); - std::thread::sleep(Duration::from_millis(50)); - assert_eq!( - listed_seen.runs.load(Ordering::SeqCst), - 0, - "ran though a submitted command buffer's table listed it" - ); + let after = device.work_counts(); + let delayed = after.host_deallocators_delayed - before.host_deallocators_delayed; + let kept = after.host_keep_alives_kept - before.host_keep_alives_kept; + match keep_alive { + // The deallocator runs in the release; the import keeps the keep-alive. + true => { + assert_eq!(delayed, 0, "a deallocator with a keep-alive waited"); + assert_eq!(kept, 1, "the import keeps the keep-alive"); + assert_eq!( + listed_seen.runs.load(Ordering::SeqCst), + 1, + "the deallocator did not run at the release, as Metal's runs" + ); + } + false => { + assert_eq!(delayed, 1, "the release waits for the submitted table"); + std::thread::sleep(Duration::from_millis(50)); + assert_eq!( + listed_seen.runs.load(Ordering::SeqCst), + 0, + "ran though a submitted command buffer's table listed it" + ); + } + } // Beside it: a buffer listed after that submission, released; read on another queue, // since this one's next command buffer waits behind the held one. let Some((beside, beside_seen)) = member_over(device, B) else { @@ -1337,7 +1410,12 @@ fn a_released_buffer_s_pages_wait_for_the_submitted_command_buffer_whose_table_l drop(beside); deallocated(&beside_seen); assert_eq!(command_buffer.status(), CommandBufferStatus::Committed); - assert_eq!(listed_seen.runs.load(Ordering::SeqCst), 0); + let ran = usize::from(keep_alive); + assert_eq!(listed_seen.runs.load(Ordering::SeqCst), ran); + assert!( + !kept_dropped.load(Ordering::SeqCst), + "the keep-alive went while a submitted command buffer's table listed its pages" + ); event.set_signaled_value(1); command_buffer.wait_until_completed_for(WAIT).unwrap(); assert_eq!(command_buffer.error(), None); @@ -1346,6 +1424,26 @@ fn a_released_buffer_s_pages_wait_for_the_submitted_command_buffer_whose_table_l assert_eq!(read_buffer(&unrelated, 0, 16).unwrap(), [0x3c; 16]); deallocated(&listed_seen); assert_eq!(listed_seen.runs.load(Ordering::SeqCst), 1); + if keep_alive { + // The import is freed as the command buffer lets go of its table, and drops the + // keep-alive (a runtime thread may free it). + let deadline = Instant::now() + WAIT; + while !kept_dropped.load(Ordering::SeqCst) { + assert!( + Instant::now() < deadline, + "the keep-alive was never dropped" + ); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!( + device.work_counts().host_keep_alives_kept, + before.host_keep_alives_kept + ); + // No wait past Metal's release, nothing announced. + assert_made_once(messages, &[], &shared_kinds(device)); + eprintln!("REBIND-REACH released: the keep-alive held the listed pages"); + return; + } // The wait past Metal's release, announced once; the buffer beside it waited for none. assert_made_once(messages, &DELAYED_DEALLOCATORS, &shared_kinds(device)); eprintln!("REBIND-REACH released: the pages waited for the submitted table's holder"); diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 82fdfbf93..de1b31e5e 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1377,6 +1377,7 @@ codec_enum! { NativeDot, NativeMix, ColorAttachmentGroups, + TessellationTriangleOrder, } BindingSource { Buffer(f0), Texture(f0), Sampler(f0), CombinedTextureSampler { texture, sampler }, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 388bca2d5..1064e5577 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 1739; +pub const SEMANTICS_VERSION: u32 = 1740; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 1739; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 419; +pub const ARTIFACT_FORMAT_VERSION: u32 = 420; /// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding /// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 419; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 1301; +pub const RUNTIME_VERSION: u32 = 1303; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index dd1932e71..cbdb76fc6 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -449,9 +449,11 @@ fn derive_fields( fn workarounds(desc: &DeviceDescription) -> Vec { let mut found = by_identity(desc); // Every rasterizer but Apple's hands a clipped primitive's fragments their coverage by the - // whole primitive (or, lavapipe, by its own pieces), never by Apple's pieces. + // whole primitive (or, lavapipe, by its own pieces), never by Apple's pieces; and every + // tessellator but Apple's orders a patch's triangles its own way. if !(desc.driver_id == Some(vk::DriverId::MOLTENVK) && desc.vendor_id == APPLE_VENDOR_ID) { found.push(DriverWorkaround::ClippedCoverageNotMetals); + found.push(DriverWorkaround::TessellatorNotMetals); } found.extend(super::driver_facts::defects(desc)); found.sort(); diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index a2ff2465d..6c0b1261b 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1394,6 +1394,16 @@ pub enum DriverWorkaround { /// function compiled for a multisampled pipeline that reads `[[sample_mask]]` records /// `PrecisionNote::ClippedCoverageSplit` there (`lower::fragment::coverage`). ClippedCoverageNotMetals, + /// The device's tessellator does not draw a patch's triangles as Apple's does: Metal's + /// tessellator draws the D3D11 reference's triangles in its own order, each one's first corner + /// by its stitch step (`lower::tessellation::tessellator`), where Vulkan leaves a patch's + /// triangle order, first corners and ring triangulation to the implementation (every patch + /// differs on the RTX 3090, 55-95% of them on RADV and lavapipe). The device's answer, not a + /// defect. Every driver has it but MoltenVK (`VK_DRIVER_ID_MOLTENVK`) on an Apple GPU + /// (`vendor_id` 0x106B), which hands the patches to Metal's tessellator. A pipeline drawn + /// through the device's tessellation stages records `PrecisionNote::TessellationTriangleOrder` + /// there (`link::tessellation::note_evaluation_stage`). + TessellatorNotMetals, } #[cfg(test)] diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index 72c25ba94..b7c12dd5d 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -824,14 +824,18 @@ fn moltenvk_on_apple_carries_the_early_tests_image_write_defect() { W::FunctionsInlinedAtEveryCall, W::LoadsForwardedIntoLoops, W::LocalizedLoadsForwardedPastAtomicsAndCalls, - W::ClippedCoverageNotMetals + W::ClippedCoverageNotMetals, + W::TessellatorNotMetals ] ); desc.vendor_id = 0x106B; desc.driver_id = Some(vk::DriverId::MESA_RADV); // Every rasterizer but Apple's hands a clipped primitive's fragments other coverage than - // Metal's pieces. - assert_eq!(workarounds(&desc), [W::ClippedCoverageNotMetals]); + // Metal's pieces, and every tessellator but Apple's orders a patch's triangles its own way. + assert_eq!( + workarounds(&desc), + [W::ClippedCoverageNotMetals, W::TessellatorNotMetals] + ); } /// `DriverWorkaround::BothBarycentricFormsRejected`, @@ -995,37 +999,48 @@ fn the_profile_holds_the_largest_whole_point_size() { } } -/// Every driver carries `DriverWorkaround::ClippedCoverageNotMetals` but MoltenVK on an Apple GPU, -/// which draws through Metal and splits a clipped primitive as Metal does: MoltenVK on another -/// vendor's GPU carries it, and so does every other driver on an Apple vendor ID. +/// Every driver carries `DriverWorkaround::ClippedCoverageNotMetals` and +/// `DriverWorkaround::TessellatorNotMetals` but MoltenVK on an Apple GPU, which draws through Metal +/// and splits a clipped primitive and orders a patch's triangles as Metal does: MoltenVK on another +/// vendor's GPU carries them, and so does every other driver on an Apple vendor ID. #[test] -fn every_rasterizer_but_apples_hands_other_clipped_coverage() { +fn every_rasterizer_and_tessellator_but_apples_answer_their_own_way() { use crate::device::profile::DriverWorkaround; - let answer = DriverWorkaround::ClippedCoverageNotMetals; - let carries = |desc: &DeviceDescription| { - Device::new(desc.clone(), DevicePolicy::default()) - .unwrap() - .profile() - .fields() - .workarounds - .contains(&answer) - }; - for stem in [ - "nvidia-rtx5080-laptop", - "amd-rdna3-radv", - "intel-irisxe-rplp-anv", - "lavapipe", - "swiftshader", + for answer in [ + DriverWorkaround::ClippedCoverageNotMetals, + DriverWorkaround::TessellatorNotMetals, ] { - assert!(carries(&profile(stem)), "{stem}"); + let carries = |desc: &DeviceDescription| { + Device::new(desc.clone(), DevicePolicy::default()) + .unwrap() + .profile() + .fields() + .workarounds + .contains(&answer) + }; + for stem in [ + "nvidia-rtx5080-laptop", + "amd-rdna3-radv", + "intel-irisxe-rplp-anv", + "lavapipe", + "swiftshader", + ] { + assert!(carries(&profile(stem)), "{answer:?} {stem}"); + } + let mut desc = profile("moltenvk-m3"); + assert!(!carries(&desc), "{answer:?}: MoltenVK on an Apple GPU"); + desc.vendor_id = 0x1002; + assert!( + carries(&desc), + "{answer:?}: MoltenVK on another vendor's GPU" + ); + desc.vendor_id = 0x106B; + desc.driver_id = Some(vk::DriverId::MESA_RADV); + assert!( + carries(&desc), + "{answer:?}: another driver on an Apple vendor ID" + ); } - let mut desc = profile("moltenvk-m3"); - assert!(!carries(&desc), "MoltenVK on an Apple GPU"); - desc.vendor_id = 0x1002; - assert!(carries(&desc), "MoltenVK on another vendor's GPU"); - desc.vendor_id = 0x106B; - desc.driver_id = Some(vk::DriverId::MESA_RADV); - assert!(carries(&desc), "another driver on an Apple vendor ID"); } /// Lavapipe carries `DriverWorkaround::ClippedTrianglesSplitPixelFragments` (the defect is the @@ -1046,11 +1061,13 @@ fn lavapipe_carries_the_split_pixel_fragments_defect() { // The committed lavapipe's release (Mesa 26.2.3) also carries the mesh index defect, kept // past the release measured with it (`lavapipe_carries_the_mesh_index_defect_from_its_ // measured_release`). - // And, as every rasterizer but Apple's, `ClippedCoverageNotMetals`. + // And, as every rasterizer and tessellator but Apple's, `ClippedCoverageNotMetals` and + // `TessellatorNotMetals`. let both = [ defect, DriverWorkaround::MeshIndexComponentStoresMisplaced, DriverWorkaround::ClippedCoverageNotMetals, + DriverWorkaround::TessellatorNotMetals, ]; let mut desc = profile("lavapipe"); assert_eq!(desc.driver_id, Some(vk::DriverId::MESA_LLVMPIPE)); diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 48e3e4969..7c7df06f5 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1622,6 +1622,21 @@ pub enum PrecisionNote { /// the driver compiles the variants differently. Nothing broader. Recorded only by a fragment /// stage of such a pipeline. Validation derives no tolerance from it. ColorAttachmentGroups, + /// A tessellation pipeline drawn through the device's tessellation stages (a device with + /// `tessellationShader`) whose tessellator is not Apple's + /// ([`DriverWorkaround::TessellatorNotMetals`](crate::device::DriverWorkaround::TessellatorNotMetals)): + /// the device's tessellator orders each patch's triangles and picks each one's first corner, + /// and where Vulkan leaves it to the implementation chooses the triangles that join a patch's + /// rings, where Metal's tessellator draws the D3D11 reference's triangles in its own order, + /// each triangle's first corner by its stitch step (`lower::tessellation::tessellator`). The + /// domain points are Metal's; a flat varying (the first corner's), a value interpolated across + /// another triangulation, and the order in which a patch's triangles reach the blend or the + /// depth test may differ: every patch measured differs on the RTX 3090, 55-95% of them on RADV + /// and lavapipe. MoltenVK on an Apple GPU hands the patches to Metal's own tessellator and + /// records none; so does a pipeline on a device without `tessellationShader`, which draws + /// Metal's triangles in Metal's order through the emulation. Recorded on the evaluation stage. + /// Validation derives no tolerance from it. + TessellationTriangleOrder, } /// The math mode of an entry's module, which decides, on a device whose `float` functions are diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index 7470a740d..5608147d2 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -811,7 +811,7 @@ impl Device { } // A tessellation pipeline's synthesized vertex and control stages come first. if let Some(c) = &linked.control { - note_evaluation_stage(c, &mut stages); + note_evaluation_stage(c, p, &mut stages); let synthesized = synthesized_stages(c, &linked, p, m)?; let mut all = Vec::with_capacity(synthesized.len() + stages.len()); for (module, r) in synthesized { diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs index 5970048a6..6ed639f70 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs @@ -45,13 +45,15 @@ use std::collections::BTreeMap; use crate::budget::Meter; use crate::device::requirements::{Requirements, VkFeature, VkLimit}; -use crate::device::DeviceProfile; +use crate::device::{DeviceProfile, DriverWorkaround}; use crate::error::{ Capability, DescriptorError, Error, Feature, LowerFamily, RuntimeInput, Unsupported, }; use crate::lower::stage_io::fetch::encoding; use crate::metal::{TessellationControlPointIndexType, TessellationPartitionMode as Partition}; -use crate::pipeline::artifact::{Reconvergence, SpecializationLayout, StageModule, StrategyCensus}; +use crate::pipeline::artifact::{ + PrecisionNote, Reconvergence, SpecializationLayout, StageModule, StrategyCensus, +}; use crate::pipeline::descriptor::{TessellationDescriptor, VertexDescriptor}; use crate::pipeline::graphics::{EmulatedTessellation, TessellationState}; use crate::pipeline::interface::{StageInterface, TessellationStage}; @@ -324,17 +326,24 @@ pub fn push_offset(ranges: &[PushConstantRange], p: &DeviceProfile) -> Result Vec { let ours = [ PrecisionNote::TessellationWinding, PrecisionNote::TessellationFactorEdgeCases, PrecisionNote::TessellationFactorScale, PrecisionNote::TessellationFactorInstance, + PrecisionNote::TessellationTriangleOrder, ]; m.precision_notes .iter() @@ -944,6 +954,10 @@ fn a_tessellation_pipeline_links_four_stages_on_every_profile_with_tessellation( ) { notes.push(PrecisionNote::TessellationFactorInstance); } + if own_order { + notes.push(PrecisionNote::TessellationTriangleOrder); + } + notes.sort_unstable(); assert_eq!(tessellation_notes(&p.stages[2]), notes, "{stem} {entry}"); for i in [0, 1, 3] { assert_eq!(tessellation_notes(&p.stages[i]), [], "{stem} {entry} {i}"); @@ -954,6 +968,10 @@ fn a_tessellation_pipeline_links_four_stages_on_every_profile_with_tessellation( } } } + assert!( + ordered.iter().all(|&n| n > 0), + "profiles with Metal's tessellator and with their own: {ordered:?}" + ); // Without it, two stages: the vertex function draws the tessellator's triangles as a // triangle list from the draw's work buffer and records, and owns the index buffers. let mut compiled = vec![0; cases.len()]; @@ -1020,6 +1038,7 @@ fn a_tessellation_pipeline_links_four_stages_on_every_profile_with_tessellation( assert_eq!(b.stages, vertex, "{stem} {entry} {binding:?}"); } } + // The emulation draws Metal's triangles in Metal's order: no tessellation note. for m in &p.stages { assert_eq!( m.precision_notes @@ -1028,6 +1047,7 @@ fn a_tessellation_pipeline_links_four_stages_on_every_profile_with_tessellation( n, PrecisionNote::TessellationWinding | PrecisionNote::TessellationFactorEdgeCases + | PrecisionNote::TessellationTriangleOrder )) .count(), 0, diff --git a/crates/metal2vulkan/src/tests/fast_paths.rs b/crates/metal2vulkan/src/tests/fast_paths.rs index a13d8efb8..1bca86b52 100644 --- a/crates/metal2vulkan/src/tests/fast_paths.rs +++ b/crates/metal2vulkan/src/tests/fast_paths.rs @@ -190,6 +190,7 @@ fn notes() -> Vec<(&'static str, Ledger)> { DeviceAnisotropicFilter, DevicePointSize, ClippedCoverageSplit, + TessellationTriangleOrder, ], } } diff --git a/docs/API.md b/docs/API.md index 5aa563704..e79ed2c5a 100644 --- a/docs/API.md +++ b/docs/API.md @@ -176,8 +176,11 @@ first move, made by the next submission that may reach it (any command buffer's, submission of a host call on the texture, or `Texture::vk_image`), keeps the bytes the image is bound to, through the host: before that submission, once every submission made before it on each queue completed, the runtime reads them through the host pointer, submits the move alone and waits -for it, and writes them back, every one; no GPU command writes them, and no byte outside them is -touched (`WorkCounts::first_move_keeps`, `first_move_kept_bytes`). The submission waits for that, +for it, and writes back the bytes the move changed, so none is stored where it changed none (pages +the process cannot write stay untouched); no GPU command writes them, and no byte outside them is +touched (`WorkCounts::first_move_keeps`, `first_move_kept_bytes`, `first_move_restored_bytes`). +Changed bytes on pages the process no longer maps writable keep the move's values, announced +(`unrestored-first-move-bytes`). The submission waits for that, `commit` never. A rebind's new image keeps its new pages' bytes the same way. An image over a dma-buf of its own pages keeps them through its acquire from `VK_QUEUE_FAMILY_FOREIGN_EXT`, and a linear image of the runtime's own memory through its move from `PREINITIALIZED`. @@ -445,7 +448,8 @@ let pipeline = device.compile_render_pipeline(&descriptor, &Budget::standard())? Its `stages` are a synthesized vertex and tessellation control stage, the function as the evaluation stage, and the fragment stage. It draws patches only (`DrawCall::Patches` or -`PatchesIndirect`), with the factors from a tessellation factor buffer. +`PatchesIndirect`), with the factors from a tessellation factor buffer. The device's tessellator +orders the triangles (`PrecisionNote::TessellationTriangleOrder` where it is not Apple's). On a device without `tessellationShader` the pipeline is an emulation with no tessellation stage: the function is its vertex stage (`TRIANGLE_LIST`), and `graphics.emulated_tessellation` states @@ -1795,12 +1799,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. Vulkan frees no memory that submitted commands may still use (`VUID-vkFreeMemory-memory-00677`), so the pages stay: with no keep-alive (`KeepAlive`), while a command buffer submitted before a texture over them was released may still read that texture through its resource ID (its image - holds the import); with or without one, while a command buffer whose commands may reach the buffer + holds the import); with no keep-alive, while a command buffer whose commands may reach the buffer unnamed holds a table of the live buffers that lists it (its first submission's and its host steps', until it completes; one a rebind encoded again before its first submission, until then); with no keep-alive on MoltenVK (`RuntimeDriverDefect::FreedAddressMemoryFailsPendingWork`), while the batches submitted before the import's memory went are in flight, as MoltenVK fails pending work - that reads device addresses where such memory is freed. + that reads device addresses where such memory is freed. With a keep-alive the deallocator runs at + the release, as Metal's, and the import keeps the keep-alive, which keeps the pages mapped, until + it is freed: not announced. Cost: the deallocator runs once every such command buffer lets go of the pages, or those batches complete, where Metal's runs at the release; the pages stay mapped until then. - `metal2vulkan-degrade-misplaced-notice` (performance). `MisplacedNotice`: In a build without debug @@ -1878,6 +1884,14 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. draw counted by a `Counting` visibility result whose fragment function writes more than one color attachment, on ANV (`RuntimeDriverDefect::OcclusionCountPerColorOutput`). Cost: the result is Metal's count multiplied by the colors the draw writes; a `Boolean` result is Metal's. +- `metal2vulkan-degrade-unrestored-first-move-bytes` (precision). `UnrestoredFirstMoveBytes`: A + texture's first move over a no-copy buffer's host pages changed bytes the host kept across it, on + pages the process maps without write permission when the host writes them back: on Linux, pages + made read-only after the buffer was made (Linux refuses read-only pages at the import); on macOS + also pages read-only from the start, which Metal reads (a GPU write into them fails its command + buffer). Not observed on RADV, which fails the command buffers submitted after a page of an + import loses write permission (`HostMemory::new`). Cost: those bytes keep what the image's move + from `UNDEFINED` wrote, where Metal's texture leaves its pages as they were. - `metal2vulkan-degrade-f16-fma-double-rounding` (precision). `PrecisionNote::F16FmaDoubleRounding`: Widened half fma rounds twice. - `metal2vulkan-degrade-f16-int-conv-double-rounding` (precision). @@ -1946,6 +1960,15 @@ fast forms record, and each `PrecisionNote`'s rustdoc states its bound. `PrecisionNote::TessellationFactorInstance`: A tessellation pipeline whose factor step function is per instance reads instance `i`'s factors at `i ยท instanceStride`, `i` counting the draw's base instance as `[[instance_id]]` does. +- `metal2vulkan-degrade-tessellation-triangle-order` (precision). + `PrecisionNote::TessellationTriangleOrder`: A tessellation pipeline drawn through the device's + tessellation stages (a device with `tessellationShader`) whose tessellator is not Apple's (every + driver but MoltenVK on an Apple GPU, `DriverWorkaround::TessellatorNotMetals`): the device's + tessellator orders each patch's triangles, picks each one's first corner, and joins the patch's + rings where Vulkan leaves that to the implementation. The domain points are Metal's; a flat + varying, a value interpolated across another triangulation, and the order a patch's triangles + blend in may differ. A device without `tessellationShader` draws Metal's order through the + emulation (`emulated-tessellation-draws`) and records none. - `metal2vulkan-degrade-fp8-value` (precision). `PrecisionNote::Fp8Value`: An 8-bit float converts to an integer from the format's documented value with Metal's saturating float-to-integer rule, where Metal's device here answers otherwise: Metal on Apple M3 compiles these reads but extends diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index cb32bfdcd..3c41b4348 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -285,10 +285,11 @@ driver's. Each is open work. (`VUID-VkImageCreateInfo-pNext-01443`), and its first move may read and write all the memory bound to it, so the host keeps those bytes (`texture/first_move.rs`, `device/submit.rs`): once the submissions before have completed, it reads them through the host pointer, submits the moves - alone, waits, and writes them back. A CPU write to them in between, within one submission's round - trip of the commit that makes the move, is undone, once per image (`texture/shared_alias.rs`); - Metal keeps it, and never writes the bytes between a texture's rows. No byte outside them is read - or written (`runtime_lane::pitched_surfaces`: `a_texture_s_first_move_keeps_the_bytes_it_lies_over`, + alone, waits, and writes back those that differ. A CPU write to them in between, within one + submission's round trip of the commit that makes the move, is undone, once per image + (`texture/shared_alias.rs`); Metal keeps it, and never writes the bytes between a texture's rows. + No byte outside them is read or written (`runtime_lane::pitched_surfaces`: + `a_texture_s_first_move_keeps_the_bytes_it_lies_over`, `a_cpu_write_during_a_texture_s_first_move_stays_outside_its_bytes`). - **A cold pipeline making on NVIDIA grows with a module's sampling sites.** NVIDIA's compiler takes about 1 s for macOS 26's largest CoreAnimation fragment (210,033 words) on the RTX 5080 Laptop @@ -335,11 +336,12 @@ driver's. Each is open work. - **macOS 27.0.1 answers measured only on an Apple M4.** The level answers an Apple M4's block placement of a heap's block-compressed textures and its compressed-texture blits until an M3 Max probe replaces them. +- **Tessellation's triangle order.** On a device with `tessellationShader` but MoltenVK on an + Apple GPU, the device's tessellator orders a patch's triangles, picks their first corners and + joins its rings itself, announced as `TessellationTriangleOrder` + (`tessellation-triangle-order`): every patch differs on the RTX 3090, 55-95% on RADV and + lavapipe. - **lavapipe aborts on the owned fixture `mesh_order`'s mesh functions.** Compiling `mesh_order_mesh` or `mesh_order_solo` ends the process inside lavapipe's compiler ("LLVM ERROR: Cannot emit physreg copy instruction"); the validation case `mesh_order_mesh-payload-mesh-draw` runs on a GPU only. The construct behind the abort is not isolated yet. -- **Tessellation's triangle order.** On a device with `tessellationShader` the device's - tessellator orders a patch's triangles and picks each one's first corner itself (Vulkan leaves - the order to the implementation), not as Metal does: every patch differs on the RTX 3090, 55-95% - of them on RADV and lavapipe. No note announces it. diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 5394c2113..99f5f777c 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -14,7 +14,7 @@ Columns: - `none`: no public API path: malformed or non-Metal input, Apple-private calls, or a cap no valid program of ordinary size meets; - `?`: not assessed yet. -Generated at `4c29fe6a5`. +Generated at `ba16d0c0a`. ## Totals @@ -351,7 +351,7 @@ Each refusal's sites, with the function that builds it. - `feature::RasterOrderGroups`: `crates/metal2vulkan/src/device/metal.rs:242 (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/rog.rs:151 (mode)`; `crates/metal2vulkan/src/lower/fragment/rog.rs:172 (mode)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs:158 (finish)` - `feature::FramebufferFetch`: `crates/metal2vulkan-runtime/src/families/features.rs:1007 (state)`; `crates/metal2vulkan-runtime/src/framebuffer_fetch.rs:402 (ordered)`; `crates/metal2vulkan-runtime/src/render.rs:5174 (next_instance)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:111 (lacks)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:138 (new)`; `crates/metal2vulkan-runtime/src/sample_planes.rs:497 (planes_merge)`; `crates/metal2vulkan/src/bind/extended_shadow.rs:190 (extended_shadow_module)`; `crates/metal2vulkan/src/bind/graphics.rs:1422 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1459 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:1478 (plan)`; `crates/metal2vulkan/src/bind/sample_planes.rs:431 (finish)`; `crates/metal2vulkan/src/device/metal.rs:255 (unsupported_features)`; `crates/metal2vulkan/src/lower/fragment/color.rs:208 (select_param)`; `crates/metal2vulkan/src/lower/fragment/color.rs:257 (unordered)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:196 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:271 (depth_test_form)`; `crates/metal2vulkan/src/lower/fragment/depth_test.rs:317 (stencil_test_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:1493 (plan_sample)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:635 (not_implemented)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:850 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:916 (storage_form)`; `crates/metal2vulkan/src/lower/fragment/fetch.rs:952 (extended_range_blend)`; `crates/metal2vulkan/src/pipeline/link/fetch.rs:159 (storage_attachments)` - `feature::PrimitiveId`: `crates/metal2vulkan-runtime/src/families/features.rs:1115 (state)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:2989 (finish)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:240 (check_primitive_id)` -- `feature::VertexAmplification`: `crates/metal2vulkan/src/bind/graphics.rs:3834 (multiview_instances)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1258 (own_index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:718 (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:243 (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:226 (control_plan)` +- `feature::VertexAmplification`: `crates/metal2vulkan/src/bind/graphics.rs:3834 (multiview_instances)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1258 (own_index_store)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:718 (select_param)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:243 (vertex_amplification)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:228 (control_plan)` - `feature::LayeredRendering`: `crates/metal2vulkan-runtime/src/render_pass.rs:1556 (target)`; `crates/metal2vulkan-runtime/src/render_state.rs:1072 (needs_viewports)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:778 (target_index)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:797 (target_index)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1259 (own_index_store)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs:150 (not_implemented)`; `crates/metal2vulkan/src/pipeline/link/geometry.rs:172 (refused)` - `feature::ClipDistance`: `crates/metal2vulkan/src/lower/mesh/mod.rs:934 (select)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:942 (select)` - `feature::DualSourceBlending`: `crates/metal2vulkan-runtime/src/families/formats.rs:398 (answers)`; `crates/metal2vulkan/src/metal/state.rs:37 (blend_factor)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:1073 (check_outputs)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs:464 (rotated_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs:539 (rotated_blend)` @@ -362,7 +362,7 @@ Each refusal's sites, with the function that builds it. - `feature::InterfaceComponents`: `crates/metal2vulkan/src/pipeline/compile/color_group.rs:202 (refusal)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs:286 (graphics_state)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:409 (assign)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:90 (limit_error)` - `feature::UnmatchedVarying`: `crates/metal2vulkan/src/pipeline/link/varyings.rs:318 (mesh_fragment)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:537 (varyings)`; `crates/metal2vulkan/src/pipeline/link/varyings.rs:548 (varyings)` - `feature::KernelStageIn`: `crates/metal2vulkan-runtime/src/indirect_execute.rs:337 (record)`; `crates/metal2vulkan/src/bind/dispatch.rs:881 (instantiate)`; `crates/metal2vulkan/src/lower/stage_io/stage_in.rs:133 (select)` -- `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs:1238 (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs:1329 (post_check)`; `crates/metal2vulkan/src/bind/graphics.rs:3691 (tessellation_dispatch)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:519 (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1434 (primitive_id_output)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1727 (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:776 (param)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:150 (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:489 (plan_entry)`; `crates/metal2vulkan/src/metal/vertex.rs:219 (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:210 (control_plan)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:290 (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:314 (push_offset)` +- `feature::Tessellation`: `crates/metal2vulkan-air/src/canon/mod.rs:1238 (post_check)`; `crates/metal2vulkan-air/src/canon/mod.rs:1329 (post_check)`; `crates/metal2vulkan/src/bind/graphics.rs:3691 (tessellation_dispatch)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:519 (select)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1434 (primitive_id_output)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:1727 (input_builtin)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs:776 (param)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:150 (not_implemented)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:489 (plan_entry)`; `crates/metal2vulkan/src/metal/vertex.rs:219 (fetch_as)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:212 (control_plan)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:292 (check_fragment)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:316 (push_offset)` - `feature::MeshShading`: `crates/metal2vulkan/src/bind/graphics.rs:1505 (plan)`; `crates/metal2vulkan/src/bind/graphics.rs:2903 (mesh_limit)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:499 (check_payload)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:538 (plan_entry)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:572 (plan_entry)`; `crates/metal2vulkan/src/memory/plan.rs:1849 (reprs)`; `crates/metal2vulkan/src/pipeline/link/mesh.rs:95 (records)` - `feature::TileShading`: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs:498 (scratch)`; `crates/metal2vulkan/src/bind/plan/compute.rs:236 (tile_memory)`; `crates/metal2vulkan/src/lower/access/tile.rs:151 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:275 (tile_shading)`; `crates/metal2vulkan/src/pipeline/compile/api.rs:661 (tile_pipeline)` - `feature::Imageblocks`: `crates/metal2vulkan/src/lower/access/imageblock.rs:98 (imageblocks)`; `crates/metal2vulkan/src/lower/access/mod.rs:886 (select_param)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs:103 (require)`; `crates/metal2vulkan/src/lower/fragment/imageblock.rs:85 (not_implemented)`; `crates/metal2vulkan/src/lower/texture/mod.rs:2290 (select)`; `crates/metal2vulkan/src/lower/texture/slice.rs:127 (imageblocks)`; `crates/metal2vulkan/src/pipeline/link/imageblock.rs:46 (fragment_imageblock)` @@ -378,7 +378,7 @@ Each refusal's sites, with the function that builds it. - `feature::SubgroupOperations`: `crates/metal2vulkan-runtime/src/families/features.rs:1686 (simd)`; `crates/metal2vulkan/src/lower/simd/mod.rs:402 (finish)`; `crates/metal2vulkan/src/lower/simd/mod.rs:448 (full_quads)`; `crates/metal2vulkan/src/lower/simd/mod.rs:975 (select_group)` - `feature::DirectCall`: `crates/metal2vulkan-air/src/canon/mod.rs:1301 (post_check)` - `feature::WideSwitchLiteral`: `crates/metal2vulkan/src/structurize/emit.rs:207 (check_tree)` -- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs:754 (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs:1062 (texture_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:1073 (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:318 (domain_kind)`; `crates/metal2vulkan/src/lower/access/imageblock.rs:175 (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs:571 (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs:76 (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs:53 (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs:113 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:144 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:653 (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs:121 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs:168 (finish)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:147 (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:126 (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs:212 (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs:30 (refuse)`; `crates/metal2vulkan/src/lower/select.rs:817 (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs:906 (route_air)`; `crates/metal2vulkan/src/lower/simd/mod.rs:136 (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs:732 (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs:353 (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:96 (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs:173 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:72 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:269 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:310 (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:146 (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs:178 (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3566 (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs:46 (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs:183 (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs:453 (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs:662 (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:94 (patch_fetch_projection)` +- `feature::Lowering`: `crates/metal2vulkan/src/bind/plan/resources.rs:754 (level_views)`; `crates/metal2vulkan/src/lower/access/handle.rs:1062 (texture_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:1073 (sampler_target)`; `crates/metal2vulkan/src/lower/access/handle.rs:318 (domain_kind)`; `crates/metal2vulkan/src/lower/access/imageblock.rs:175 (operand)`; `crates/metal2vulkan/src/lower/access/mod.rs:571 (not_lowered)`; `crates/metal2vulkan/src/lower/access/pulled.rs:76 (share)`; `crates/metal2vulkan/src/lower/arith/legal.rs:53 (not_lowered)`; `crates/metal2vulkan/src/lower/dispatch.rs:113 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:144 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/discard.rs:653 (plan)`; `crates/metal2vulkan/src/lower/fragment/mod.rs:121 (not_lowered)`; `crates/metal2vulkan/src/lower/fragment/snapshot.rs:168 (finish)`; `crates/metal2vulkan/src/lower/mesh/mod.rs:147 (not_lowered)`; `crates/metal2vulkan/src/lower/raytracing/mod.rs:126 (not_lowered)`; `crates/metal2vulkan/src/lower/sampler/mod.rs:212 (refuse)`; `crates/metal2vulkan/src/lower/sampler/select.rs:30 (refuse)`; `crates/metal2vulkan/src/lower/select.rs:817 (not_lowered)`; `crates/metal2vulkan/src/lower/select.rs:906 (route_air)`; `crates/metal2vulkan/src/lower/simd/mod.rs:136 (not_lowered)`; `crates/metal2vulkan/src/lower/simd/mod.rs:732 (select_param)`; `crates/metal2vulkan/src/lower/simd/workgroup.rs:353 (check)`; `crates/metal2vulkan/src/lower/stage_io/fetch.rs:96 (not_lowered)`; `crates/metal2vulkan/src/lower/stage_io/mod.rs:173 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/barrier.rs:72 (not_lowered)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:269 (not_implemented)`; `crates/metal2vulkan/src/lower/sync/memory_model.rs:310 (select)`; `crates/metal2vulkan/src/lower/tessellation/mod.rs:146 (not_lowered)`; `crates/metal2vulkan/src/lower/texture/mod.rs:178 (refuse)`; `crates/metal2vulkan/src/lower/texture/mod.rs:3566 (select_write)`; `crates/metal2vulkan/src/memory/alloca.rs:46 (not_lowered)`; `crates/metal2vulkan/src/memory/leaf.rs:183 (not_lowered)`; `crates/metal2vulkan/src/memory/plan.rs:453 (not_lowered)`; `crates/metal2vulkan/src/memory/provenance.rs:662 (not_lowered)`; `crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs:96 (patch_fetch_projection)` - `feature::SamplerAddressMode`: `crates/metal2vulkan/src/lower/sampler/constexpr.rs:176`; `crates/metal2vulkan/src/metal/sampler.rs:251 (check_sampler)` - `feature::AlphaToOne`: `crates/metal2vulkan/src/pipeline/link/graphics.rs:267 (graphics_state)` - `feature::StageStoresAndAtomics`: `crates/metal2vulkan/src/lower/access/tile_memory.rs:73 (written)`