From c032eb5f59503aee0cd748137dc7bbfd78c6013a Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sun, 8 Nov 2026 23:26:55 -0800 Subject: [PATCH] The in-place check's queue is the runtime's own: it makes no texture pool and takes no sampler ID The device's in-place check of render targets made its passes' queue with new_command_queue_now, whose place took Metal's device sampler ID and made the texture pool as the program's first command queue does (resource_ids.rs). The check runs on its thread while the program makes its objects, so on a device whose check made that queue before the program's reservation: - a texture reservation kept the pool's first range (1 to 15) beside its own, and plain textures took those IDs again (the consumer's pin 27: 15 of 256 plain textures inside the reserved range); - the device sampler ID started the sampler pool, so a sampler reservation was ignored, with a late-reservation line. Queues now carry whom they were made for (queue.rs, MadeFor). Device::own_command_queue_now makes a round-robin queue as new_command_queue_now does, but its places, a recovery's new one included, touch neither ID rule; the check takes its queue there. The check's draw (CheckDraw) makes only Vulkan objects and takes no Metal ID. No other runtime-internal queue exists. The test replaces the one before it, which asserted the wrong mechanism: settle the check, then reserve texture IDs 1 to 64 and sampler IDs 1 to 16, make 32 plain textures and 8 plain sampler states, and assert none lands in a reserved range and no late-reservation line is given; the same with the reservation made as the device is made. It prints whether the check made its render queue before the reservation, the path the bug needs. Verification: device runs on lavapipe, Iris and the M3, each with a negative control at the previous queue.rs and in_place_check.rs, are reported with the branch. (cherry picked from commit cdc84aff87ef5faee0f4d48bc242862570ea1412) --- .../src/in_place_check.rs | 15 ++- crates/metal2vulkan-runtime/src/queue.rs | 75 +++++++++--- .../metal2vulkan-runtime/src/resource_ids.rs | 3 +- .../src/tests/blit_holds.rs | 2 +- .../src/tests/in_place_check.rs | 114 +++++++++++++----- 5 files changed, 156 insertions(+), 53 deletions(-) diff --git a/crates/metal2vulkan-runtime/src/in_place_check.rs b/crates/metal2vulkan-runtime/src/in_place_check.rs index 3841dfc34..c95e10185 100644 --- a/crates/metal2vulkan-runtime/src/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/in_place_check.rs @@ -91,11 +91,14 @@ //! the program makes its resources, so a range of the space it took would refuse a pin of the //! program's there, or move a range the runtime picks for it. Its pages, their import, the //! image and the move do not depend on the address, so neither does a verdict. -//! - **Its textures take no resource ID** (`IdUse::Runtime`, `resource_ids.rs`): the check runs -//! on its thread while the program makes its textures, so a plain ID one of its textures held -//! would move the program's next texture's ID past Metal's, and a texture reservation after it -//! would be ignored. The ID does not touch the image, its pages or its move, so neither does a -//! verdict. +//! - **Its textures take no resource ID** (`IdUse::Runtime`, `resource_ids.rs`), and its queue +//! touches no ID rule of Metal's device (`Device::own_command_queue_now`, `queue.rs`): the +//! check runs on its thread while the program makes its textures, so a plain ID one of its +//! textures held would move the program's next texture's ID past Metal's, and a texture +//! reservation after it would be ignored; a queue of the program's would make the texture pool, +//! keeping its first range beside a later texture reservation, and take the device's sampler +//! ID, ignoring a later sampler reservation. The ID does not touch the image, its pages or its +//! move, so neither does a verdict. //! - **Its cost** is the pattern's fill and compare of each window, at the speed of a copy and a //! comparison of memory (a 3840x2160 surface's 33 MB among them), and each image's making and //! first move (and pass, or kernel's stores): the writes themselves run only while those do. @@ -688,7 +691,7 @@ fn check_class( | Access::NarrowBufferWrites => None, Access::Renders => { let made = exit_guard::enter().map(|_busy| { - let queue = device.new_command_queue_now()?; + let queue = device.own_command_queue_now()?; Ok::<_, crate::Error>((queue, CheckDraw::new(device)?)) }); match made? { diff --git a/crates/metal2vulkan-runtime/src/queue.rs b/crates/metal2vulkan-runtime/src/queue.rs index 0cb2a04ab..21d848626 100644 --- a/crates/metal2vulkan-runtime/src/queue.rs +++ b/crates/metal2vulkan-runtime/src/queue.rs @@ -81,6 +81,14 @@ //! command buffers hold. A recovery retires every queue's place; the queue takes a new one on the //! new generation, as it took its first, at its next command buffer (or lent `VkQueue`), and its //! label and its count of the GPU errors its command buffers caused (`revocation.rs`) go on. +//! +//! **The runtime's own queues.** The device's in-place check of render targets takes its passes on +//! a queue of its own (`in_place_check.rs`), made as a program's is but for Metal's device ID +//! rules: Metal's device makes its texture pool and takes its sampler ID at the program's first +//! command queue (`resource_ids.rs`), and the check runs on its thread while the program makes its +//! objects, so a queue of its that counted as the program's would keep the pool's first range +//! beside a texture reservation the program made after it, and ignore a sampler reservation. +//! Every place of such a queue, a recovery's new one included, touches neither rule. use super::attachment_stand_in::BackingPool; use super::command_buffer::hang::QueueHangs; @@ -114,6 +122,8 @@ pub(crate) struct QueueLine { device: Device, /// Which constructor made it. kind: Kind, + /// Whether the program made it, for Metal's device ID rules. + made_for: MadeFor, /// Its `maxCommandBufferCount`. count: usize, common: Arc, @@ -164,6 +174,17 @@ enum Kind { Presenting, } +/// Whom a queue was made for, and so whether its places count toward Metal's device ID rules +/// (the module docs, `resource_ids.rs`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum MadeFor { + /// A constructor the program called: Metal's device makes its texture pool and takes its + /// sampler ID at its first queue. + Program, + /// The runtime's own (`Device::own_command_queue_now`): touches neither rule. + Runtime, +} + /// [`QueueShared::sharing`]: one of its command buffers ran long (`queue_share::LONG_HEAD`). const LONG: u8 = 1; /// [`QueueShared::sharing`]: a long queue that settled, for good. @@ -339,7 +360,19 @@ impl Device { if self.is_lost() { return Err(self.lost_refusal()); } - Ok(self.command_queue(count, Kind::RoundRobin)) + Ok(self.command_queue(count, Kind::RoundRobin, MadeFor::Program)) + } + + /// No Metal counterpart: a queue the runtime makes for its own work (the module docs), as + /// [`new_command_queue`](Self::new_command_queue)'s on the generation that serves, but that + /// makes no texture pool and takes no sampler ID of Metal's device (`resource_ids.rs`). + /// Refused as that call is on a lost device (`DeviceLost`). + pub(crate) fn own_command_queue_now(&self) -> Result { + if self.is_lost() { + return Err(self.lost_refusal()); + } + let count = DEFAULT_MAX_COMMAND_BUFFER_COUNT; + Ok(self.command_queue(count, Kind::RoundRobin, MadeFor::Runtime)) } /// No Metal counterpart: a command queue of at most `count` uncompleted command buffers, as @@ -390,7 +423,7 @@ impl Device { if self.is_lost() { return Err(self.lost_refusal()); } - Ok(self.command_queue(count, Kind::Unshared)) + Ok(self.command_queue(count, Kind::Unshared, MadeFor::Program)) } /// No Metal counterpart: a queue for presenting, of at most 64 uncompleted command buffers as @@ -420,21 +453,23 @@ impl Device { if self.is_lost() { return Err(self.lost_refusal()); } - Ok(self.command_queue(DEFAULT_MAX_COMMAND_BUFFER_COUNT, Kind::Presenting)) + let count = DEFAULT_MAX_COMMAND_BUFFER_COUNT; + Ok(self.command_queue(count, Kind::Presenting, MadeFor::Program)) } - /// A queue of at most `count` uncompleted command buffers made by `kind`'s constructor, with - /// its place on this generation, known to the device's line, whose recoveries retire it - /// (`device/line.rs`). - fn command_queue(&self, count: usize, kind: Kind) -> CommandQueue { + /// A queue of at most `count` uncompleted command buffers made by `kind`'s constructor for + /// `made_for`, with its place on this generation, known to the device's line, whose + /// recoveries retire it (`device/line.rs`). + fn command_queue(&self, count: usize, kind: Kind, made_for: MadeFor) -> CommandQueue { let common = Arc::new(QueueCommon { label: Mutex::new(None), errors: QueueErrors::default(), }); - let place = self.queue_place(count, kind, &common); + let place = self.queue_place((count, kind, made_for), &common); let queue = CommandQueue(Arc::new(QueueLine { device: self.root(), kind, + made_for, count, common, cell: Mutex::new(Place::Serving(place)), @@ -476,14 +511,22 @@ impl Device { } /// A queue's place on this generation (the module docs), of at most `count` uncompleted - /// command buffers, made by `kind`'s constructor, `common` what its places share: on the - /// `VkQueue` [`place_queue`](Self::place_queue) gives. One on a round robin's `VkQueue` counts - /// itself there (an unshared one counted itself already), and the first starts the device's - /// check of its GPU's idling between `VkQueue`s (`queue_share.rs`). - fn queue_place(&self, count: usize, kind: Kind, common: &Arc) -> QueueGen { + /// command buffers, made by `kind`'s constructor for `made_for`, `common` what its places + /// share: on the `VkQueue` [`place_queue`](Self::place_queue) gives. One the program made + /// takes Metal's device sampler ID and makes its texture pool, as Metal's first queue does + /// (`resource_ids.rs`); the runtime's own touches neither. One on a round robin's `VkQueue` + /// counts itself there (an unshared one counted itself already), and the first starts the + /// device's check of its GPU's idling between `VkQueue`s (`queue_share.rs`). + fn queue_place( + &self, + (count, kind, made_for): (usize, Kind, MadeFor), + common: &Arc, + ) -> QueueGen { let (id, vk_queue) = self.place_queue(kind); - self.take_device_sampler(); - self.make_texture_pool(); + if made_for == MadeFor::Program { + self.take_device_sampler(); + self.make_texture_pool(); + } self.keep_room(); let shared = self.shared(); if vk_queue < shared.round_robin() { @@ -528,7 +571,7 @@ impl QueueLine { return place.clone(); } } - let place = device.queue_place(self.count, self.kind, &self.common); + let place = device.queue_place((self.count, self.kind, self.made_for), &self.common); let retired = std::mem::replace(&mut *cell, Place::Serving(place.clone())); drop(cell); drop(retired); diff --git a/crates/metal2vulkan-runtime/src/resource_ids.rs b/crates/metal2vulkan-runtime/src/resource_ids.rs index ccdc40f74..444f6b65f 100644 --- a/crates/metal2vulkan-runtime/src/resource_ids.rs +++ b/crates/metal2vulkan-runtime/src/resource_ids.rs @@ -43,7 +43,8 @@ //! it leaves, and Metal hands out that range's IDs again while textures hold them (20 reserved //! gives 21 to 31, 1 to 15, 1 to 15 again, 16 to 19, 32 on). The runtime hands them out as Metal //! does: both textures answer the ID, the slot is the later one's (Slots), and each gives it back -//! as it goes, as Metal's do ([`Pool`]). +//! as it goes, as Metal's do ([`Pool`]). A queue the runtime makes for its own work (its +//! in-place check's, `queue.rs`) is no Metal queue: it makes no pool and takes no sampler ID. //! - **The device's sampler ID** (the consumer's M3 Max report at 701572bbf, the M4 probes, plain //! and under API validation alike). Metal's device keeps a sampler ID for itself for good as it //! makes its first command queue, indirect command buffer, or texture whose memory is its own (of diff --git a/crates/metal2vulkan-runtime/src/tests/blit_holds.rs b/crates/metal2vulkan-runtime/src/tests/blit_holds.rs index f2da10d10..a53c93b4c 100644 --- a/crates/metal2vulkan-runtime/src/tests/blit_holds.rs +++ b/crates/metal2vulkan-runtime/src/tests/blit_holds.rs @@ -159,7 +159,7 @@ pub(super) fn shadow_device(cache: &Path) -> Device { } /// The options of [`device`]. -fn options(cache: &Path) -> DeviceOptions { +pub(super) fn options(cache: &Path) -> DeviceOptions { DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index dc51ab17b..0a877ed98 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -2,7 +2,8 @@ //! address space: its buffers, one per class of pages, lie outside it (`address.rs`, "Outside the //! space"), so no pin or pick of the program's depends on whether or when the check runs, and the //! space's state changes no verdict. Nor does it take a texture ID: its textures are the -//! runtime's own (`resource_ids.rs`), so the program's IDs are Metal's whether or when it runs. +//! runtime's own (`resource_ids.rs`), and its queue touches no ID rule of Metal's device +//! (`queue.rs`), so the program's IDs and reservations are Metal's whether or when it runs. //! And it checks fresh pages wherever the device takes them, also where its held imports cost its //! submissions and no long buffer of the product's lies in them. //! @@ -11,17 +12,20 @@ //! directory, so no record holds its verdicts and its check runs; the two devices the placement //! test compares find there only a record of the same submission-check answers ([`answering`]). -use super::blit_holds::{device, Scratch}; +use super::blit_holds::{device, options, Scratch}; use crate::address::{PAGE, SPACE_BASE, SPACE_END}; use crate::fresh_pages::FRESH_PAGES_PAST; use crate::in_place::{verdict_index, Access, PagesClass, RowEnds, Verdict as InPlaceVerdict}; use crate::submit_check::{encode, record_name, Check, Measured, Verdict}; use crate::{ - AddressPlacement, Buffer, BufferContents, BufferDescriptor, Device, Error, GpuAddress, - ResourceId, ResourceIdKind, ResourceOptions, Texture, TextureDescriptor, + AddressPlacement, Buffer, BufferContents, BufferDescriptor, DebugMessage, Device, + DeviceOptions, Error, GpuAddress, MessageSink, ResourceId, ResourceIdKind, ResourceOptions, + SamplerState, SamplerStateOptions, Texture, TextureDescriptor, }; +use metal2vulkan::bind::SamplerDescriptor; use metal2vulkan::metal::{PixelFormat, TextureUsage}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; /// The longest a check may take. @@ -392,40 +396,92 @@ fn the_in_place_check_takes_no_texture_id() { ); } -/// A texture reservation made as soon as the device is made, as a consumer's first call reserves -/// its guest's IDs, is kept whatever the device's check does meanwhile on its thread, and so is -/// one made once the check has run to its end: the plain textures made after it take IDs past the -/// reserved range, and no late-reservation diagnostic is given. A texture of the check's that took -/// a plain ID would start the pool before the reservation, which is then ignored (Metal's pool -/// logs "reserve() must be called before any allocation takes place"), and the plain textures -/// take the reserved IDs from 1. +/// The device the cfg selects over `cache`, as [`device`]'s, with a sink that keeps the code of +/// every message it gives. +fn hearing(cache: &Path) -> (Device, Arc>>) { + let heard: Arc>> = Arc::default(); + let kept = Arc::clone(&heard); + let options = DeviceOptions { + messages: Some(MessageSink::new(move |message: &DebugMessage| { + kept.lock().unwrap().push(message.id_name.clone()); + })), + ..options(cache) + }; + (Device::system_default_with(&options).unwrap(), heard) +} + +/// A plain sampler state of the program's, its LOD clamped from `lod`, so that each `lod` gives +/// a state of its own; its ID readable (`support_argument_buffers`). +fn sampler_state(device: &Device, lod: u32) -> SamplerState { + let mut descriptor = SamplerDescriptor::new(); + descriptor.lod_min_clamp = lod as f32; + let mut options = SamplerStateOptions::default(); + options.support_argument_buffers = true; + (device.new_sampler_state_with_options(&descriptor, options)).unwrap() +} + +/// Whether the device's check made the queue its render passes take (`Access::Renders`): a +/// class it checked for rendering, passed or failed, made it first. +fn check_rendered(device: &Device) -> bool { + let verdicts = device.shared().in_place.verdicts(); + (PagesClass::ALL.into_iter()).any(|class| { + RowEnds::ALL.into_iter().any(|rows| { + let verdict = verdicts[verdict_index(class, Access::Renders, rows)]; + matches!(verdict, InPlaceVerdict::Passed | InPlaceVerdict::Failed) + }) + }) +} + +/// The program's reservations hold whatever the device's check did before them: its render +/// passes take a queue of the runtime's own (`queue.rs`), which touches no ID rule of Metal's +/// device. Once the check has run to its end, a reservation of texture IDs 1 to 64 and of sampler +/// IDs 1 to 16 holds: plain textures made after it take IDs past 64, plain sampler states IDs +/// past 16, and no late-reservation line is given. A check queue that counted as the program's +/// first queue would have made the texture pool, so the reservation kept the pool's first range +/// beside its own and the plain textures took 1 to 15 again; and it would have taken the device's +/// sampler ID, so the sampler reservation was ignored, with a late-reservation line, and the +/// plain states took the reserved IDs. A reservation made as soon as the device is made, as a +/// consumer's first call reserves its guest's IDs, holds as well, whatever the check does on its +/// thread meanwhile. #[test] -fn a_texture_reservation_made_with_the_device_is_kept_whatever_its_check_does() { - const RESERVED: u64 = 64; - for settled in [false, true] { +fn reservations_hold_whatever_the_in_place_check_did() { + const TEXTURES: u64 = 64; + const SAMPLERS: u64 = 16; + for settled in [true, false] { let scratch = Scratch::new("in-place-check-reservation"); - let device = device(&scratch.0); + let (device, heard) = hearing(&scratch.0); if settled { assert!(device.settle_in_place_checks(WAIT), "the check answered"); } - let ids = &device.shared().resource_ids; - let started = crate::device::lock(ids).started(crate::resource_ids::IdSpace::Texture); - let reserved: Vec = (1..=RESERVED).map(ResourceId).collect(); - device - .reserve_resource_ids(ResourceIdKind::Texture, &reserved) - .unwrap(); - let made: Vec = (0..16).map(|_| texture(&device)).collect(); - let ids: Vec = made.iter().map(|t| t.gpu_resource_id().0).collect(); + let rendered = check_rendered(&device); + let reserve = |kind, last: u64| { + let ids: Vec = (1..=last).map(ResourceId).collect(); + device.reserve_resource_ids(kind, &ids).unwrap(); + }; + reserve(ResourceIdKind::Texture, TEXTURES); + reserve(ResourceIdKind::SamplerState, SAMPLERS); + let textures: Vec = (0..32).map(|_| texture(&device)).collect(); + let states: Vec = (0..8).map(|lod| sampler_state(&device, lod)).collect(); + let texture_ids: Vec = textures.iter().map(|t| t.gpu_resource_id().0).collect(); + let sampler_ids: Vec = states.iter().map(|s| s.gpu_resource_id().0).collect(); + let late = (heard.lock().unwrap().iter()) + .filter(|code| *code == "metal2vulkan-late-reservation") + .count(); eprintln!( - "IN-PLACE-CHECK-RESERVATION on {}, the check settled first {settled}: the texture \ - IDs had started before the reservation: {started}; the plain textures took {ids:?}", + "IN-PLACE-CHECK-RESERVATION on {}, the check settled first {settled}, its render \ + queue made before the reservation {rendered}: plain textures took {texture_ids:?}, \ + plain sampler states {sampler_ids:?}; late-reservation lines {late}", device.name() ); - assert!(!started, "the texture IDs started before the reservation"); assert!( - ids.iter().all(|&id| id > RESERVED), - "plain textures took reserved IDs: {ids:?}" + texture_ids.iter().all(|&id| id > TEXTURES), + "plain textures took reserved IDs: {texture_ids:?}" ); + assert!( + sampler_ids.iter().all(|&id| id > SAMPLERS), + "plain sampler states took reserved IDs: {sampler_ids:?}" + ); + assert_eq!(late, 0, "a reservation was ignored as late"); } }