garage44.eu/jeroen/pinnacle

logclone: git clone https://garage44.eu/jeroen/pinnacle.git

.. /vulkan/src/lib.rs

raw

//! Pinnacle's Vulkan driver for programs: the functions Vulkan's callers
//! (ash, wgpu) take from [`vkGetInstanceProcAddr`], run on the host's GPU
//! through Venus over the program's GPU channel.
//!
//! Most functions are generated (`commands.rs`, `cargo xtask venus-gen`):
//! the handles a command makes are named by ids of the driver's, then the
//! command is sent โ€” a `vkCmd*` recorded, one with outputs called and its
//! reply read. The few Venus treats otherwise are here: names to
//! functions, extensions, the physical devices (one id each, per instance), the
//! queues (each on a ring of its own), mapping memory (memory the host
//! shares, as a blob), and every wait (Venus refuses one that would block
//! the host: they ask a fence's status until it is signalled); and the
//! window system, surfaces and swapchains onto the display server (`wsi.rs`).
//!
//! Commands go in order, through one stream: what is sent without a reply
//! waits in it until the next call, or until it is long. A stream longer
//! than a message is copied into memory the host shares and run from there
//! (vkExecuteCommandStreamsMESA).

#![allow(non_snake_case, clippy::missing_safety_doc)]

mod commands;
mod host;
mod stats;
mod wsi;

pub use wsi::*;

use pinnacle_venus::Host;
use pinnacle_venus::encode::*;
use pinnacle_venus::vk::*;
use pinnacle_venus::wire::{Decoder, Encoder};
use std::collections::HashMap;
use std::ffi::{CStr, c_char, c_void};
use std::ptr::{null, null_mut};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard};

pub use commands::proc_addr;

/// A command's flag: write a reply to the reply stream.
pub(crate) const GENERATE_REPLY: u32 = 1;
/// The reply stream's size: room for the largest reply.
const REPLY_SIZE: u64 = 1 << 20;
/// The memory long streams are run from.
const STREAMS_SIZE: u64 = 4 << 20;
/// The longest stream a message carries (a message's 4 KiB, its kind aside).
const MESSAGE_STREAM: usize = 4000;
/// How long a fence is waited for, in milliseconds, where the driver waits
/// on one itself.
const TIMEOUT_MS: u64 = 5000;
/// How long a reply is waited for before the GPU counts as gone. A reply
/// comes after everything submitted before it has been decoded, which under
/// a heavy frame took over 5 s; a call that gave up sooner answered zeros
/// (sizes, alignments), and the late reply was then taken for the next one.
const REPLY_TIMEOUT_MS: u64 = 60_000;
/// A reply slower than this is said on stderr, once per call.
const SLOW_REPLY_MS: u64 = 2000;
/// How long a reply is waited for on the core before the core is given
/// up: an empty round trip takes about 0.1 ms, and a yielded core comes
/// back only after the other threads' slices, up to 10 ms each.
const SPIN: std::time::Duration = std::time::Duration::from_millis(2);
/// The reply stream's first word while no reply has come.
const NO_REPLY: u32 = u32::MAX;
/// Where in the reply stream the sign that a reply is whole goes: past
/// any reply.
const REPLY_MARK: usize = REPLY_SIZE as usize - 64;

pub type PFN_vkVoidFunction = Option<unsafe extern "system" fn()>;

struct Driver {
    gpu: host::Gpu,
    /// The reply stream: where in the program it is mapped.
    reply: usize,
    /// The memory long streams are run from: its resource, where it is,
    /// and how much of it holds streams not yet known to have run.
    streams: (u32, usize, usize),
    /// What is sent without a reply, not yet submitted.
    pending: Encoder,
    /// The physical devices, by the ids they were made under.
    physical: Option<Vec<VkPhysicalDevice>>,
    /// Each device's queue families and counts, as created.
    devices: HashMap<VkDevice, Vec<(u32, u32)>>,
    /// The queues made: (device, family, index) โ†’ queue.
    queues: HashMap<(VkDevice, u32, u32), VkQueue>,
    queue_devices: HashMap<VkQueue, VkDevice>,
    next_ring: u32,
    /// Memory allocated: its size, and where it is mapped once it is.
    memory: HashMap<VkDeviceMemory, (u64, Option<host::Shared>)>,
    /// The memory types' property flags, once asked (`memory_types`).
    memory_types: Option<Vec<u32>>,
    /// Buffers made with no chain: their kind and size.
    buffers: HashMap<VkBuffer, (BufferKind, VkDeviceSize)>,
    /// Per kind of buffer, the alignment and memory types the host gave.
    buffer_requirements: HashMap<BufferKind, (VkDeviceSize, u32)>,
    /// Whether the host took a guest blob as memory: None until tried.
    guest_blobs: Option<bool>,
    stats: stats::Stats,
}

static DRIVER: Mutex<Option<Driver>> = Mutex::new(None);
/// The ids handles are named by: Venus makes the host's objects under them.
static NEXT_ID: AtomicU64 = AtomicU64::new(1 << 16);

pub(crate) fn new_id() -> u64 {
    NEXT_ID.fetch_add(1, Ordering::Relaxed)
}

/// The driver, started on first use: the GPU channel, the reply stream set,
/// the memory for long streams. None without a 3D GPU.
pub(crate) fn driver() -> MutexGuard<'static, Option<Driver>> {
    let mut guard = DRIVER.lock().unwrap_or_else(|e| e.into_inner());
    if guard.is_none() {
        *guard = start();
    }
    guard
}

fn start() -> Option<Driver> {
    let mut gpu = host::Gpu::open()?;
    let (reply_resource, reply) = gpu.blob(0, REPLY_SIZE)?;
    let (streams_resource, streams) = gpu.blob(0, STREAMS_SIZE)?;
    let mut stream: VkCommandStreamDescriptionMESA = zeroed();
    stream.resourceId = reply_resource;
    stream.size = REPLY_SIZE as usize;
    let mut e = Encoder::default();
    // SAFETY: a live local.
    unsafe { encode_vkSetReplyCommandStreamMESA(&mut e, 0, &stream) };
    if !gpu.submit(&e.0) {
        return None;
    }
    let reply = reply.address;
    let streams = (streams_resource, streams.address, 0);
    let mut driver = Driver {
        gpu,
        reply,
        streams,
        pending: Encoder::default(),
        physical: None,
        devices: HashMap::new(),
        queues: HashMap::new(),
        queue_devices: HashMap::new(),
        next_ring: 1,
        memory: HashMap::new(),
        memory_types: None,
        buffers: HashMap::new(),
        buffer_requirements: HashMap::new(),
        guest_blobs: None,
        stats: stats::Stats::new(),
    };
    if driver.stats.on() {
        // A round trip to the host with nothing else in it, at the start:
        // the floor every reply waited for stands on.
        let mut took: Vec<std::time::Duration> = (0..50)
            .map(|_| {
                let start = std::time::Instant::now();
                driver.sync();
                start.elapsed()
            })
            .collect();
        took.sort();
        eprintln!(
            "pinnacle-vulkan stats: an empty round trip takes {:?} at least, {:?} typically, {:?} at most",
            took[0], took[25], took[49]
        );
    }
    Some(driver)
}

pub(crate) fn zeroed<T>() -> T {
    // SAFETY: Vulkan's structs are integers, floats and raw pointers, for
    // which all zeros is a value.
    unsafe { std::mem::zeroed() }
}

impl Driver {
    /// Sends one message to the host, counted (`stats`): `long` when it
    /// runs a stream from the memory for long streams.
    fn send_message(&mut self, message: &[u8], long: bool) -> bool {
        let start = std::time::Instant::now();
        let sent = self.gpu.submit(message);
        self.stats.sent(message.len(), start.elapsed(), long);
        sent
    }

    /// Submits a stream: in a message when it fits, else from the memory
    /// for long streams. False when the channel refused it.
    fn submit(&mut self, stream: &[u8]) -> bool {
        if stream.is_empty() {
            return true;
        }
        if stream.len() <= MESSAGE_STREAM {
            return self.send_message(stream, false);
        }
        let (resource, at, used) = self.streams;
        let size = stream.len().next_multiple_of(4);
        if size > STREAMS_SIZE as usize {
            return false;
        }
        if used + size > STREAMS_SIZE as usize {
            // Make sure what is there has run before writing over it.
            self.sync();
            self.streams.2 = 0;
        }
        let offset = self.streams.2;
        // SAFETY: inside the memory for long streams, mapped for the driver.
        unsafe { std::ptr::copy_nonoverlapping(stream.as_ptr(), (at + offset) as *mut u8, stream.len()) };
        self.streams.2 = offset + size;
        let mut description: VkCommandStreamDescriptionMESA = zeroed();
        description.resourceId = resource;
        description.offset = offset;
        description.size = stream.len();
        let mut e = Encoder::default();
        // SAFETY: a live local; no reply positions, no dependencies.
        unsafe { encode_vkExecuteCommandStreamsMESA(&mut e, 0, 1, &description, null(), 0, null(), 0) };
        self.send_message(&e.0, true)
    }

    /// Submits what waits, and waits for it to have run.
    fn sync(&mut self) {
        let mut version = 0u32;
        let version_out = &raw mut version;
        self.call(
            COMMAND_VK_ENUMERATE_INSTANCE_VERSION,
            // SAFETY: a live local.
            |e| unsafe { encode_vkEnumerateInstanceVersion(e, GENERATE_REPLY, version_out) },
            |d| unsafe { decode_vkEnumerateInstanceVersion_reply(d, version_out) },
        );
    }

    /// Adds commands that write no reply to what waits.
    fn send(&mut self, encode: impl FnOnce(&mut Encoder)) {
        encode(&mut self.pending);
        if self.pending.0.len() > MESSAGE_STREAM {
            let pending = std::mem::take(&mut self.pending);
            self.submit(&pending.0);
        }
    }

    /// Sends a command with a reply after what waits, waits for the reply
    /// and reads it. None when no reply came or it did not read whole.
    fn call<R>(
        &mut self,
        kind: u32,
        encode: impl FnOnce(&mut Encoder),
        decode: impl FnOnce(&mut Decoder) -> R,
    ) -> Option<R> {
        let mut e = std::mem::take(&mut self.pending);
        // SAFETY: a value, no pointers.
        unsafe { encode_vkSeekReplyCommandStreamMESA(&mut e, 0, 0) };
        encode(&mut e);
        // The host writes a reply a field at a time, its command's number
        // first: that number showing says nothing of the rest. A second
        // command replies at the stream's end, after the first reply is
        // written whole (the host decodes in order); its number is the
        // sign. Read too early, a reply's sizes and alignments were zeros.
        let mut version = 0u32;
        // SAFETY: values and a live local; the reply to it is not read.
        unsafe {
            encode_vkSeekReplyCommandStreamMESA(&mut e, 0, REPLY_MARK);
            encode_vkEnumerateInstanceVersion(&mut e, GENERATE_REPLY, &mut version);
        }
        // SAFETY: the reply stream's first page, mapped for the driver.
        unsafe { std::ptr::write_bytes(self.reply as *mut u8, 0, 4096) };
        // A reply's first word is its command's number, 0 for
        // vkCreateInstance: no reply yet is a word no command has.
        let mark = (self.reply + REPLY_MARK) as *mut u32;
        // SAFETY: inside the reply stream, mapped for the driver.
        unsafe {
            (self.reply as *mut u32).write_volatile(NO_REPLY);
            mark.write_volatile(NO_REPLY);
        }
        let called = std::time::Instant::now();
        if !self.submit(&e.0) {
            eprintln!("pinnacle-vulkan: command {kind} could not be sent");
            return None;
        }
        let first = || {
            // SAFETY: inside the reply stream.
            unsafe { (self.reply as *const u32).read_volatile() }
        };
        let start = self.gpu.now_ms();
        let spin_until = std::time::Instant::now() + SPIN;
        let mut said = false;
        // SAFETY: as above.
        while unsafe { mark.read_volatile() } == NO_REPLY {
            let waited = self.gpu.now_ms() - start;
            if waited >= REPLY_TIMEOUT_MS {
                eprintln!("pinnacle-vulkan: no reply to command {kind} in {waited} ms; the GPU counts as gone");
                return None;
            }
            if waited >= SLOW_REPLY_MS && !said {
                eprintln!("pinnacle-vulkan: command {kind} waits over {SLOW_REPLY_MS} ms for its reply");
                said = true;
            }
            if std::time::Instant::now() < spin_until {
                std::hint::spin_loop();
            } else {
                std::thread::yield_now();
            }
        }
        // The reply's bytes are read after the sign that they are whole.
        std::sync::atomic::fence(std::sync::atomic::Ordering::Acquire);
        if first() != kind {
            eprintln!("pinnacle-vulkan: command {kind} got the reply of command {}", first());
            return None;
        }
        // What was submitted before this reply has run.
        self.streams.2 = 0;
        // SAFETY: the reply stream, mapped for as long as the driver.
        let bytes = unsafe { std::slice::from_raw_parts(self.reply as *const u8, REPLY_SIZE as usize) };
        let mut d = Decoder::new(bytes);
        self.stats.called(kind, called.elapsed());
        let value = decode(&mut d);
        if d.fatal {
            eprintln!("pinnacle-vulkan: the reply to command {kind} did not decode");
            return None;
        }
        Some(value)
    }
}

/// What a function returns when the GPU is gone or did not answer.
pub(crate) trait Lost {
    fn lost() -> Self;
}

impl Lost for VkResult {
    fn lost() -> Self {
        VK_ERROR_DEVICE_LOST
    }
}

impl Lost for () {
    fn lost() -> Self {}
}

impl Lost for u32 {
    fn lost() -> Self {
        0
    }
}

impl Lost for u64 {
    fn lost() -> Self {
        0
    }
}

/// Records a command of a command buffer (it runs on submit).
pub(crate) fn record(_command_buffer: VkCommandBuffer, encode: impl FnOnce(&mut Encoder)) {
    if let Some(driver) = driver().as_mut() {
        driver.send(encode);
    }
}

/// Sends a command that writes no reply.
pub(crate) fn send(encode: impl FnOnce(&mut Encoder)) {
    if let Some(driver) = driver().as_mut() {
        driver.send(encode);
    }
}

/// Calls a command and reads its reply.
pub(crate) fn call<R: Lost>(
    kind: u32,
    encode: impl FnOnce(&mut Encoder),
    decode: impl FnOnce(&mut Decoder) -> R,
) -> R {
    match driver().as_mut() {
        Some(driver) => driver.call(kind, encode, decode).unwrap_or_else(R::lost),
        None => R::lost(),
    }
}

/// The function `pName` stands for: what a caller starts from.
pub unsafe extern "system" fn vkGetInstanceProcAddr(
    _instance: VkInstance,
    pName: *const c_char,
) -> PFN_vkVoidFunction {
    if pName.is_null() {
        return None;
    }
    // SAFETY: a NUL-terminated name, as Vulkan has it.
    proc_addr(unsafe { CStr::from_ptr(pName) }.to_bytes())
}

pub unsafe extern "system" fn vkGetDeviceProcAddr(
    _device: VkDevice,
    pName: *const c_char,
) -> PFN_vkVoidFunction {
    // SAFETY: as vkGetInstanceProcAddr.
    unsafe { vkGetInstanceProcAddr(0, pName) }
}

/// Writes `items` out the Vulkan way: the count asked, or as many as fit.
pub(crate) unsafe fn enumerate<T: Copy>(items: &[T], pCount: *mut u32, pItems: *mut T) -> VkResult {
    // SAFETY: as the caller (Vulkan's rules) promised.
    unsafe {
        if pItems.is_null() {
            *pCount = items.len() as u32;
            return VK_SUCCESS;
        }
        let n = (*pCount as usize).min(items.len());
        std::ptr::copy_nonoverlapping(items.as_ptr(), pItems, n);
        *pCount = n as u32;
        if n < items.len() {
            VK_INCOMPLETE
        } else {
            VK_SUCCESS
        }
    }
}

/// An extension this driver does itself (`wsi.rs`), as Vulkan lists one.
fn own_extension(name: &[u8], version: u32) -> VkExtensionProperties {
    let mut extension: VkExtensionProperties = zeroed();
    for (to, &from) in extension.extensionName.iter_mut().zip(name) {
        *to = from as c_char;
    }
    extension.specVersion = version;
    extension
}

/// The instance's extensions: a surface (on a display server's window),
/// which the driver does itself.
pub unsafe extern "system" fn vkEnumerateInstanceExtensionProperties(
    _pLayerName: *const c_char,
    pPropertyCount: *mut u32,
    pProperties: *mut VkExtensionProperties,
) -> VkResult {
    let own = [own_extension(b"VK_KHR_surface", 25)];
    // SAFETY: as the caller promised.
    unsafe { enumerate(&own, pPropertyCount, pProperties) }
}

pub unsafe extern "system" fn vkEnumerateInstanceLayerProperties(
    pPropertyCount: *mut u32,
    pProperties: *mut VkLayerProperties,
) -> VkResult {
    // SAFETY: as the caller promised.
    unsafe { enumerate::<VkLayerProperties>(&[], pPropertyCount, pProperties) }
}

pub unsafe extern "system" fn vkEnumerateDeviceLayerProperties(
    _physicalDevice: VkPhysicalDevice,
    pPropertyCount: *mut u32,
    pProperties: *mut VkLayerProperties,
) -> VkResult {
    // SAFETY: as the caller promised.
    unsafe { enumerate::<VkLayerProperties>(&[], pPropertyCount, pProperties) }
}

/// Extensions Venus lists that a guest's driver does itself (Mesa's: over
/// dma-bufs, sync files, its own WSI), not the host: a device asking for
/// them on a host without them fails, so this driver does not offer them.
const GUEST_SIDE: &[&[u8]] = &[
    b"VK_KHR_external_memory_fd",
    b"VK_EXT_external_memory_dma_buf",
    b"VK_KHR_external_semaphore_fd",
    b"VK_KHR_external_fence_fd",
    b"VK_EXT_image_drm_format_modifier",
    b"VK_EXT_queue_family_foreign",
    b"VK_KHR_swapchain",
    b"VK_KHR_swapchain_mutable_format",
    b"VK_KHR_incremental_present",
    b"VK_KHR_present_id",
    b"VK_KHR_present_wait",
    b"VK_EXT_swapchain_maintenance1",
    b"VK_ANDROID_native_buffer",
    b"VK_ANDROID_external_memory_android_hardware_buffer",
];

/// The device's extensions, those the driver does not do left out.
pub unsafe extern "system" fn vkEnumerateDeviceExtensionProperties(
    physicalDevice: VkPhysicalDevice,
    pLayerName: *const c_char,
    pPropertyCount: *mut u32,
    pProperties: *mut VkExtensionProperties,
) -> VkResult {
    let mut count = 0u32;
    let count_out = &raw mut count;
    let counted = call(
        COMMAND_VK_ENUMERATE_DEVICE_EXTENSION_PROPERTIES,
        // SAFETY: a live local and the caller's name.
        |e| unsafe {
            encode_vkEnumerateDeviceExtensionProperties(
                e,
                GENERATE_REPLY,
                physicalDevice,
                pLayerName,
                count_out,
                null_mut(),
            )
        },
        |d| unsafe {
            decode_vkEnumerateDeviceExtensionProperties_reply(
                d,
                physicalDevice,
                pLayerName,
                count_out,
                null_mut(),
            )
        },
    );
    if counted != VK_SUCCESS {
        return counted;
    }
    let mut all: Vec<VkExtensionProperties> = (0..count).map(|_| zeroed()).collect();
    let all_out = all.as_mut_ptr();
    let listed = call(
        COMMAND_VK_ENUMERATE_DEVICE_EXTENSION_PROPERTIES,
        // SAFETY: `count` live locals.
        |e| unsafe {
            encode_vkEnumerateDeviceExtensionProperties(
                e,
                GENERATE_REPLY,
                physicalDevice,
                pLayerName,
                count_out,
                all_out,
            )
        },
        |d| unsafe {
            decode_vkEnumerateDeviceExtensionProperties_reply(
                d,
                physicalDevice,
                pLayerName,
                count_out,
                all_out,
            )
        },
    );
    if !matches!(listed, VK_SUCCESS | VK_INCOMPLETE) {
        return listed;
    }
    all.truncate(count as usize);
    all.retain(|extension| {
        // SAFETY: a NUL-terminated name, the reply's decoder made sure.
        let name = unsafe { CStr::from_ptr(extension.extensionName.as_ptr()) }.to_bytes();
        !GUEST_SIDE.contains(&name)
    });
    // Swapchains: the driver's own (`wsi.rs`).
    all.push(own_extension(b"VK_KHR_swapchain", 70));
    // SAFETY: as the caller promised.
    unsafe { enumerate(&all, pPropertyCount, pProperties) }
}

/// An instance: Venus takes none of the caller's layers or extensions (it
/// adds its own on the host).
pub unsafe extern "system" fn vkCreateInstance(
    pCreateInfo: *const VkInstanceCreateInfo,
    pAllocator: *const VkAllocationCallbacks,
    pInstance: *mut VkInstance,
) -> VkResult {
    // SAFETY: as the caller promised.
    let mut info = unsafe { *pCreateInfo };
    info.enabledLayerCount = 0;
    info.ppEnabledLayerNames = null();
    info.enabledExtensionCount = 0;
    info.ppEnabledExtensionNames = null();
    let _ = pAllocator;
    unsafe { *pInstance = new_id() };
    // A new instance has physical devices of its own: those of one before
    // (destroyed, the host's ids gone with it) are asked again, under new ids.
    if let Some(driver) = driver().as_mut() {
        driver.physical = None;
        driver.memory_types = None;
    }
    let info = &raw const info;
    call(
        COMMAND_VK_CREATE_INSTANCE,
        // SAFETY: a live local and the caller's pointer.
        |e| unsafe { encode_vkCreateInstance(e, GENERATE_REPLY, info, null(), pInstance) },
        |d| unsafe { decode_vkCreateInstance_reply(d, info, null(), pInstance) },
    )
}

/// The physical devices: asked once per instance, each under the same id
/// as long as it lasts.
pub unsafe extern "system" fn vkEnumeratePhysicalDevices(
    instance: VkInstance,
    pPhysicalDeviceCount: *mut u32,
    pPhysicalDevices: *mut VkPhysicalDevice,
) -> VkResult {
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else {
        return VK_ERROR_INITIALIZATION_FAILED;
    };
    if driver.physical.is_none() {
        let mut count = 0u32;
        let count_out = &raw mut count;
        let counted = driver.call(
            COMMAND_VK_ENUMERATE_PHYSICAL_DEVICES,
            // SAFETY: a live local.
            |e| unsafe {
                encode_vkEnumeratePhysicalDevices(e, GENERATE_REPLY, instance, count_out, null_mut())
            },
            |d| unsafe { decode_vkEnumeratePhysicalDevices_reply(d, instance, count_out, null_mut()) },
        );
        if counted != Some(VK_SUCCESS) {
            return VK_ERROR_INITIALIZATION_FAILED;
        }
        let mut ids: Vec<VkPhysicalDevice> = (0..count).map(|_| new_id()).collect();
        let ids_out = ids.as_mut_ptr();
        let listed = driver.call(
            COMMAND_VK_ENUMERATE_PHYSICAL_DEVICES,
            // SAFETY: live locals, `count` of them.
            |e| unsafe { encode_vkEnumeratePhysicalDevices(e, GENERATE_REPLY, instance, count_out, ids_out) },
            |d| unsafe { decode_vkEnumeratePhysicalDevices_reply(d, instance, count_out, ids_out) },
        );
        if !matches!(listed, Some(VK_SUCCESS | VK_INCOMPLETE)) {
            return VK_ERROR_INITIALIZATION_FAILED;
        }
        ids.truncate(count as usize);
        driver.physical = Some(ids);
    }
    let physical = driver.physical.clone().unwrap_or_default();
    drop(guard);
    // SAFETY: as the caller promised.
    unsafe { enumerate(&physical, pPhysicalDeviceCount, pPhysicalDevices) }
}

/// Each physical device a group of its own.
pub unsafe extern "system" fn vkEnumeratePhysicalDeviceGroups(
    instance: VkInstance,
    pPhysicalDeviceGroupCount: *mut u32,
    pPhysicalDeviceGroupProperties: *mut VkPhysicalDeviceGroupProperties,
) -> VkResult {
    let mut count = 0u32;
    // SAFETY: a live local.
    let result = unsafe { vkEnumeratePhysicalDevices(instance, &mut count, null_mut()) };
    if result != VK_SUCCESS {
        return result;
    }
    let mut physical = vec![0; count as usize];
    unsafe { vkEnumeratePhysicalDevices(instance, &mut count, physical.as_mut_ptr()) };
    // SAFETY: as the caller promised.
    unsafe {
        if pPhysicalDeviceGroupProperties.is_null() {
            *pPhysicalDeviceGroupCount = count;
            return VK_SUCCESS;
        }
        let n = (*pPhysicalDeviceGroupCount).min(count) as usize;
        for (i, &device) in physical.iter().take(n).enumerate() {
            let group = &mut *pPhysicalDeviceGroupProperties.add(i);
            group.physicalDeviceCount = 1;
            group.physicalDevices[0] = device;
            group.subsetAllocation = 0;
        }
        *pPhysicalDeviceGroupCount = n as u32;
        if n < count as usize {
            VK_INCOMPLETE
        } else {
            VK_SUCCESS
        }
    }
}

/// A device: its queues remembered, for vkGetDeviceQueue to make them on
/// rings of their own.
pub unsafe extern "system" fn vkCreateDevice(
    physicalDevice: VkPhysicalDevice,
    pCreateInfo: *const VkDeviceCreateInfo,
    pAllocator: *const VkAllocationCallbacks,
    pDevice: *mut VkDevice,
) -> VkResult {
    unsafe { *pDevice = new_id() };
    // The extensions the driver does itself (swapchains) are not the host's
    // to enable.
    // SAFETY: as the caller promised.
    let mut info = unsafe { *pCreateInfo };
    let extensions: Vec<*const c_char> = (0..info.enabledExtensionCount as usize)
        .map(|i| unsafe { *info.ppEnabledExtensionNames.add(i) })
        .filter(|&name| {
            let name = unsafe { CStr::from_ptr(name) }.to_bytes();
            name != b"VK_KHR_swapchain" && !GUEST_SIDE.contains(&name)
        })
        .collect();
    info.enabledExtensionCount = extensions.len() as u32;
    info.ppEnabledExtensionNames = extensions.as_ptr();
    let info = &raw const info;
    let result = call(
        COMMAND_VK_CREATE_DEVICE,
        // SAFETY: a live local and the caller's pointers.
        |e| unsafe { encode_vkCreateDevice(e, GENERATE_REPLY, physicalDevice, info, pAllocator, pDevice) },
        |d| unsafe { decode_vkCreateDevice_reply(d, physicalDevice, info, pAllocator, pDevice) },
    );
    if result == VK_SUCCESS {
        // SAFETY: as the caller promised.
        let families = unsafe {
            let info = &*pCreateInfo;
            (0..info.queueCreateInfoCount as usize)
                .map(|i| {
                    let q = &*info.pQueueCreateInfos.add(i);
                    (q.queueFamilyIndex, q.queueCount)
                })
                .collect()
        };
        if let Some(driver) = driver().as_mut() {
            driver.devices.insert(unsafe { *pDevice }, families);
        }
    }
    result
}

/// The queue `index` of `family` on `device`: made once (Venus takes each
/// once, by vkGetDeviceQueue2, on a ring of its own), the same ever after.
pub(crate) fn queue(device: VkDevice, flags: VkDeviceQueueCreateFlags, family: u32, index: u32) -> VkQueue {
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else { return 0 };
    if let Some(&queue) = driver.queues.get(&(device, family, index)) {
        return queue;
    }
    let mut timeline: VkDeviceQueueTimelineInfoMESA = zeroed();
    timeline.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_TIMELINE_INFO_MESA;
    timeline.ringIdx = driver.next_ring;
    driver.next_ring += 1;
    let mut info: VkDeviceQueueInfo2 = zeroed();
    info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2;
    info.pNext = &raw const timeline as *const c_void;
    info.flags = flags;
    info.queueFamilyIndex = family;
    info.queueIndex = index;
    let mut queue = new_id();
    let queue_out = &raw mut queue;
    let info = &raw const info;
    driver.call(
        COMMAND_VK_GET_DEVICE_QUEUE2,
        // SAFETY: live locals.
        |e| unsafe { encode_vkGetDeviceQueue2(e, GENERATE_REPLY, device, info, queue_out) },
        |d| unsafe { decode_vkGetDeviceQueue2_reply(d, device, info, queue_out) },
    );
    driver.queues.insert((device, family, index), queue);
    driver.queue_devices.insert(queue, device);
    queue
}

pub unsafe extern "system" fn vkGetDeviceQueue(
    device: VkDevice,
    queueFamilyIndex: u32,
    queueIndex: u32,
    pQueue: *mut VkQueue,
) {
    unsafe { *pQueue = queue(device, 0, queueFamilyIndex, queueIndex) };
}

pub unsafe extern "system" fn vkGetDeviceQueue2(
    device: VkDevice,
    pQueueInfo: *const VkDeviceQueueInfo2,
    pQueue: *mut VkQueue,
) {
    // SAFETY: as the caller promised.
    unsafe {
        let info = &*pQueueInfo;
        *pQueue = queue(device, info.flags, info.queueFamilyIndex, info.queueIndex);
    }
}

/// The granule memory the host shares is mapped in (the kernel's window's,
/// a whole number of any host's pages).
const MAPPED_GRANULE: u64 = 64 << 10;
/// The most a guest blob holds: the kernel's largest block of pages.
const GUEST_BLOB_MOST: u64 = 16 << 20;

/// Whether the host takes guest blobs as memory: not known until the first
/// is tried, and not tried again once one failed.
fn guest_blobs_offered() -> bool {
    driver().as_ref().is_some_and(|d| d.guest_blobs != Some(false))
}

/// The first physical device's memory types' property flags, asked once
/// per instance.
fn memory_types() -> Vec<u32> {
    let physical = {
        let guard = driver();
        let Some(driver) = guard.as_ref() else {
            return Vec::new();
        };
        if let Some(types) = &driver.memory_types {
            return types.clone();
        }
        match driver.physical.as_ref().and_then(|p| p.first().copied()) {
            Some(physical) => physical,
            None => return Vec::new(),
        }
    };
    let mut properties: VkPhysicalDeviceMemoryProperties = zeroed();
    // SAFETY: a live local.
    unsafe { commands::vkGetPhysicalDeviceMemoryProperties(physical, &mut properties) };
    let types: Vec<u32> = (0..properties.memoryTypeCount.min(32) as usize)
        .map(|i| properties.memoryTypes[i].propertyFlags)
        .collect();
    if let Some(driver) = driver().as_mut() {
        driver.memory_types = Some(types.clone());
    }
    types
}

/// Memory: its size remembered, for mapping it. Memory the host may share
/// is made a whole number of the granule it is mapped in: the host rounds
/// it to its pages, and a blob of it is the window's granule โ€” sizes that
/// differ and it is not shared.
pub unsafe extern "system" fn vkAllocateMemory(
    device: VkDevice,
    pAllocateInfo: *const VkMemoryAllocateInfo,
    pAllocator: *const VkAllocationCallbacks,
    pMemory: *mut VkDeviceMemory,
) -> VkResult {
    unsafe { *pMemory = new_id() };
    // SAFETY: as the caller promised.
    let mut info = unsafe { *pAllocateInfo };
    let visible = memory_types()
        .get(info.memoryTypeIndex as usize)
        .is_some_and(|&flags| flags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT as u32 != 0);
    if visible {
        info.allocationSize = info.allocationSize.next_multiple_of(MAPPED_GRANULE);
    }
    let size = info.allocationSize;
    // Memory the CPU maps, from the guest's own pages where the host can
    // use them as they are: past the host-visible window, which wgpu's
    // uploads filled. Imported by resource id; where the host cannot (an
    // unpatched QEMU, RAM with no file behind it) the driver stops asking.
    if visible && size <= GUEST_BLOB_MOST && guest_blobs_offered() {
        let memory = unsafe { *pMemory };
        let guest = driver().as_mut().and_then(|d| d.gpu.guest_blob(size));
        if let Some((resource, shared)) = guest {
            let mut import: VkImportMemoryResourceInfoMESA = zeroed();
            import.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_RESOURCE_INFO_MESA;
            import.pNext = info.pNext;
            import.resourceId = resource;
            let mut imported = info;
            imported.pNext = &raw const import as *const c_void;
            let imported = &raw const imported;
            let result = call(
                COMMAND_VK_ALLOCATE_MEMORY,
                // SAFETY: live locals and the caller's pointers.
                |e| unsafe { encode_vkAllocateMemory(e, GENERATE_REPLY, device, imported, pAllocator, pMemory) },
                |d| unsafe { decode_vkAllocateMemory_reply(d, device, imported, pAllocator, pMemory) },
            );
            if let Some(driver) = driver().as_mut() {
                if result == VK_SUCCESS {
                    driver.memory.insert(memory, (size, Some(shared)));
                    return VK_SUCCESS;
                }
                driver.gpu.free(shared);
                driver.guest_blobs = Some(false);
                eprintln!("pinnacle-vulkan: the host took no guest blob as memory ({result}); mapped memory goes through its window");
            }
        } else if let Some(driver) = driver().as_mut() {
            driver.guest_blobs = Some(false);
            eprintln!("pinnacle-vulkan: the kernel made no guest blob; mapped memory goes through the host's window");
        }
    }
    let info = &raw const info;
    let result = call(
        COMMAND_VK_ALLOCATE_MEMORY,
        // SAFETY: a live local and the caller's pointers.
        |e| unsafe { encode_vkAllocateMemory(e, GENERATE_REPLY, device, info, pAllocator, pMemory) },
        |d| unsafe { decode_vkAllocateMemory_reply(d, device, info, pAllocator, pMemory) },
    );
    if result == VK_SUCCESS
        && let Some(driver) = driver().as_mut()
    {
        driver.memory.insert(unsafe { *pMemory }, (size, None));
    }
    result
}

/// Mapped as memory the host shares: a blob of it (its id the memory's).
pub unsafe extern "system" fn vkMapMemory(
    _device: VkDevice,
    memory: VkDeviceMemory,
    offset: VkDeviceSize,
    _size: VkDeviceSize,
    _flags: VkMemoryMapFlags,
    ppData: *mut *mut c_void,
) -> VkResult {
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else {
        return VK_ERROR_DEVICE_LOST;
    };
    // What waits goes first: the memory's commands must have run.
    let pending = std::mem::take(&mut driver.pending);
    driver.submit(&pending.0);
    let Some(&(size, ref mapped)) = driver.memory.get(&memory) else {
        return VK_ERROR_MEMORY_MAP_FAILED;
    };
    let address = match mapped {
        Some(shared) => shared.address,
        None => match driver.gpu.blob(memory, size) {
            Some((_, shared)) => {
                let address = shared.address;
                driver.memory.insert(memory, (size, Some(shared)));
                address
            }
            None => return VK_ERROR_MEMORY_MAP_FAILED,
        },
    };
    unsafe { *ppData = (address + offset as usize) as *mut c_void };
    VK_SUCCESS
}

/// Left mapped until the memory is freed: mapping again is then free.
pub unsafe extern "system" fn vkUnmapMemory(_device: VkDevice, _memory: VkDeviceMemory) {}

pub unsafe extern "system" fn vkFreeMemory(
    device: VkDevice,
    memory: VkDeviceMemory,
    pAllocator: *const VkAllocationCallbacks,
) {
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else { return };
    if let Some((_, Some(shared))) = driver.memory.remove(&memory) {
        driver.gpu.free(shared);
    }
    // SAFETY: the caller's handle; no allocator.
    driver.send(|e| unsafe { encode_vkFreeMemory(e, 0, device, memory, pAllocator) });
}

/// What a buffer's memory requirements follow from: its device, flags,
/// usage and sharing (its size aside).
type BufferKind = (VkDevice, VkBufferCreateFlags, VkBufferUsageFlags, VkSharingMode);

/// Sent with no reply (Mesa's Venus does too), its kind and size kept for
/// [`vkGetBufferMemoryRequirements`].
pub unsafe extern "system" fn vkCreateBuffer(
    device: VkDevice,
    pCreateInfo: *const VkBufferCreateInfo,
    pAllocator: *const VkAllocationCallbacks,
    pBuffer: *mut VkBuffer,
) -> VkResult {
    // SAFETY: as the caller promised.
    let info = unsafe { &*pCreateInfo };
    unsafe { *pBuffer = new_id() };
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else {
        return VK_ERROR_DEVICE_LOST;
    };
    // A chain (external memory, say) may change the requirements.
    if info.pNext.is_null() {
        let kind = (device, info.flags, info.usage, info.sharingMode);
        driver.buffers.insert(unsafe { *pBuffer }, (kind, info.size));
    }
    // SAFETY: the caller's pointers.
    driver.send(|e| unsafe { encode_vkCreateBuffer(e, 0, device, pCreateInfo, pAllocator, pBuffer) });
    VK_SUCCESS
}

pub unsafe extern "system" fn vkDestroyBuffer(
    device: VkDevice,
    buffer: VkBuffer,
    pAllocator: *const VkAllocationCallbacks,
) {
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else { return };
    driver.buffers.remove(&buffer);
    // SAFETY: the caller's handle.
    driver.send(|e| unsafe { encode_vkDestroyBuffer(e, 0, device, buffer, pAllocator) });
}

/// Asked once per kind of buffer: a buffer of a kind seen has the
/// alignment and memory types the first had, and its size rounded up to
/// that alignment, as Mesa's Venus works it out. Kept only when the first
/// answer bore the rule out. A frame asked hundreds of times, a round
/// trip each.
pub unsafe extern "system" fn vkGetBufferMemoryRequirements(
    device: VkDevice,
    buffer: VkBuffer,
    pMemoryRequirements: *mut VkMemoryRequirements,
) {
    let mut guard = driver();
    let Some(driver) = guard.as_mut() else { return };
    let known = driver.buffers.get(&buffer).copied();
    if let Some((kind, size)) = known
        && let Some(&(alignment, types)) = driver.buffer_requirements.get(&kind)
    {
        // SAFETY: the caller's output.
        unsafe {
            *pMemoryRequirements = VkMemoryRequirements {
                size: size.next_multiple_of(alignment),
                alignment,
                memoryTypeBits: types,
            }
        };
        return;
    }
    driver.call(
        COMMAND_VK_GET_BUFFER_MEMORY_REQUIREMENTS,
        // SAFETY: the caller's handle and output.
        |e| unsafe { encode_vkGetBufferMemoryRequirements(e, GENERATE_REPLY, device, buffer, pMemoryRequirements) },
        |d| unsafe { decode_vkGetBufferMemoryRequirements_reply(d, device, buffer, pMemoryRequirements) },
    );
    // SAFETY: just written by the reply.
    let asked = unsafe { *pMemoryRequirements };
    if let Some((kind, size)) = known
        && asked.alignment.is_power_of_two()
        && asked.size == size.next_multiple_of(asked.alignment)
    {
        driver.buffer_requirements.insert(kind, (asked.alignment, asked.memoryTypeBits));
    }
}

/// A fence's status, asked.
fn fence_status(device: VkDevice, fence: VkFence) -> VkResult {
    call(
        COMMAND_VK_GET_FENCE_STATUS,
        // SAFETY: values.
        |e| unsafe { encode_vkGetFenceStatus(e, GENERATE_REPLY, device, fence) },
        |d| unsafe { decode_vkGetFenceStatus_reply(d, device, fence) },
    )
}

/// Waits by asking the fences' status until they are signalled (all, or
/// any), or the time is up.
pub unsafe extern "system" fn vkWaitForFences(
    device: VkDevice,
    fenceCount: u32,
    pFences: *const VkFence,
    waitAll: VkBool32,
    timeout: u64,
) -> VkResult {
    // SAFETY: as the caller promised.
    let fences = unsafe { std::slice::from_raw_parts(pFences, fenceCount as usize) };
    let start = std::time::Instant::now();
    loop {
        let mut signalled = 0;
        for &fence in fences {
            match fence_status(device, fence) {
                VK_SUCCESS => signalled += 1,
                VK_NOT_READY => {}
                other => return other,
            }
        }
        if (waitAll != 0 && signalled == fences.len()) || (waitAll == 0 && signalled > 0) {
            return VK_SUCCESS;
        }
        if start.elapsed().as_nanos() as u64 >= timeout {
            return VK_TIMEOUT;
        }
        std::thread::yield_now();
    }
}

/// A queue's work waited for: an empty submit signalling a fence of ours.
pub unsafe extern "system" fn vkQueueWaitIdle(queue: VkQueue) -> VkResult {
    let device = driver()
        .as_ref()
        .and_then(|d| d.queue_devices.get(&queue).copied())
        .unwrap_or(0);
    let mut info: VkFenceCreateInfo = zeroed();
    info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
    let mut fence = new_id();
    let fence_out = &raw mut fence;
    let info = &raw const info;
    let made = call(
        COMMAND_VK_CREATE_FENCE,
        // SAFETY: live locals.
        |e| unsafe { encode_vkCreateFence(e, GENERATE_REPLY, device, info, null(), fence_out) },
        |d| unsafe { decode_vkCreateFence_reply(d, device, info, null(), fence_out) },
    );
    if made != VK_SUCCESS {
        return made;
    }
    let submitted = call(
        COMMAND_VK_QUEUE_SUBMIT,
        // SAFETY: no submits, a fence.
        |e| unsafe { encode_vkQueueSubmit(e, GENERATE_REPLY, queue, 0, null(), fence) },
        |d| unsafe { decode_vkQueueSubmit_reply(d, queue, 0, null(), fence) },
    );
    let result = match submitted {
        VK_SUCCESS => unsafe { vkWaitForFences(device, 1, &fence, 1, TIMEOUT_MS * 1_000_000) },
        other => other,
    };
    // SAFETY: the fence just made.
    send(|e| unsafe { encode_vkDestroyFence(e, 0, device, fence, null()) });
    result
}

/// Every queue of the device waited for.
pub unsafe extern "system" fn vkDeviceWaitIdle(device: VkDevice) -> VkResult {
    let queues: Vec<VkQueue> = driver()
        .as_ref()
        .map(|d| {
            d.queues
                .iter()
                .filter(|((dev, ..), _)| *dev == device)
                .map(|(_, &q)| q)
                .collect()
        })
        .unwrap_or_default();
    for queue in queues {
        let result = unsafe { vkQueueWaitIdle(queue) };
        if result != VK_SUCCESS {
            return result;
        }
    }
    VK_SUCCESS
}