Skip to main content

gpu/
vk_dev.rs

1// vk_dev -- Vulkan device and queue: creation, the timeline, deferred destruction, command
2// buffer slots, staged uploads, submission
3//
4//   adapter.create_device(&DeviceDesc) -> Result<Device>
5//        one queue (the first family with graphics + compute, presentation checked per
6//        surface); level Voll when the adapter has it and desc.max_level allows it.  Enabled:
7//        timeline semaphores, dynamic rendering (core 1.3 or the KHR extensions on 1.1 / 1.2),
8//        VK_KHR_swapchain when the instance has surfaces, the optional features of Features,
9//        the Vulkan memory model only together with its device scope (else Device-scope
10//        atomics, as in the benchmark's cull, would be invalid); on Voll also descriptor
11//        indexing (update after bind, partially bound, non-uniform indexing) and
12//        draw-indirect-count; maintenance4 on Vulkan 1.3 (LocalSizeId); for shaders compiled
13//        from WGSL (lib/wgsl): f16 in uniform buffers and push constants, the standard uniform
14//        buffer layout, demote-to-helper (discard on Vulkan 1.3), clip distances, the
15//        primitive index (geometryShader), sample-rate shading, dual-source blending in
16//        shaders, the extended storage image formats, storage reads without format.  Not
17//        enabled: robust buffer access (speed; lib/wgsl's back end clamps indices instead).
18//   device.queue() -> &Queue        queue.submit([cmd, ..]) -> Result<SubmitId>, submit_after(&[id], [cmd, ..])
19//   device.compute_queue() -> Option<&ComputeQueue>    (G5d) a queue of its own for compute and copies when
20//        DeviceOptions::compute_queue asked for it (Adapter::create_device_with): a family without graphics where the
21//        device has one (jfgui_GPU_COMPUTE=0: none); encoder(), submit, submit_after
22//   queue.write_buffer(&buf, off, &[T])            staged into an upload command buffer that
23//   queue.write_texture(&region, &[u8], layout, before, after)   runs first in the next submit
24//   queue.write_texture_rects(&tex, &rects, &[u8], stride, before, after)   rectangles of a frame
25//   queue.write_texture_rects_at(&tex, &rects, origin, &[u8], stride, before, after)   of a larger image
26//   queue.read_buffer(&buf, off, &mut [T])          copies, submits and waits (slow path)
27//   queue.flush() -> Result<SubmitId>               submit the pending uploads now
28//   device.wait(id, timeout_ns) -> Result<bool>     false: timed out
29//   device.wait_idle(), poll() (frees what the GPU has finished with), is_lost(),
30//   test_lose() (a test aid: the device behaves as lost from now on)
31//
32// The timeline: one timeline semaphore per device; every submit signals the next value
33// (SubmitId).  completed caches the last value seen reached (vkGetSemaphoreCounterValue at
34// submits, polls and waits).  A dropped resource goes to the garbage with the value of the
35// latest submit and is destroyed once that value is reached -- earlier if no submit is
36// pending; a buffer or image, which the open upload command buffer (or one another thread took
37// and has not submitted yet) may name, waits until every such upload is submitted and then takes
38// the value reached by then (State::pending).  Command buffers come from slots (a transient command pool with one buffer each),
39// reused once their submission completed.  Uploads: the data goes into the staging ring, the
40// copies into one upload command buffer that ends with a global barrier (copy writes -> every
41// later access) and is put before the caller's command buffers in the next vkQueueSubmit.
42// The staging ring: 256 KiB chunks of Upload memory, filled front to back across submissions;
43// a full chunk is reused once the GPU has passed the last submission that reads from it (two
44// are kept free, more go back).  An upload above half a chunk gets a buffer of its own (its size
45// rounded up to 64 KiB), reused by a later one that fits it without wasting half of it; once the GPU
46// is done with them only the largest free one stays, and only until a second after the last such
47// upload (Device::poll): a frame of small rectangles costs what they hold, not a full frame or a new
48// allocation, and a frame of many canvas tiles does not keep twice their bytes around afterwards.
49// Device lost: VK_ERROR_DEVICE_LOST from any call sets the device's lost flag; every later
50// call returns GpuError::DeviceLost (objects are still destroyed normally).
51// (G5d) The compute queue comes only when asked for (DeviceOptions; without it a device is what it was in 0.1.0: one
52// queue, every resource exclusive).  It has a timeline of its own (two queues signalling one timeline semaphore could reach its
53// values out of order); its SubmitIds carry COMPUTE_ID.  A submission waits for the other queue's values through
54// the timeline (submit_after, at all commands).  A dropped resource waits for the latest submission of both queues;
55// command slots come from a pool of each family.  Resources are shared between the families concurrently: every
56// buffer, and every texture that is no render target (render targets stay exclusive to the device's queue: render
57// passes run there only, and some GPUs compress exclusive targets) -- no ownership transfers in the caller's code.
58// Pending uploads run on the device's queue: a compute submission flushes them first and waits for them.
59
60use alloc::sync::Arc;
61use alloc::vec::Vec;
62use core::ffi::c_void;
63use core::sync::atomic::{AtomicBool, AtomicU64, Ordering};
64
65use rt::sync::SpinLock;
66
67use crate::vk_ffi as vk;
68use crate::vk_inst::{Adapter, InstShared, err};
69use crate::vk_mem::{Alloc, Allocator};
70use crate::{AdapterInfo, DataLayout, DeviceDesc, DeviceOptions, Features, GpuError, Layout, Level, Limits, MemoryKind, Pod, Result,
71            SubmitId, TextureRegion};
72
73/// what waits for the GPU before it is destroyed
74pub(crate) enum Garbage {
75    Buffer(vk::Handle, Alloc),
76    Image(vk::Handle, Option<Alloc>),
77    View(vk::Handle),
78    Sampler(vk::Handle),
79    Shader(vk::Handle),
80    SetLayout(vk::Handle),
81    PipeLayout(vk::Handle),
82    Pipeline(vk::Handle),
83    Set(vk::Handle, vk::Handle),
84    Pool(vk::Handle),
85    Query(vk::Handle),
86    #[cfg_attr(jfgui_glibc, allow(dead_code))] // (vk_swap.rs)
87    Semaphore(vk::Handle),
88    /// a swapchain and its surface, kept until the swapchain is gone (Vulkan: a surface outlives
89    /// its swapchains; the Swapchain's own surface went first when it was dropped)
90    #[cfg_attr(jfgui_glibc, allow(dead_code))]
91    Swapchain(vk::Handle, crate::vk_swap::Surface),
92    #[cfg_attr(not(jfgui_glibc), allow(dead_code))] // (vk_dmabuf.rs: an image's dedicated allocation)
93    Memory(vk::Handle),
94}
95
96/// a command pool with its one command buffer (of the compute queue's family, or the device queue's)
97pub(crate) struct Slot {
98    pub pool: vk::Handle,
99    pub cb: vk::CommandBuffer,
100    pub compute: bool,
101}
102
103/// (G5d) the bit of a SubmitId of the compute queue (its timeline's value below it)
104pub(crate) const COMPUTE_ID: u64 = 1 << 63;
105
106/// (G5d) the compute queue: its family, its timeline, what was submitted and is known done
107pub(crate) struct Lane {
108    pub queue: vk::Queue,
109    pub family: u32,
110    pub timeline: vk::Handle,
111    pub ts_bits: u32,
112    submitted: AtomicU64,
113    completed: AtomicU64,
114    qlock: SpinLock<()>,
115}
116
117/// a buffer of the staging ring
118struct Chunk {
119    buf: vk::Handle,
120    a: Alloc,
121    used: u64, // bytes used, front to back
122    big: bool, // one upload's own buffer (above half a chunk), not one of the ring
123}
124
125/// the pending staged uploads: the command buffer, the chunks full since the last submission
126/// that it reads from
127struct Upload {
128    slot: Slot,
129    retired: Vec<Chunk>,
130    /// its number (State::up_gen when it was opened)
131    num: u64,
132}
133
134/// the staging ring
135#[derive(Default)]
136struct Ring {
137    cur: Option<Chunk>, // the chunk being filled (what is behind `used` stays free across submissions)
138    cur_value: u64,     // the last submission that reads from it (0: none)
139    cur_open: bool,     // the open upload command buffer reads from it
140    busy: Vec<(u64, Chunk)>, // retired: free once the GPU reached the value
141    free: Vec<Chunk>,
142    big_at: u64,        // plat::time_us of the last upload above half a chunk
143    big_size: u64,      // its bytes
144}
145
146pub(crate) struct State {
147    pub mem: Allocator,
148    /// (the device queue's value, the compute queue's)
149    garbage: Vec<(u64, u64, Garbage)>,
150    free: Vec<Slot>,
151    /// (G5d) free slots of the compute queue's family
152    cfree: Vec<Slot>,
153    /// (a SubmitId's value: COMPUTE_ID for the compute queue)
154    busy: Vec<(u64, Slot)>,
155    pools: Vec<vk::Handle>, // descriptor pools of the bind groups (the last one is filled)
156    upload: Option<Upload>,
157    /// the number of the last upload opened
158    up_gen: u64,
159    /// the numbers of the uploads submit_on took whose submissions are not in `submitted` yet
160    in_flight: Vec<u64>,
161    /// buffers and images an open or taken upload may name, with the newest such upload's
162    /// number: they become garbage of the then reached `submitted` once every upload up to it
163    /// is submitted (another thread may take the upload and submit it after a submission of
164    /// its own that does not carry it; "the next submission" was too early)
165    pending: Vec<(u64, u64, Garbage)>,
166    ring: Ring,
167}
168
169/// a chunk of the staging ring
170const CHUNK: u64 = 256 << 10;
171/// a large chunk stays while large uploads need at least this part of it
172const BIG_KEEP_RATIO: u64 = 8;
173/// free chunks kept beyond the one being filled
174const CHUNKS_FREE: usize = 2;
175/// an upload above half a chunk keeps its buffer this long after the last one (us)
176const BIG_KEEP_US: u64 = 1_000_000;
177
178pub(crate) struct Shared {
179    pub inst: Arc<InstShared>,
180    pub pd: vk::PhysicalDevice,
181    pub dev: vk::Device,
182    pub f: vk::DeviceFns,
183    pub queue: vk::Queue,
184    pub family: u32,
185    pub timeline: vk::Handle,
186    pub info: AdapterInfo,
187    pub features: Features,
188    pub limits: Limits,
189    pub level: Level,
190    pub raw: vk::PhysicalDeviceLimits,
191    pub ts_mask: u64,
192    #[cfg_attr(jfgui_glibc, allow(dead_code))] // (vk_swap.rs)
193    pub swapchain: bool,
194    /// images for a window go to VK_QUEUE_FAMILY_FOREIGN_EXT (vk_dmabuf.rs)
195    #[cfg_attr(not(jfgui_glibc), allow(dead_code))]
196    pub queue_foreign: bool,
197    /// the first timestamp tick read on the device: Timestamps::read_ms counts from it
198    pub ts_base: AtomicU64,
199    /// vkResetQueryPool from the host (hostQueryReset enabled)
200    pub host_query_reset: bool,
201    /// maintenance4 enabled (Vulkan 1.3): shaders may set their workgroup size with LocalSizeId
202    pub maintenance4: bool,
203    /// (G5d) the compute queue
204    pub lane: Option<Lane>,
205    lost: AtomicBool,
206    submitted: AtomicU64,
207    completed: AtomicU64,
208    qlock: SpinLock<()>,
209    pub st: SpinLock<State>,
210}
211
212/// a logical GPU device: creates resources, records commands, owns the queue
213#[derive(Clone)]
214pub struct Device {
215    pub(crate) sh: Arc<Shared>,
216    queue: Queue,
217    compute: Option<ComputeQueue>,
218}
219
220/// (G5d) a queue of its own for compute shaders and copies, beside the device's queue (Device::compute_queue): its
221/// encoders record no render passes, its submissions run in parallel with the device queue's unless one waits for the
222/// other (submit_after)
223#[derive(Clone)]
224pub struct ComputeQueue {
225    pub(crate) sh: Arc<Shared>,
226}
227
228/// the device's queue (graphics, compute, copies, presentation)
229#[derive(Clone)]
230pub struct Queue {
231    pub(crate) sh: Arc<Shared>,
232}
233
234// features enabled when present (indices into the VkBool32 arrays)
235const E10: &[usize] = &[
236    vk::F10_FULL_DRAW_INDEX_UINT32,
237    vk::F10_IMAGE_CUBE_ARRAY,
238    vk::F10_INDEPENDENT_BLEND,
239    vk::F10_GEOMETRY_SHADER,
240    vk::F10_SAMPLE_RATE_SHADING,
241    vk::F10_DUAL_SRC_BLEND,
242    vk::F10_MULTI_DRAW_INDIRECT,
243    vk::F10_DRAW_INDIRECT_FIRST_INSTANCE,
244    vk::F10_DEPTH_CLAMP,
245    vk::F10_FILL_MODE_NON_SOLID,
246    vk::F10_SAMPLER_ANISOTROPY,
247    vk::F10_TEXTURE_COMPRESSION_BC,
248    vk::F10_VERTEX_PIPELINE_STORES_AND_ATOMICS,
249    vk::F10_FRAGMENT_STORES_AND_ATOMICS,
250    vk::F10_SHADER_STORAGE_IMAGE_EXTENDED_FORMATS,
251    vk::F10_SHADER_STORAGE_IMAGE_READ_WITHOUT_FORMAT,
252    vk::F10_SHADER_STORAGE_IMAGE_WRITE_WITHOUT_FORMAT,
253    vk::F10_SHADER_UNIFORM_BUFFER_ARRAY_DYNAMIC_INDEXING,
254    vk::F10_SHADER_SAMPLED_IMAGE_ARRAY_DYNAMIC_INDEXING,
255    vk::F10_SHADER_STORAGE_BUFFER_ARRAY_DYNAMIC_INDEXING,
256    vk::F10_SHADER_STORAGE_IMAGE_ARRAY_DYNAMIC_INDEXING,
257    vk::F10_SHADER_CLIP_DISTANCE,
258    vk::F10_SHADER_FLOAT64,
259    vk::F10_SHADER_INT64,
260    vk::F10_SHADER_INT16,
261];
262const E11: &[usize] = &[
263    vk::F11_STORAGE_BUFFER_16BIT_ACCESS,
264    vk::F11_UNIFORM_AND_STORAGE_BUFFER_16BIT_ACCESS,
265    vk::F11_STORAGE_PUSH_CONSTANT16,
266    vk::F11_SHADER_DRAW_PARAMETERS,
267];
268const E12: &[usize] = &[
269    vk::F12_STORAGE_BUFFER_8BIT_ACCESS,
270    vk::F12_SHADER_FLOAT16,
271    vk::F12_SHADER_INT8,
272    vk::F12_SCALAR_BLOCK_LAYOUT,
273    vk::F12_UNIFORM_BUFFER_STANDARD_LAYOUT,
274    vk::F12_SHADER_SUBGROUP_EXTENDED_TYPES,
275    vk::F12_HOST_QUERY_RESET,
276    vk::F12_TIMELINE_SEMAPHORE,
277    vk::F12_BUFFER_DEVICE_ADDRESS,
278    vk::F12_VULKAN_MEMORY_MODEL,
279    vk::F12_VULKAN_MEMORY_MODEL_DEVICE_SCOPE,
280];
281const E12_VOLL: &[usize] = &[
282    vk::F12_DRAW_INDIRECT_COUNT,
283    vk::F12_DESCRIPTOR_INDEXING,
284    vk::F12_SHADER_SAMPLED_IMAGE_ARRAY_NON_UNIFORM_INDEXING,
285    vk::F12_SHADER_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING,
286    vk::F12_SHADER_STORAGE_IMAGE_ARRAY_NON_UNIFORM_INDEXING,
287    vk::F12_DESCRIPTOR_BINDING_SAMPLED_IMAGE_UPDATE_AFTER_BIND,
288    vk::F12_DESCRIPTOR_BINDING_STORAGE_IMAGE_UPDATE_AFTER_BIND,
289    vk::F12_DESCRIPTOR_BINDING_STORAGE_BUFFER_UPDATE_AFTER_BIND,
290    vk::F12_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING,
291    vk::F12_DESCRIPTOR_BINDING_PARTIALLY_BOUND,
292    vk::F12_RUNTIME_DESCRIPTOR_ARRAY,
293];
294const E13: &[usize] = &[
295    vk::F13_SHADER_DEMOTE_TO_HELPER_INVOCATION,
296    vk::F13_SUBGROUP_SIZE_CONTROL,
297    vk::F13_SYNCHRONIZATION2,
298    vk::F13_DYNAMIC_RENDERING,
299    vk::F13_MAINTENANCE4,
300];
301
302fn pick<const N: usize>(have: &[u32; N], want: &[usize]) -> [u32; N] {
303    let mut out = [0u32; N];
304    for &i in want {
305        out[i] = have[i];
306    }
307    out
308}
309
310impl Adapter {
311    /// a device of this adapter (level: the highest up to desc.max_level), with one queue
312    pub fn create_device(&self, desc: &DeviceDesc) -> Result<Device> {
313        self.create_device_with(desc, &DeviceOptions::DEFAULT)
314    }
315
316    /// (G5d) a device of this adapter with options: a compute queue of its own (Device::compute_queue) where the
317    /// adapter has a family without graphics and jfgui_GPU_COMPUTE is not 0
318    pub fn create_device_with(&self, desc: &DeviceDesc, opts: &DeviceOptions) -> Result<Device> {
319        if let Some(why) = self.info.missing {
320            return Err(GpuError::Unsupported(why));
321        }
322        let inst = &self.inst;
323        let level = if self.voll && desc.max_level == Level::Voll { Level::Voll } else { Level::Basis };
324        let voll = level == Level::Voll;
325        let v12 = self.api >= vk::API_VERSION_1_2;
326        let v13 = self.api >= vk::API_VERSION_1_3;
327        let mut e10 = pick(&self.f10, E10);
328        if !voll {
329            e10[vk::F10_MULTI_DRAW_INDIRECT] = 0;
330        }
331        let e11 = pick(&self.f11, E11);
332        let mut e12 = pick(&self.f12, E12);
333        // with the Vulkan memory model on, Device-scope atomics (any shader's, also under the
334        // GLSL450 model) need its device scope (VUID-RuntimeSpirv-vulkanMemoryModel-06265)
335        if e12[vk::F12_VULKAN_MEMORY_MODEL_DEVICE_SCOPE] == 0 {
336            e12[vk::F12_VULKAN_MEMORY_MODEL] = 0;
337        }
338        if voll {
339            for &i in E12_VOLL {
340                e12[i] = self.f12[i];
341            }
342        }
343        let e13 = pick(&self.f13, E13);
344        let mut f13: vk::PhysicalDeviceVulkan13Features = vk::Zero::zero();
345        f13.s_type = vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES;
346        f13.f = e13;
347        let mut f12: vk::PhysicalDeviceVulkan12Features = vk::Zero::zero();
348        f12.s_type = vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES;
349        f12.f = e12;
350        let mut f11: vk::PhysicalDeviceVulkan11Features = vk::Zero::zero();
351        f11.s_type = vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES;
352        f11.f = e11;
353        let mut dynr: vk::PhysicalDeviceOneFeature = vk::Zero::zero();
354        dynr.s_type = vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_DYNAMIC_RENDERING_FEATURES;
355        dynr.f = 1;
356        let mut tl: vk::PhysicalDeviceOneFeature = vk::Zero::zero();
357        tl.s_type = vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES;
358        tl.f = 1;
359        let mut f2: vk::PhysicalDeviceFeatures2 = vk::Zero::zero();
360        f2.s_type = vk::STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2;
361        f2.f = e10;
362        let mut names: Vec<*const u8> = Vec::new();
363        // the chain is linked from its tail: no structure is written after a pointer to it exists
364        if v12 {
365            if v13 {
366                f12.p_next = &mut f13 as *mut _ as *mut c_void;
367            } else {
368                f12.p_next = &mut dynr as *mut _ as *mut c_void;
369                names.push(b"VK_KHR_dynamic_rendering\0".as_ptr());
370            }
371            f11.p_next = &mut f12 as *mut _ as *mut c_void;
372            f2.p_next = &mut f11 as *mut _ as *mut c_void;
373        } else {
374            // Vulkan 1.1: the extensions and their dependencies
375            tl.p_next = &mut dynr as *mut _ as *mut c_void;
376            f2.p_next = &mut tl as *mut _ as *mut c_void;
377            names.push(b"VK_KHR_timeline_semaphore\0".as_ptr());
378            names.push(b"VK_KHR_create_renderpass2\0".as_ptr());
379            names.push(b"VK_KHR_depth_stencil_resolve\0".as_ptr());
380            names.push(b"VK_KHR_dynamic_rendering\0".as_ptr());
381        }
382        let swapchain = self.exts.swapchain;
383        if swapchain {
384            names.push(b"VK_KHR_swapchain\0".as_ptr());
385        }
386        let dmabuf = self.exts.dmabuf;
387        if dmabuf {
388            names.push(b"VK_KHR_external_memory_fd\0".as_ptr());
389            names.push(b"VK_EXT_external_memory_dma_buf\0".as_ptr());
390            names.push(b"VK_EXT_image_drm_format_modifier\0".as_ptr());
391            if !v12 {
392                names.push(b"VK_KHR_image_format_list\0".as_ptr());
393            }
394        }
395        let queue_foreign = dmabuf && self.exts.queue_foreign;
396        if queue_foreign {
397            names.push(b"VK_EXT_queue_family_foreign\0".as_ptr());
398        }
399        let prio = 1.0f32;
400        let qi = vk::DeviceQueueCreateInfo {
401            s_type: vk::STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
402            queue_family_index: self.family,
403            queue_count: 1,
404            p_queue_priorities: &prio,
405            ..vk::Zero::zero()
406        };
407        // (G5d) the compute queue: a family of its own when asked for, unless jfgui_GPU_COMPUTE=0
408        let off = plat::env("jfgui_GPU_COMPUTE").is_some_and(|v| v == "0" || v.eq_ignore_ascii_case("off"));
409        let cfam = self.compute_family.filter(|_| opts.compute_queue && !off);
410        let qis = [qi, vk::DeviceQueueCreateInfo { queue_family_index: cfam.map_or(0, |c| c.0), ..qi }];
411        let info = vk::DeviceCreateInfo {
412            s_type: vk::STRUCTURE_TYPE_DEVICE_CREATE_INFO,
413            p_next: &f2 as *const _ as *const c_void,
414            queue_create_info_count: 1 + cfam.is_some() as u32,
415            p_queue_create_infos: qis.as_ptr(),
416            enabled_extension_count: names.len() as u32,
417            pp_enabled_extension_names: names.as_ptr(),
418            ..vk::Zero::zero()
419        };
420        let mut dev: vk::Device = 0;
421        // SAFETY: the chain and the arrays live until the call returns.
422        let r = unsafe { (inst.f.create_device)(self.pd, &info, core::ptr::null(), &mut dev) };
423        if r != vk::SUCCESS {
424            return Err(err(r));
425        }
426        let gdpa = inst.f.get_device_proc_addr;
427        // SAFETY: names are NUL-terminated; dev is the device just created.
428        let f = match vk::DeviceFns::load(&|n| unsafe { gdpa(dev, n.as_ptr()) }) {
429            Ok(f) => f,
430            Err(name) => {
431                // SAFETY: vkDestroyDevice of the fresh device (nothing created from it).
432                let d = unsafe { gdpa(dev, b"vkDestroyDevice\0".as_ptr()) };
433                if d != 0 {
434                    // SAFETY: vkDestroyDevice's prototype.
435                    unsafe {
436                        core::mem::transmute::<usize, unsafe extern "system" fn(vk::Device, *const c_void)>(d)(
437                            dev,
438                            core::ptr::null(),
439                        )
440                    };
441                }
442                return Err(GpuError::Unsupported(name));
443            }
444        };
445        let mut queue: vk::Queue = 0;
446        // SAFETY: family / index 0 were requested above.
447        unsafe { (f.get_device_queue)(dev, self.family, 0, &mut queue) };
448        let ti = vk::SemaphoreTypeCreateInfo {
449            s_type: vk::STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO,
450            semaphore_type: vk::SEMAPHORE_TYPE_TIMELINE,
451            initial_value: 0,
452            ..vk::Zero::zero()
453        };
454        let si = vk::SemaphoreCreateInfo {
455            s_type: vk::STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO,
456            p_next: &ti as *const _ as *const c_void,
457            flags: 0,
458        };
459        let mut timeline = 0;
460        // SAFETY: valid create info.
461        let r = unsafe { (f.create_semaphore)(dev, &si, core::ptr::null(), &mut timeline) };
462        if r != vk::SUCCESS {
463            // SAFETY: nothing else was created from the device.
464            unsafe { (f.destroy_device)(dev, core::ptr::null()) };
465            return Err(err(r));
466        }
467        let mut lane = None;
468        if let Some((family, ts_bits)) = cfam {
469            let mut cq: vk::Queue = 0;
470            let mut ct = 0;
471            // SAFETY: the family / index 0 requested above; a valid create info.
472            let r = unsafe {
473                (f.get_device_queue)(dev, family, 0, &mut cq);
474                (f.create_semaphore)(dev, &si, core::ptr::null(), &mut ct)
475            };
476            if r != vk::SUCCESS {
477                // SAFETY: only the timeline was created from the device.
478                unsafe {
479                    (f.destroy_semaphore)(dev, timeline, core::ptr::null());
480                    (f.destroy_device)(dev, core::ptr::null());
481                }
482                return Err(err(r));
483            }
484            lane = Some(Lane { queue: cq, family, timeline: ct, ts_bits, submitted: AtomicU64::new(0), completed: AtomicU64::new(0), qlock: SpinLock::new(()) });
485        }
486        let mut features = self.features;
487        if !voll {
488            features.bindless = false;
489            features.draw_indirect_count = false;
490            features.multi_draw_indirect = false;
491        }
492        let mut limits = self.limits;
493        if !voll {
494            limits.max_bindless_textures = 0;
495            limits.max_bindless_samplers = 0;
496            limits.max_bindless_buffers = 0;
497            limits.max_bindless_storage_textures = 0;
498        }
499        let ts_mask = match self.ts_bits {
500            0 => 0,
501            64.. => !0,
502            b => (1u64 << b) - 1,
503        };
504        let sh = Arc::new(Shared {
505            inst: inst.clone(),
506            pd: self.pd,
507            dev,
508            f,
509            queue,
510            family: self.family,
511            timeline,
512            info: self.info.clone(),
513            features,
514            limits,
515            level,
516            raw: self.raw,
517            ts_mask,
518            swapchain,
519            queue_foreign,
520            ts_base: AtomicU64::new(0),
521            host_query_reset: v12 && e12[vk::F12_HOST_QUERY_RESET] != 0,
522            maintenance4: v13 && e13[vk::F13_MAINTENANCE4] != 0,
523            lane,
524            lost: AtomicBool::new(false),
525            submitted: AtomicU64::new(0),
526            completed: AtomicU64::new(0),
527            qlock: SpinLock::new(()),
528            st: SpinLock::new(State {
529                mem: Allocator::new(self.mem),
530                garbage: Vec::new(),
531                free: Vec::new(),
532                cfree: Vec::new(),
533                busy: Vec::new(),
534                pools: Vec::new(),
535                upload: None,
536                up_gen: 0,
537                in_flight: Vec::new(),
538                pending: Vec::new(),
539                ring: Ring::default(),
540            }),
541        });
542        let compute = sh.lane.as_ref().map(|_| ComputeQueue { sh: sh.clone() });
543        Ok(Device { queue: Queue { sh: sh.clone() }, compute, sh })
544    }
545}
546
547impl Shared {
548    /// Err(DeviceLost) once the device is lost
549    #[inline]
550    pub fn check(&self) -> Result<()> {
551        if self.lost.load(Ordering::Relaxed) { Err(GpuError::DeviceLost) } else { Ok(()) }
552    }
553
554    /// a VkResult as Result (DEVICE_LOST marks the device)
555    pub fn vk(&self, r: vk::VkResult) -> Result<()> {
556        if r == vk::SUCCESS {
557            return Ok(());
558        }
559        if r == vk::ERROR_DEVICE_LOST {
560            self.lost.store(true, Ordering::Relaxed);
561        }
562        Err(err(r))
563    }
564
565    /// run f with the queue held (vkQueuePresentKHR and vkQueueSubmit need it alone)
566    #[cfg_attr(jfgui_glibc, allow(dead_code))]
567    pub fn with_queue<R>(&self, f: impl FnOnce(vk::Queue) -> R) -> R {
568        let _q = self.qlock.lock();
569        f(self.queue)
570    }
571
572    /// wait until the queue has finished everything, presents included (vkQueueWaitIdle;
573    /// also on a lost device, where it returns at once)
574    #[cfg_attr(jfgui_glibc, allow(dead_code))]
575    pub fn queue_idle(&self) -> Result<()> {
576        // the value is read while the queue is held: nothing is submitted until the wait ends
577        // SAFETY: the queue is held while the driver waits on it.
578        let (r, v) = self.with_queue(|q| (unsafe { (self.f.queue_wait_idle)(q) }, self.submitted()));
579        self.vk(r)?;
580        self.completed.fetch_max(v, Ordering::AcqRel);
581        let mut st = self.st.lock();
582        self.collect(&mut st);
583        Ok(())
584    }
585
586    pub fn mark_lost(&self) {
587        self.lost.store(true, Ordering::Relaxed);
588    }
589
590    pub fn submitted(&self) -> u64 {
591        self.submitted.load(Ordering::Acquire)
592    }
593
594    /// (G5d) the compute queue's last submitted value (0 without one)
595    fn lane_submitted(&self) -> u64 {
596        self.lane.as_ref().map_or(0, |l| l.submitted.load(Ordering::Acquire))
597    }
598
599    /// (G5d) the compute queue's value the GPU has reached (asks the driver; 0 without one)
600    fn lane_refresh(&self) -> u64 {
601        let Some(l) = &self.lane else { return 0 };
602        // (nothing pending: no call; a device that never uses the queue never asks its timeline)
603        let done = l.completed.load(Ordering::Acquire);
604        if l.submitted.load(Ordering::Acquire) <= done {
605            return done;
606        }
607        let mut v = 0u64;
608        // SAFETY: the compute queue's timeline semaphore.
609        let r = unsafe { (self.f.get_semaphore_counter_value)(self.dev, l.timeline, &mut v) };
610        if r != vk::SUCCESS {
611            if r == vk::ERROR_DEVICE_LOST {
612                self.lost.store(true, Ordering::Relaxed);
613            }
614            return l.completed.load(Ordering::Acquire);
615        }
616        l.completed.fetch_max(v, Ordering::AcqRel);
617        v
618    }
619
620    /// the timeline value the GPU has reached (asks the driver)
621    pub fn refresh(&self) -> u64 {
622        let mut v = 0u64;
623        // SAFETY: the device's timeline semaphore.
624        let r = unsafe { (self.f.get_semaphore_counter_value)(self.dev, self.timeline, &mut v) };
625        if r != vk::SUCCESS {
626            if r == vk::ERROR_DEVICE_LOST {
627                self.lost.store(true, Ordering::Relaxed);
628            }
629            return self.completed.load(Ordering::Acquire);
630        }
631        self.completed.fetch_max(v, Ordering::AcqRel);
632        v
633    }
634
635    /// destroy g once the GPU has finished every submission made so far; a buffer or image also
636    /// the open upload buffer, whose copies may name it (a texture written and dropped before the
637    /// next submit).  Nothing else waits for that: a swapchain must go before its surface, which
638    /// its drop releases right after this
639    pub fn defer(&self, g: Garbage) {
640        let mut st = self.st.lock();
641        // (G5d) and the compute queue's latest submission
642        let vc = self.lane_submitted();
643        // an open upload, or one another thread took to submit, may name a buffer or image, or
644        // reset a query pool (a device without hostQueryReset: Timestamps::new records the reset
645        // there): it waits until every upload up to the newest of them is submitted
646        // (State::pending)
647        if matches!(g, Garbage::Buffer(..) | Garbage::Image(..) | Garbage::Query(..)) && !self.lost.load(Ordering::Relaxed) {
648            if let Some(num) = st.upload.as_ref().map(|u| u.num).or_else(|| st.in_flight.iter().max().copied()) {
649                st.pending.push((num, vc, g));
650                return;
651            }
652        }
653        let v = self.submitted();
654        let lane_done = self.lane.as_ref().is_none_or(|l| vc <= l.completed.load(Ordering::Acquire));
655        if (v <= self.completed.load(Ordering::Acquire) && lane_done) || self.lost.load(Ordering::Relaxed) {
656            self.destroy(&mut st, g);
657        } else {
658            st.garbage.push((v, vc, g));
659        }
660    }
661
662    /// the pending buffers and images whose uploads are all in `submitted` now (no older or equal
663    /// upload is open or taken and unsubmitted) become garbage of its value
664    fn settle(&self, st: &mut State) {
665        if st.pending.is_empty() {
666            return;
667        }
668        let lost = self.lost.load(Ordering::Relaxed);
669        let oldest = st.in_flight.iter().copied().chain(st.upload.as_ref().map(|u| u.num)).min();
670        let v = self.submitted();
671        let mut i = 0;
672        while i < st.pending.len() {
673            if lost || oldest.is_none_or(|o| st.pending[i].0 < o) {
674                let (_, vc, g) = st.pending.swap_remove(i);
675                st.garbage.push((v, vc, g));
676            } else {
677                i += 1;
678            }
679        }
680    }
681
682    fn destroy(&self, st: &mut State, g: Garbage) {
683        let (f, d, n) = (&self.f, self.dev, core::ptr::null());
684        // SAFETY: the GPU no longer uses the object (its timeline value is reached, or no
685        // submission is pending, or the device is lost); each handle is destroyed once.
686        unsafe {
687            match g {
688                Garbage::Buffer(h, a) => {
689                    (f.destroy_buffer)(d, h, n);
690                    st.mem.free(f, d, &a);
691                }
692                Garbage::Image(h, a) => {
693                    (f.destroy_image)(d, h, n);
694                    if let Some(a) = a {
695                        st.mem.free(f, d, &a);
696                    }
697                }
698                Garbage::View(h) => (f.destroy_image_view)(d, h, n),
699                Garbage::Sampler(h) => (f.destroy_sampler)(d, h, n),
700                Garbage::Shader(h) => (f.destroy_shader_module)(d, h, n),
701                Garbage::SetLayout(h) => (f.destroy_descriptor_set_layout)(d, h, n),
702                Garbage::PipeLayout(h) => (f.destroy_pipeline_layout)(d, h, n),
703                Garbage::Pipeline(h) => (f.destroy_pipeline)(d, h, n),
704                Garbage::Set(pool, set) => {
705                    (f.free_descriptor_sets)(d, pool, 1, &set);
706                }
707                Garbage::Pool(h) => (f.destroy_descriptor_pool)(d, h, n),
708                Garbage::Query(h) => (f.destroy_query_pool)(d, h, n),
709                Garbage::Semaphore(h) => (f.destroy_semaphore)(d, h, n),
710                Garbage::Swapchain(h, surface) => {
711                    if let Some(ds) = f.destroy_swapchain_khr {
712                        ds(d, h, n);
713                    }
714                    drop(surface); // only now
715                }
716                Garbage::Memory(h) => (f.free_memory)(d, h, n),
717            }
718        }
719    }
720
721    /// free the garbage and the command slots whose submissions completed
722    fn collect(&self, st: &mut State) {
723        if st.garbage.is_empty() && st.busy.is_empty() && st.ring.busy.is_empty() && st.ring.free.is_empty() {
724            return;
725        }
726        let lost = self.lost.load(Ordering::Relaxed);
727        let done = if lost { u64::MAX } else { self.refresh() };
728        let done_c = if lost { u64::MAX } else { self.lane_refresh() };
729        let mut i = 0;
730        while i < st.ring.busy.len() {
731            if st.ring.busy[i].0 <= done {
732                let (_, mut c) = st.ring.busy.swap_remove(i);
733                c.used = 0;
734                st.ring.free.push(c);
735            } else {
736                i += 1;
737            }
738        }
739        self.ring_trim(st);
740        let mut i = 0;
741        while i < st.busy.len() {
742            let v = st.busy[i].0;
743            let finished = if v & COMPUTE_ID != 0 { v & !COMPUTE_ID <= done_c } else { v <= done };
744            if finished {
745                let (_, s) = st.busy.swap_remove(i);
746                // SAFETY: the pool's command buffer finished executing.
747                unsafe { (self.f.reset_command_pool)(self.dev, s.pool, 0) };
748                if s.compute { st.cfree.push(s) } else { st.free.push(s) }
749            } else {
750                i += 1;
751            }
752        }
753        let mut i = 0;
754        while i < st.garbage.len() {
755            if st.garbage[i].0 <= done && st.garbage[i].1 <= done_c {
756                let (_, _, g) = st.garbage.swap_remove(i);
757                self.destroy(st, g);
758            } else {
759                i += 1;
760            }
761        }
762    }
763
764    /// a command buffer slot (reused or new), begun for one submission
765    #[cfg_attr(not(jfgui_glibc), allow(dead_code))] // (vk_dmabuf.rs)
766    pub fn take_slot(&self) -> Result<Slot> {
767        self.take_slot_for(false)
768    }
769
770    /// (G5d) a slot of the compute queue's family (compute) or the device queue's
771    pub fn take_slot_for(&self, compute: bool) -> Result<Slot> {
772        self.check()?;
773        if compute && self.lane.is_none() {
774            return Err(GpuError::Unsupported("a compute queue"));
775        }
776        let slot = {
777            let mut st = self.st.lock();
778            let empty = if compute { st.cfree.is_empty() } else { st.free.is_empty() };
779            if empty {
780                self.collect(&mut st);
781            }
782            if compute { st.cfree.pop() } else { st.free.pop() }
783        };
784        let slot = match slot {
785            Some(s) => s,
786            None => self.new_slot(compute)?,
787        };
788        let bi = vk::CommandBufferBeginInfo {
789            s_type: vk::STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
790            flags: vk::COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
791            ..vk::Zero::zero()
792        };
793        // SAFETY: the slot's buffer is in the initial state (new or its pool reset).
794        let r = unsafe { (self.f.begin_command_buffer)(slot.cb, &bi) };
795        if let Err(e) = self.vk(r) {
796            self.give_slot(slot);
797            return Err(e);
798        }
799        Ok(slot)
800    }
801
802    fn new_slot(&self, compute: bool) -> Result<Slot> {
803        let family = match (&self.lane, compute) {
804            (Some(l), true) => l.family,
805            _ => self.family,
806        };
807        let pi = vk::CommandPoolCreateInfo {
808            s_type: vk::STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO,
809            flags: vk::COMMAND_POOL_CREATE_TRANSIENT_BIT,
810            queue_family_index: family,
811            ..vk::Zero::zero()
812        };
813        let mut pool = 0;
814        // SAFETY: valid create info.
815        self.vk(unsafe { (self.f.create_command_pool)(self.dev, &pi, core::ptr::null(), &mut pool) })?;
816        let ai = vk::CommandBufferAllocateInfo {
817            s_type: vk::STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO,
818            command_pool: pool,
819            level: vk::COMMAND_BUFFER_LEVEL_PRIMARY,
820            command_buffer_count: 1,
821            ..vk::Zero::zero()
822        };
823        let mut cb = 0;
824        // SAFETY: one buffer from the new pool.
825        let r = unsafe { (self.f.allocate_command_buffers)(self.dev, &ai, &mut cb) };
826        if let Err(e) = self.vk(r) {
827            // SAFETY: the pool is unused.
828            unsafe { (self.f.destroy_command_pool)(self.dev, pool, core::ptr::null()) };
829            return Err(e);
830        }
831        Ok(Slot { pool, cb, compute })
832    }
833
834    /// a slot that was never submitted: reset, back to the free list
835    pub fn give_slot(&self, s: Slot) {
836        // SAFETY: the buffer is not pending (never submitted).
837        unsafe { (self.f.reset_command_pool)(self.dev, s.pool, 0) };
838        let mut st = self.st.lock();
839        if s.compute { st.cfree.push(s) } else { st.free.push(s) }
840    }
841
842    /// (G5d) the families a resource is shared by (concurrently), when there is a compute queue
843    pub fn sharing(&self) -> Option<[u32; 2]> {
844        self.lane.as_ref().map(|l| [self.family, l.family])
845    }
846
847    /// the free chunks beyond what the ring keeps go back: ordinary ones above CHUNKS_FREE,
848    /// large ones a second after the last large upload (all but one of the largest at once -- a
849    /// frame of many tiles has as many buffers of one size; that one too when the last large
850    /// upload was far smaller: one big image's buffer does not stay around for the frames after it)
851    fn ring_trim(&self, st: &mut State) {
852        let now = plat::time_us();
853        let keep_big = now.saturating_sub(st.ring.big_at) < BIG_KEEP_US;
854        let largest = st.ring.free.iter().filter(|c| c.big).map(|c| c.a.size).max().unwrap_or(0);
855        let mut kept_big = false;
856        let mut small = 0;
857        let mut i = 0;
858        while i < st.ring.free.len() {
859            let c = &st.ring.free[i];
860            let size = c.a.size;
861            let keep = if c.big {
862                let k = !kept_big && keep_big && size == largest && size <= st.ring.big_size.saturating_mul(BIG_KEEP_RATIO).max(CHUNK * 2);
863                kept_big |= k;
864                k
865            } else {
866                small += 1;
867                small <= CHUNKS_FREE
868            };
869            if keep {
870                i += 1;
871            } else {
872                let c = st.ring.free.swap_remove(i);
873                self.destroy(st, Garbage::Buffer(c.buf, c.a));
874            }
875        }
876    }
877
878    /// a chunk of at least size bytes, reused or new (its `used` is 0): one of the ring (big =
879    /// false, size = CHUNK) or an upload's own buffer (big; a free one at most twice the size)
880    fn ring_chunk(&self, st: &mut State, size: u64, big: bool) -> Result<Chunk> {
881        let top = size.saturating_mul(2);
882        let best = st.ring.free.iter().enumerate().filter(|(_, c)| c.big == big && c.a.size >= size && c.a.size <= top).min_by_key(|(_, c)| c.a.size).map(|(i, _)| i);
883        if let Some(i) = best {
884            return Ok(st.ring.free.swap_remove(i));
885        }
886        let (buf, a) = self.raw_buffer(st, size, vk::BUFFER_USAGE_TRANSFER_SRC_BIT, MemoryKind::Upload)?;
887        Ok(Chunk { buf, a, used: 0, big })
888    }
889
890    /// the upload command buffer (begun when there is none): it runs first in the next submit
891    pub fn upload_cb(&self, st: &mut State) -> Result<vk::CommandBuffer> {
892        self.stage(st, 0)?;
893        Ok(st.upload.as_ref().map_or(0, |u| u.slot.cb))
894    }
895
896    /// staging space of n bytes for the upload command buffer -> (buffer, offset, address)
897    /// (n = 0: only the command buffer)
898    fn stage(&self, st: &mut State, n: u64) -> Result<(vk::Handle, u64, usize)> {
899        if st.upload.is_none() {
900            // the upload buffer's slot: from the free list or new (the lock is held: no collect)
901            let slot = match st.free.pop() {
902                Some(s) => s,
903                None => self.new_slot(false)?,
904            };
905            let bi = vk::CommandBufferBeginInfo {
906                s_type: vk::STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
907                flags: vk::COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT,
908                ..vk::Zero::zero()
909            };
910            // SAFETY: a slot in the initial state.
911            let r = unsafe { (self.f.begin_command_buffer)(slot.cb, &bi) };
912            if let Err(e) = self.vk(r) {
913                st.free.push(slot);
914                return Err(e);
915            }
916            st.up_gen += 1;
917            st.upload = Some(Upload { slot, retired: Vec::new(), num: st.up_gen });
918        }
919        if n == 0 {
920            return Ok((0, 0, 0));
921        }
922        if n > CHUNK / 2 {
923            // a buffer of its own: free once the next submission is done
924            st.ring.big_at = plat::time_us();
925            st.ring.big_size = n;
926            let size = (n + 0xFFFF) & !0xFFFF;
927            let mut c = self.ring_chunk(st, size, true)?;
928            c.used = n;
929            let (buf, ptr) = (c.buf, c.a.ptr);
930            st.upload.as_mut().unwrap_or_else(|| unreachable!()).retired.push(c);
931            return Ok((buf, 0, ptr));
932        }
933        let room = st.ring.cur.as_ref().is_some_and(|c| c.used + n <= c.a.size);
934        if !room {
935            if let Some(c) = st.ring.cur.take() {
936                if st.ring.cur_open {
937                    st.upload.as_mut().unwrap_or_else(|| unreachable!()).retired.push(c);
938                } else {
939                    let v = st.ring.cur_value;
940                    st.ring.busy.push((v, c));
941                }
942            }
943            let c = self.ring_chunk(st, CHUNK, false)?;
944            st.ring.cur = Some(c);
945            st.ring.cur_open = false;
946        }
947        st.ring.cur_open = true;
948        let c = st.ring.cur.as_mut().unwrap_or_else(|| unreachable!());
949        let off = c.used;
950        c.used = (off + n + 15) & !15;
951        Ok((c.buf, off, c.a.ptr + off as usize))
952    }
953
954    /// a VkBuffer with memory of kind (bound) -> (buffer, allocation)
955    pub fn raw_buffer(&self, st: &mut State, size: u64, usage: u32, kind: MemoryKind) -> Result<(vk::Handle, Alloc)> {
956        // (G5d) every buffer is shared with the compute queue's family, if there is one
957        let fams = self.sharing();
958        let bi = vk::BufferCreateInfo {
959            s_type: vk::STRUCTURE_TYPE_BUFFER_CREATE_INFO,
960            size,
961            usage,
962            sharing_mode: if fams.is_some() { vk::SHARING_MODE_CONCURRENT } else { vk::SHARING_MODE_EXCLUSIVE },
963            queue_family_index_count: if fams.is_some() { 2 } else { 0 },
964            p_queue_family_indices: fams.as_ref().map_or(core::ptr::null(), |f| f.as_ptr()),
965            ..vk::Zero::zero()
966        };
967        let mut buf = 0;
968        // SAFETY: valid create info.
969        self.vk(unsafe { (self.f.create_buffer)(self.dev, &bi, core::ptr::null(), &mut buf) })?;
970        let mut req: vk::MemoryRequirements = vk::Zero::zero();
971        // SAFETY: the buffer just created.
972        unsafe { (self.f.get_buffer_memory_requirements)(self.dev, buf, &mut req) };
973        let a = match st.mem.alloc(&self.f, self.dev, &req, kind, true) {
974            Ok(a) => a,
975            Err(e) => {
976                // SAFETY: unbound, unused buffer.
977                unsafe { (self.f.destroy_buffer)(self.dev, buf, core::ptr::null()) };
978                return Err(e);
979            }
980        };
981        // SAFETY: the allocation satisfies the buffer's requirements.
982        let r = unsafe { (self.f.bind_buffer_memory)(self.dev, buf, a.mem, a.offset) };
983        if let Err(e) = self.vk(r) {
984            // SAFETY: as above.
985            unsafe { (self.f.destroy_buffer)(self.dev, buf, core::ptr::null()) };
986            st.mem.free(&self.f, self.dev, &a);
987            return Err(e);
988        }
989        Ok((buf, a))
990    }
991
992    /// submit command buffers (their slots), after the pending uploads; wait: a binary
993    /// semaphore and its stages, signal: a binary semaphore -> the timeline value
994    pub fn submit(&self, cbs: &[vk::CommandBuffer], slots: Vec<Slot>, wait: Option<(vk::Handle, u32)>,
995                  signal: Option<vk::Handle>) -> Result<u64> {
996        self.submit_on(false, cbs, slots, wait, &[], signal)
997    }
998
999    /// (G5d) the semaphore and value a SubmitId waits on; Invalid when it was not submitted yet
1000    fn wait_of(&self, id: u64) -> Result<(vk::Handle, u64)> {
1001        if id & COMPUTE_ID == 0 {
1002            return if id <= self.submitted() { Ok((self.timeline, id)) } else { Err(GpuError::Invalid("submit_after: a submission not made yet")) };
1003        }
1004        match &self.lane {
1005            Some(l) if id & !COMPUTE_ID <= l.submitted.load(Ordering::Acquire) => Ok((l.timeline, id & !COMPUTE_ID)),
1006            Some(_) => Err(GpuError::Invalid("submit_after: a submission not made yet")),
1007            None => Err(GpuError::Invalid("submit_after: an id of a compute queue the device does not have")),
1008        }
1009    }
1010
1011    /// submit on the device's queue (compute false: after the pending uploads) or on the compute queue (the pending
1012    /// uploads go first on the device's queue, and it waits for them); wait: a binary semaphore and its stages,
1013    /// after: SubmitIds of either queue it waits for (at all commands), signal: a binary semaphore -> the SubmitId
1014    /// (COMPUTE_ID on the compute queue)
1015    pub fn submit_on(&self, compute: bool, cbs: &[vk::CommandBuffer], slots: Vec<Slot>, wait: Option<(vk::Handle, u32)>, after: &[u64],
1016                     signal: Option<vk::Handle>) -> Result<u64> {
1017        let mut slots = slots;
1018        let fine = self.check().and_then(|_| {
1019            if slots.iter().any(|s| s.compute != compute) {
1020                return Err(GpuError::Invalid("submit: a command buffer of the other queue's family (Device::encoder / ComputeQueue::encoder)"));
1021            }
1022            if compute && (self.lane.is_none() || wait.is_some() || signal.is_some()) {
1023                return Err(GpuError::Invalid("submit: no compute queue, or a semaphore on it"));
1024            }
1025            Ok(())
1026        });
1027        let mut waits: Vec<(vk::Handle, u64)> = Vec::with_capacity(after.len() + 1);
1028        let fine = fine.and_then(|_| {
1029            for &id in after {
1030                waits.push(self.wait_of(id)?);
1031            }
1032            Ok(())
1033        });
1034        if let Err(e) = fine {
1035            for s in slots {
1036                self.give_slot(s);
1037            }
1038            return Err(e);
1039        }
1040        if compute {
1041            return self.submit_lane(cbs, slots, waits);
1042        }
1043        let up = {
1044            let mut st = self.st.lock();
1045            let u = st.upload.take();
1046            if let Some(u) = &u {
1047                st.in_flight.push(u.num); // (defer: until `submitted` holds its value)
1048            }
1049            u
1050        };
1051        let mut all: Vec<vk::CommandBuffer> = Vec::with_capacity(cbs.len() + 1);
1052        let mut chunks: Vec<Chunk> = Vec::new();
1053        let uploads = up.is_some();
1054        let num = up.as_ref().map_or(0, |u| u.num);
1055        // after `submitted` holds this submission's value (or it failed): under st's lock, so
1056        // defer sees one or the other
1057        let put_back = |me: &Self| {
1058            if uploads {
1059                let mut st = me.st.lock();
1060                st.in_flight.retain(|&g| g != num);
1061                me.settle(&mut st);
1062            }
1063        };
1064        if let Some(u) = up {
1065            let mb = vk::MemoryBarrier {
1066                s_type: vk::STRUCTURE_TYPE_MEMORY_BARRIER,
1067                src_access_mask: vk::ACCESS_TRANSFER_WRITE_BIT,
1068                dst_access_mask: vk::ACCESS_MEMORY_READ_BIT | vk::ACCESS_MEMORY_WRITE_BIT,
1069                ..vk::Zero::zero()
1070            };
1071            // SAFETY: the upload buffer is recording; its copies are done before what follows.
1072            unsafe {
1073                (self.f.cmd_pipeline_barrier)(u.slot.cb, vk::PIPELINE_STAGE_TRANSFER_BIT,
1074                    vk::PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 1, &mb, 0, core::ptr::null(), 0, core::ptr::null());
1075            }
1076            // SAFETY: as above.
1077            let r = unsafe { (self.f.end_command_buffer)(u.slot.cb) };
1078            all.push(u.slot.cb);
1079            slots.push(u.slot);
1080            chunks = u.retired;
1081            if let Err(e) = self.vk(r) {
1082                put_back(self);
1083                self.fail_submit(slots, chunks);
1084                return Err(e);
1085            }
1086        }
1087        all.extend_from_slice(cbs);
1088        // the binary semaphore (its value is ignored) and the timelines it waits for
1089        let mut ws: Vec<vk::Handle> = Vec::with_capacity(waits.len() + 1);
1090        let mut wv: Vec<u64> = Vec::with_capacity(waits.len() + 1);
1091        let mut wst: Vec<u32> = Vec::with_capacity(waits.len() + 1);
1092        if let Some((s, st)) = wait {
1093            ws.push(s);
1094            wv.push(0);
1095            wst.push(st);
1096        }
1097        for &(s, v) in &waits {
1098            ws.push(s);
1099            wv.push(v);
1100            wst.push(vk::PIPELINE_STAGE_ALL_COMMANDS_BIT);
1101        }
1102        let q = self.qlock.lock();
1103        let value = self.submitted.load(Ordering::Relaxed) + 1;
1104        let sems = [self.timeline, signal.unwrap_or(0)];
1105        let values = [value, 0];
1106        let nsig = 1 + signal.is_some() as u32;
1107        let tsi = vk::TimelineSemaphoreSubmitInfo {
1108            s_type: vk::STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO,
1109            wait_semaphore_value_count: wv.len() as u32,
1110            p_wait_semaphore_values: wv.as_ptr(),
1111            signal_semaphore_value_count: nsig,
1112            p_signal_semaphore_values: values.as_ptr(),
1113            ..vk::Zero::zero()
1114        };
1115        let si = vk::SubmitInfo {
1116            s_type: vk::STRUCTURE_TYPE_SUBMIT_INFO,
1117            p_next: &tsi as *const _ as *const c_void,
1118            wait_semaphore_count: ws.len() as u32,
1119            p_wait_semaphores: ws.as_ptr(),
1120            p_wait_dst_stage_mask: wst.as_ptr(),
1121            command_buffer_count: all.len() as u32,
1122            p_command_buffers: all.as_ptr(),
1123            signal_semaphore_count: nsig,
1124            p_signal_semaphores: sems.as_ptr(),
1125        };
1126        // SAFETY: every command buffer is executable; the queue is held (qlock).
1127        let r = unsafe { (self.f.queue_submit)(self.queue, 1, &si, 0) };
1128        if r == vk::SUCCESS {
1129            self.submitted.store(value, Ordering::Release);
1130        }
1131        drop(q);
1132        put_back(self);
1133        if let Err(e) = self.vk(r) {
1134            self.fail_submit(slots, chunks);
1135            return Err(e);
1136        }
1137        let mut st = self.st.lock();
1138        for s in slots {
1139            st.busy.push((value, s));
1140        }
1141        for c in chunks {
1142            st.ring.busy.push((value, c));
1143        }
1144        if uploads && st.ring.cur_open {
1145            st.ring.cur_value = value;
1146            st.ring.cur_open = false;
1147        }
1148        self.collect(&mut st);
1149        Ok(value)
1150    }
1151
1152    /// (G5d) a submission on the compute queue (checked by submit_on): the pending uploads first on the device's
1153    /// queue, waited for
1154    fn submit_lane(&self, cbs: &[vk::CommandBuffer], slots: Vec<Slot>, mut waits: Vec<(vk::Handle, u64)>) -> Result<u64> {
1155        let Some(l) = &self.lane else { return Err(GpuError::Invalid("no compute queue")) };
1156        if self.st.lock().upload.is_some() {
1157            match self.submit_on(false, &[], Vec::new(), None, &[], None) {
1158                Ok(v) => waits.push((self.timeline, v)),
1159                Err(e) => {
1160                    for s in slots {
1161                        self.give_slot(s);
1162                    }
1163                    return Err(e);
1164                }
1165            }
1166        }
1167        let wv: Vec<u64> = waits.iter().map(|w| w.1).collect();
1168        let ws: Vec<vk::Handle> = waits.iter().map(|w| w.0).collect();
1169        let wst: Vec<u32> = ws.iter().map(|_| vk::PIPELINE_STAGE_ALL_COMMANDS_BIT).collect();
1170        let q = l.qlock.lock();
1171        let value = l.submitted.load(Ordering::Relaxed) + 1;
1172        let tsi = vk::TimelineSemaphoreSubmitInfo {
1173            s_type: vk::STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO,
1174            wait_semaphore_value_count: wv.len() as u32,
1175            p_wait_semaphore_values: wv.as_ptr(),
1176            signal_semaphore_value_count: 1,
1177            p_signal_semaphore_values: &value,
1178            ..vk::Zero::zero()
1179        };
1180        let si = vk::SubmitInfo {
1181            s_type: vk::STRUCTURE_TYPE_SUBMIT_INFO,
1182            p_next: &tsi as *const _ as *const c_void,
1183            wait_semaphore_count: ws.len() as u32,
1184            p_wait_semaphores: ws.as_ptr(),
1185            p_wait_dst_stage_mask: wst.as_ptr(),
1186            command_buffer_count: cbs.len() as u32,
1187            p_command_buffers: cbs.as_ptr(),
1188            signal_semaphore_count: 1,
1189            p_signal_semaphores: &l.timeline,
1190        };
1191        // SAFETY: every command buffer is executable and of the compute family; the queue is held.
1192        let r = unsafe { (self.f.queue_submit)(l.queue, 1, &si, 0) };
1193        if r == vk::SUCCESS {
1194            l.submitted.store(value, Ordering::Release);
1195        }
1196        drop(q);
1197        if let Err(e) = self.vk(r) {
1198            for s in slots {
1199                self.give_slot(s);
1200            }
1201            return Err(e);
1202        }
1203        let mut st = self.st.lock();
1204        for s in slots {
1205            st.busy.push((value | COMPUTE_ID, s));
1206        }
1207        self.collect(&mut st);
1208        Ok(value | COMPUTE_ID)
1209    }
1210
1211    /// (G5d) wait for a SubmitId of either queue -> false on timeout
1212    pub fn wait_id(&self, id: u64, timeout_ns: u64) -> Result<bool> {
1213        if id & COMPUTE_ID == 0 {
1214            return self.wait_value(id, timeout_ns);
1215        }
1216        self.check()?;
1217        let Some(l) = &self.lane else { return Err(GpuError::Invalid("wait: an id of a compute queue the device does not have")) };
1218        let v = id & !COMPUTE_ID;
1219        if v <= l.completed.load(Ordering::Acquire) {
1220            return Ok(true);
1221        }
1222        if v > l.submitted.load(Ordering::Acquire) {
1223            return Err(GpuError::Invalid("wait: not submitted yet"));
1224        }
1225        let wi = vk::SemaphoreWaitInfo {
1226            s_type: vk::STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO,
1227            semaphore_count: 1,
1228            p_semaphores: &l.timeline,
1229            p_values: &v,
1230            ..vk::Zero::zero()
1231        };
1232        // SAFETY: the compute queue's timeline semaphore and a value already submitted.
1233        let r = unsafe { (self.f.wait_semaphores)(self.dev, &wi, timeout_ns) };
1234        if r == vk::TIMEOUT {
1235            return Ok(false);
1236        }
1237        self.vk(r)?;
1238        l.completed.fetch_max(v, Ordering::AcqRel);
1239        let mut st = self.st.lock();
1240        self.collect(&mut st);
1241        Ok(true)
1242    }
1243
1244    fn fail_submit(&self, slots: Vec<Slot>, chunks: Vec<Chunk>) {
1245        for s in slots {
1246            self.give_slot(s);
1247        }
1248        let mut st = self.st.lock();
1249        st.ring.cur_open = false; // its copies never ran
1250        for c in chunks {
1251            self.destroy(&mut st, Garbage::Buffer(c.buf, c.a));
1252        }
1253    }
1254
1255    /// wait until the timeline reaches v -> false on timeout
1256    pub fn wait_value(&self, v: u64, timeout_ns: u64) -> Result<bool> {
1257        self.check()?;
1258        if v <= self.completed.load(Ordering::Acquire) {
1259            return Ok(true);
1260        }
1261        if v > self.submitted() {
1262            return Err(GpuError::Invalid("wait: not submitted yet"));
1263        }
1264        let wi = vk::SemaphoreWaitInfo {
1265            s_type: vk::STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO,
1266            semaphore_count: 1,
1267            p_semaphores: &self.timeline,
1268            p_values: &v,
1269            ..vk::Zero::zero()
1270        };
1271        // SAFETY: the device's timeline semaphore and a value already submitted (or later).
1272        let r = unsafe { (self.f.wait_semaphores)(self.dev, &wi, timeout_ns) };
1273        if r == vk::TIMEOUT {
1274            return Ok(false);
1275        }
1276        self.vk(r)?;
1277        self.completed.fetch_max(v, Ordering::AcqRel);
1278        let mut st = self.st.lock();
1279        self.collect(&mut st);
1280        Ok(true)
1281    }
1282
1283    /// bind-group descriptor sets: a set of layout from the pools (a new pool when all are full)
1284    pub fn alloc_set(&self, layout: vk::Handle, needs: &[vk::DescriptorPoolSize]) -> Result<(vk::Handle, vk::Handle)> {
1285        let mut st = self.st.lock();
1286        let alloc = |pool: vk::Handle| {
1287            let ai = vk::DescriptorSetAllocateInfo {
1288                s_type: vk::STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
1289                descriptor_pool: pool,
1290                descriptor_set_count: 1,
1291                p_set_layouts: &layout,
1292                ..vk::Zero::zero()
1293            };
1294            let mut set = 0;
1295            // SAFETY: the pool belongs to this device; the state lock serialises pool use.
1296            let r = unsafe { (self.f.allocate_descriptor_sets)(self.dev, &ai, &mut set) };
1297            (r, set)
1298        };
1299        for &pool in st.pools.iter().rev() {
1300            let (r, set) = alloc(pool);
1301            if r == vk::SUCCESS {
1302                return Ok((pool, set));
1303            }
1304            if r != vk::ERROR_OUT_OF_POOL_MEMORY && r != vk::ERROR_FRAGMENTED_POOL {
1305                self.vk(r)?;
1306            }
1307        }
1308        // a new pool, large enough for 64 groups of this layout as well
1309        let mut sizes: Vec<vk::DescriptorPoolSize> = [
1310            (vk::DESCRIPTOR_TYPE_UNIFORM_BUFFER, 256),
1311            (vk::DESCRIPTOR_TYPE_STORAGE_BUFFER, 512),
1312            (vk::DESCRIPTOR_TYPE_SAMPLED_IMAGE, 512),
1313            (vk::DESCRIPTOR_TYPE_STORAGE_IMAGE, 128),
1314            (vk::DESCRIPTOR_TYPE_SAMPLER, 256),
1315        ]
1316        .iter()
1317        .map(|&(t, n)| vk::DescriptorPoolSize { type_: t, descriptor_count: n })
1318        .collect();
1319        for s in sizes.iter_mut() {
1320            let need: u32 = needs.iter().filter(|x| x.type_ == s.type_).map(|x| x.descriptor_count).sum();
1321            s.descriptor_count = s.descriptor_count.max(need.saturating_mul(64));
1322        }
1323        let pi = vk::DescriptorPoolCreateInfo {
1324            s_type: vk::STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
1325            flags: vk::DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT,
1326            max_sets: 256,
1327            pool_size_count: sizes.len() as u32,
1328            p_pool_sizes: sizes.as_ptr(),
1329            ..vk::Zero::zero()
1330        };
1331        let mut pool = 0;
1332        // SAFETY: valid create info.
1333        self.vk(unsafe { (self.f.create_descriptor_pool)(self.dev, &pi, core::ptr::null(), &mut pool) })?;
1334        st.pools.push(pool);
1335        let (r, set) = alloc(pool);
1336        self.vk(r)?;
1337        Ok((pool, set))
1338    }
1339}
1340
1341impl Drop for Shared {
1342    fn drop(&mut self) {
1343        let (f, d, n) = (&self.f, self.dev, core::ptr::null());
1344        // SAFETY: the last handle of the device is gone: wait for the GPU, then destroy every
1345        // object the device still owns, the device last.
1346        unsafe {
1347            (f.device_wait_idle)(d);
1348            let mut st = self.st.lock();
1349            if let Some(u) = st.upload.take() {
1350                for c in u.retired {
1351                    st.garbage.push((0, 0, Garbage::Buffer(c.buf, c.a)));
1352                }
1353                st.free.push(u.slot);
1354            }
1355            let ring = core::mem::take(&mut st.ring);
1356            for c in ring.cur.into_iter().chain(ring.free).chain(ring.busy.into_iter().map(|(_, c)| c)) {
1357                st.garbage.push((0, 0, Garbage::Buffer(c.buf, c.a)));
1358            }
1359            let pending = core::mem::take(&mut st.pending);
1360            let garbage = core::mem::take(&mut st.garbage);
1361            for (_, _, g) in garbage.into_iter().chain(pending) {
1362                self.destroy(&mut st, g);
1363            }
1364            for (_, s) in core::mem::take(&mut st.busy) {
1365                st.free.push(s);
1366            }
1367            let cfree = core::mem::take(&mut st.cfree);
1368            for s in st.free.drain(..).chain(cfree) {
1369                (f.destroy_command_pool)(d, s.pool, n);
1370            }
1371            for p in st.pools.drain(..) {
1372                (f.destroy_descriptor_pool)(d, p, n);
1373            }
1374            st.mem.destroy_all(f, d);
1375            (f.destroy_semaphore)(d, self.timeline, n);
1376            if let Some(l) = &self.lane {
1377                (f.destroy_semaphore)(d, l.timeline, n);
1378            }
1379            drop(st);
1380            (f.destroy_device)(d, n);
1381        }
1382    }
1383}
1384
1385impl Device {
1386    pub fn queue(&self) -> &Queue {
1387        &self.queue
1388    }
1389    /// (G5d) the queue of its own for compute and copies (a family without graphics), when DeviceOptions asked for it;
1390    /// None where the device has none, without asking and with jfgui_GPU_COMPUTE=0 (then everything goes through
1391    /// queue())
1392    pub fn compute_queue(&self) -> Option<&ComputeQueue> {
1393        self.compute.as_ref()
1394    }
1395    pub fn info(&self) -> &AdapterInfo {
1396        &self.sh.info
1397    }
1398    /// what this device has enabled
1399    pub fn features(&self) -> &Features {
1400        &self.sh.features
1401    }
1402    pub fn limits(&self) -> &Limits {
1403        &self.sh.limits
1404    }
1405    pub fn level(&self) -> Level {
1406        self.sh.level
1407    }
1408    /// the device was lost: every call fails with DeviceLost; create a new device
1409    pub fn is_lost(&self) -> bool {
1410        self.sh.check().is_err()
1411    }
1412    /// (test aid) behave as a lost device from now on (a lost device runs nothing any more and
1413    /// its resources may go at once; here the GPU may still work on the last submission: it
1414    /// finishes first)
1415    pub fn test_lose(&self) {
1416        let _ = self.wait_idle();
1417        self.sh.mark_lost();
1418    }
1419    /// the validation layer watches this device
1420    pub fn validating(&self) -> bool {
1421        self.sh.inst.validate
1422    }
1423    /// free what the GPU has finished with (also done by submit and wait)
1424    pub fn poll(&self) -> Result<()> {
1425        self.sh.check()?;
1426        let mut st = self.sh.st.lock();
1427        self.sh.collect(&mut st);
1428        drop(st);
1429        self.sh.check()
1430    }
1431    /// wait for a submission (of either queue) -> false when timeout_ns passed first
1432    pub fn wait(&self, id: SubmitId, timeout_ns: u64) -> Result<bool> {
1433        self.sh.wait_id(id.0, timeout_ns)
1434    }
1435    /// wait for every submission so far (of both queues)
1436    pub fn wait_idle(&self) -> Result<()> {
1437        let v = self.sh.submitted();
1438        let vc = self.sh.lane_submitted();
1439        if self.sh.wait_value(v, 10_000_000_000)? && (vc == 0 || self.sh.wait_id(vc | COMPUTE_ID, 10_000_000_000)?) { Ok(()) } else { Err(GpuError::Timeout) }
1440    }
1441    /// the last submission the GPU has finished
1442    pub fn completed(&self) -> SubmitId {
1443        SubmitId(self.sh.refresh())
1444    }
1445    /// the submission id (of either queue) is done on the GPU (asks the driver; never waits)
1446    pub fn is_done(&self, id: SubmitId) -> bool {
1447        if id.0 & COMPUTE_ID != 0 {
1448            return self.sh.lane_refresh() >= id.0 & !COMPUTE_ID;
1449        }
1450        self.sh.refresh() >= id.0
1451    }
1452    /// bytes of device and host memory the device holds in blocks
1453    pub fn memory_reserved(&self) -> u64 {
1454        self.sh.st.lock().mem.reserved
1455    }
1456}
1457
1458impl Queue {
1459    /// run command buffers in order (after the pending uploads) -> their timeline value
1460    pub fn submit<'a, I: IntoIterator<Item = crate::CommandBuffer<'a>>>(&self, cmds: I) -> Result<SubmitId> {
1461        let mut cbs = Vec::new();
1462        let mut slots = Vec::new();
1463        for c in cmds {
1464            let s = c.into_slot();
1465            cbs.push(s.cb);
1466            slots.push(s);
1467        }
1468        self.sh.submit(&cbs, slots, None, None).map(SubmitId)
1469    }
1470
1471    /// (G5d) run command buffers in order once the submissions `wait` (of either queue; Device::compute_queue) are
1472    /// done: a wait through the timeline, at all commands
1473    pub fn submit_after<'a, I: IntoIterator<Item = crate::CommandBuffer<'a>>>(&self, wait: &[SubmitId], cmds: I) -> Result<SubmitId> {
1474        let (cbs, slots) = split_cmds(cmds);
1475        let after: Vec<u64> = wait.iter().map(|w| w.0).collect();
1476        self.sh.submit_on(false, &cbs, slots, None, &after, None).map(SubmitId)
1477    }
1478
1479    /// submit the pending uploads now
1480    pub fn flush(&self) -> Result<SubmitId> {
1481        self.sh.submit(&[], Vec::new(), None, None).map(SubmitId)
1482    }
1483
1484    /// write data into a buffer at offset before the next submission (staged)
1485    pub fn write_buffer<T: Pod>(&self, buf: &crate::Buffer, offset: u64, data: &[T]) -> Result<()> {
1486        let bytes = crate::bytes_of(data);
1487        let n = bytes.len() as u64;
1488        if offset.checked_add(n).is_none_or(|e| e > buf.size()) {
1489            return Err(GpuError::Invalid("write_buffer: range outside the buffer"));
1490        }
1491        if n == 0 {
1492            return Ok(());
1493        }
1494        let sh = &self.sh;
1495        sh.check()?;
1496        let mut st = sh.st.lock();
1497        let (sbuf, soff, ptr) = sh.stage(&mut st, n)?;
1498        let cb = st.upload.as_ref().map_or(0, |u| u.slot.cb);
1499        // SAFETY: ptr addresses n mapped bytes of the staging chunk; the copy is recorded
1500        // into the upload buffer (recording, guarded by the lock).
1501        unsafe {
1502            core::ptr::copy_nonoverlapping(bytes.as_ptr(), ptr as *mut u8, bytes.len());
1503            let region = vk::BufferCopy { src_offset: soff, dst_offset: offset, size: n };
1504            (sh.f.cmd_copy_buffer)(cb, sbuf, buf.handle(), 1, &region);
1505        }
1506        Ok(())
1507    }
1508
1509    /// write texels into a texture region before the next submission (staged): the region
1510    /// goes from `before` to CopyDst, gets the data, then goes to `after`
1511    pub fn write_texture(&self, dst: &TextureRegion, data: &[u8], layout: DataLayout, before: Layout,
1512                         after: Layout) -> Result<()> {
1513        let t = dst.texture;
1514        let copy = crate::vk_res::copy_region(dst, &layout, data.len() as u64)?;
1515        let need = copy.1;
1516        let sh = &self.sh;
1517        sh.check()?;
1518        let mut st = sh.st.lock();
1519        let (sbuf, soff, ptr) = sh.stage(&mut st, need)?;
1520        let cb = st.upload.as_ref().map_or(0, |u| u.slot.cb);
1521        let mut region = copy.0;
1522        region.buffer_offset = soff;
1523        let range = crate::vk_res::subresources(t, dst.mip, 1, dst.base_layer, dst.layers);
1524        // SAFETY: as in write_buffer; data holds at least `need` bytes after layout.offset
1525        // (copy_region checked it).
1526        unsafe {
1527            core::ptr::copy_nonoverlapping(data.as_ptr().add(layout.offset as usize), ptr as *mut u8, need as usize);
1528            crate::vk_cmd::image_barrier(&sh.f, cb, t.image(), range, before, Layout::CopyDst);
1529            (sh.f.cmd_copy_buffer_to_image)(cb, sbuf, t.image(), vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &region);
1530            crate::vk_cmd::image_barrier(&sh.f, cb, t.image(), range, Layout::CopyDst, after);
1531        }
1532        Ok(())
1533    }
1534
1535    /// write rectangles (x, y, w, h; clipped to the texture, empty ones skipped) of mip 0, layer 0
1536    /// of a 2D texture from `data`, an image of the texture's size in rows of `stride` bytes (a
1537    /// framebuffer), before the next submission; the staged bytes are those of the rectangles.
1538    /// The whole level goes from `before` to CopyDst and then to `after`, once for all of them
1539    pub fn write_texture_rects(&self, t: &crate::Texture, rects: &[[i32; 4]], data: &[u8], stride: u32, before: Layout,
1540                               after: Layout) -> Result<()> {
1541        let f = t.format();
1542        let bb = f.block_bytes() as u64;
1543        if f.is_compressed() || f.is_depth() || t.depth() != 1 {
1544            return Err(GpuError::Invalid("write_texture_rects: an uncompressed 2D colour texture"));
1545        }
1546        let (tw, th) = (t.width() as i32, t.height() as i32);
1547        if (stride as u64) < tw as u64 * bb || (data.len() as u64) < stride as u64 * th as u64 {
1548            return Err(GpuError::Invalid("write_texture_rects: data smaller than the texture"));
1549        }
1550        self.write_texture_rects_at(t, rects, (0, 0), data, stride, before, after)
1551    }
1552
1553    /// write_texture_rects from an image of another size: rectangles (x, y, w, h) of `data`, an
1554    /// image in rows of `stride` bytes, go to (x - origin.0, y - origin.1) of the texture; what
1555    /// lies outside the image or the texture is skipped
1556    #[allow(clippy::too_many_arguments)]
1557    pub fn write_texture_rects_at(&self, t: &crate::Texture, rects: &[[i32; 4]], origin: (i32, i32), data: &[u8], stride: u32, before: Layout,
1558                                  after: Layout) -> Result<()> {
1559        let f = t.format();
1560        let bb = f.block_bytes() as u64;
1561        if f.is_compressed() || f.is_depth() || t.depth() != 1 {
1562            return Err(GpuError::Invalid("write_texture_rects: an uncompressed 2D colour texture"));
1563        }
1564        let (tw, th) = (t.width() as i32, t.height() as i32);
1565        if stride == 0 {
1566            return Err(GpuError::Invalid("write_texture_rects: stride 0"));
1567        }
1568        // the image's size: rows that lie completely in data, as many pixels as a row holds
1569        let (iw, ih) = ((stride as u64 / bb).min(i32::MAX as u64) as i64, (data.len() as u64 / stride as u64).min(i32::MAX as u64) as i64);
1570        let mut regions: Vec<vk::BufferImageCopy> = Vec::with_capacity(rects.len());
1571        let mut total = 0u64;
1572        let sub = crate::vk_res::subresources(t, 0, 1, 0, 1);
1573        let (ox, oy) = (origin.0 as i64, origin.1 as i64);
1574        for r in rects {
1575            // in the texture's coordinates, cut to the texture and the image
1576            let x0 = (r[0] as i64 - ox).max(0).max(-ox);
1577            let y0 = (r[1] as i64 - oy).max(0).max(-oy);
1578            let x1 = (r[0] as i64 + r[2] as i64 - ox).min(tw as i64).min(iw - ox);
1579            let y1 = (r[1] as i64 + r[3] as i64 - oy).min(th as i64).min(ih - oy);
1580            if x1 <= x0 || y1 <= y0 {
1581                continue;
1582            }
1583            let (x0, y0, x1, y1) = (x0 as i32, y0 as i32, x1 as i32, y1 as i32);
1584            let (w, h) = ((x1 - x0) as u32, (y1 - y0) as u32);
1585            regions.push(vk::BufferImageCopy {
1586                buffer_offset: total,
1587                buffer_row_length: w,
1588                buffer_image_height: h,
1589                image_subresource: vk::ImageSubresourceLayers { aspect_mask: sub.aspect_mask, mip_level: 0, base_array_layer: 0, layer_count: 1 },
1590                image_offset: vk::Offset3D { x: x0, y: y0, z: 0 },
1591                image_extent: vk::Extent3D { width: w, height: h, depth: 1 },
1592            });
1593            total += w as u64 * h as u64 * bb;
1594        }
1595        if regions.is_empty() {
1596            return Ok(());
1597        }
1598        let sh = &self.sh;
1599        sh.check()?;
1600        let mut st = sh.st.lock();
1601        let (sbuf, soff, ptr) = sh.stage(&mut st, total)?;
1602        let cb = st.upload.as_ref().map_or(0, |u| u.slot.cb);
1603        for g in regions.iter_mut() {
1604            let (x, y) = ((g.image_offset.x as i64 + ox) as usize, (g.image_offset.y as i64 + oy) as usize);
1605            let (w, h) = (g.image_extent.width as usize, g.image_extent.height as usize);
1606            let row = w * bb as usize;
1607            let mut dst = ptr + g.buffer_offset as usize;
1608            for yy in y..y + h {
1609                let from = yy * stride as usize + x * bb as usize;
1610                // SAFETY: the row lies in data (cut to the image above) and in the staged range
1611                // of `total` bytes, whose rectangles follow each other.
1612                unsafe { core::ptr::copy_nonoverlapping(data.as_ptr().add(from), dst as *mut u8, row) };
1613                dst += row;
1614            }
1615            g.buffer_offset += soff;
1616        }
1617        // SAFETY: the upload buffer is recording (guarded by the lock); the regions lie in the
1618        // texture (clipped above) and the staged range.
1619        unsafe {
1620            crate::vk_cmd::image_barrier(&sh.f, cb, t.image(), sub, before, Layout::CopyDst);
1621            (sh.f.cmd_copy_buffer_to_image)(cb, sbuf, t.image(), vk::IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, regions.len() as u32, regions.as_ptr());
1622            crate::vk_cmd::image_barrier(&sh.f, cb, t.image(), sub, Layout::CopyDst, after);
1623        }
1624        Ok(())
1625    }
1626
1627    /// read a buffer's contents at offset (copies through a readback buffer when needed,
1628    /// submits and waits for the GPU: the slow path, for tools and tests)
1629    pub fn read_buffer<T: Pod>(&self, buf: &crate::Buffer, offset: u64, out: &mut [T]) -> Result<()> {
1630        let n = core::mem::size_of_val(out) as u64;
1631        if offset.checked_add(n).is_none_or(|e| e > buf.size()) {
1632            return Err(GpuError::Invalid("read_buffer: range outside the buffer"));
1633        }
1634        if buf.memory() == MemoryKind::Readback {
1635            let id = self.flush()?;
1636            self.sh.wait_value(id.0, u64::MAX)?;
1637            return buf.read(offset, out);
1638        }
1639        let dev = Device { sh: self.sh.clone(), queue: self.clone(), compute: None };
1640        let rb = dev.create_buffer(&crate::BufferDesc { size: n.max(4), usage: crate::BufferUsage::NONE, memory: MemoryKind::Readback })?;
1641        let mut enc = dev.encoder()?;
1642        enc.copy_buffer(buf, offset, &rb, 0, n);
1643        let id = self.submit([enc.finish()?])?;
1644        if !self.sh.wait_value(id.0, 10_000_000_000)? {
1645            return Err(GpuError::Timeout);
1646        }
1647        rb.read(0, out)
1648    }
1649}
1650
1651/// (G5d) the command buffers' handles and slots
1652fn split_cmds<'a, I: IntoIterator<Item = crate::CommandBuffer<'a>>>(cmds: I) -> (Vec<vk::CommandBuffer>, Vec<Slot>) {
1653    let mut cbs = Vec::new();
1654    let mut slots = Vec::new();
1655    for c in cmds {
1656        let s = c.into_slot();
1657        cbs.push(s.cb);
1658        slots.push(s);
1659    }
1660    (cbs, slots)
1661}
1662
1663impl ComputeQueue {
1664    /// (G5d) an encoder of this queue's family: copies, fills, barriers, compute and timestamps (where the family has
1665    /// them); a render pass is Invalid (from finish)
1666    pub fn encoder(&self) -> Result<crate::CommandEncoder<'_>> {
1667        crate::vk_cmd::CommandEncoder::of(&self.sh, true)
1668    }
1669
1670    /// (G5d) run this queue's command buffers in order -> their SubmitId (Device::wait takes it); the pending uploads go
1671    /// first, on the device's queue
1672    pub fn submit<'a, I: IntoIterator<Item = crate::CommandBuffer<'a>>>(&self, cmds: I) -> Result<SubmitId> {
1673        self.submit_after(&[], cmds)
1674    }
1675
1676    /// (G5d) the same once the submissions `wait` (of either queue) are done: a wait through the timeline, at all
1677    /// commands
1678    pub fn submit_after<'a, I: IntoIterator<Item = crate::CommandBuffer<'a>>>(&self, wait: &[SubmitId], cmds: I) -> Result<SubmitId> {
1679        let (cbs, slots) = split_cmds(cmds);
1680        let after: Vec<u64> = wait.iter().map(|w| w.0).collect();
1681        self.sh.submit_on(true, &cbs, slots, None, &after, None).map(SubmitId)
1682    }
1683}