garage44.eu/jeroen/pinnacle

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

.. /venus/src/lib.rs

raw

//! Venus: a program's Vulkan commands, serialized for the host's Vulkan to
//! run (VK_EXT_command_serialization, VK_MESA_venus_protocol), over a
//! [`Host`] that carries them — a program's GPU channel, or anything else
//! that can send a command stream and share the host's memory.
//!
//! [`vk`] is Vulkan's types as C lays them out and [`encode`] Venus's
//! encoders and reply decoders for all of what Venus carries, both
//! generated from Vulkan's registry (`cargo xtask venus-gen`); [`wire`] is
//! what they are written in. [`hello`] is a session on them: the host's
//! version, its GPUs, and a first command run on one.

#![no_std]

extern crate alloc;

pub mod encode;
pub mod vk;
pub mod wire;

use alloc::string::String;
use alloc::vec::Vec;
use core::ffi::c_void;
use core::ptr::{null, null_mut};
use encode::*;
use vk::*;
use wire::{Decoder, Encoder};

/// What carries Venus: a context on the host's GPU.
pub trait Host {
    /// Memory the host shares, as this side holds it.
    type Memory;
    /// Sends a command stream (whole commands) to the context.
    fn submit(&mut self, stream: &[u8]) -> bool;
    /// Memory the host shares: `blob_id` 0 for memory of Venus's own (a
    /// reply stream), else a `VkDeviceMemory`'s id; `size` bytes at least.
    /// Returns the resource Venus names it by, and the memory.
    fn blob(&mut self, blob_id: u64, size: u64) -> Option<(u32, Self::Memory)>;
    /// Where the memory is, in this side's view.
    fn address(memory: &Self::Memory) -> usize;
    /// Gives the memory back.
    fn free(&mut self, memory: Self::Memory);
    /// A clock in milliseconds, for giving up on a reply.
    fn now_ms(&self) -> u64;
}

/// A command's flag: write a reply to the reply stream.
pub const GENERATE_REPLY: u32 = 1;
/// The bytes of a session's reply stream.
const REPLY_SIZE: u64 = 64 << 10;
/// Where the sign that a reply is whole goes: past any reply.
const REPLY_MARK: usize = REPLY_SIZE as usize - 64;

/// What the host's Vulkan said, asked through Venus.
pub struct Hello {
    /// The instance version (Vulkan's packing: variant, major, minor, patch).
    pub version: u32,
    /// The host's GPUs: name, vendor, device and type
    /// (`VkPhysicalDeviceType`: 1 integrated, 2 discrete, 3 virtual, 4 CPU).
    pub devices: Vec<(String, u32, u32, u32)>,
    /// The bytes of a buffer the first GPU filled, read back as [`FILL`].
    pub filled: u32,
}

/// What the first command fills its buffer with: "Pinn".
pub const FILL: u32 = u32::from_le_bytes(*b"Pinn");
/// The buffer's size, and its memory's.
const FILL_SIZE: u64 = 64 << 10;

/// Object ids are the guest's to choose (Venus makes the host's objects
/// under them): the instance, its physical devices, the logical device and
/// what is made on it.
const INSTANCE_ID: u64 = 1;
const PHYSICAL_DEVICE_IDS: u64 = 16;
/// At most this many physical devices are asked for.
const MAX_PHYSICAL_DEVICES: u32 = 8;
const DEVICE_ID: u64 = 32;
const QUEUE_ID: u64 = 33;
const MEMORY_ID: u64 = 34;
const BUFFER_ID: u64 = 35;
const POOL_ID: u64 = 36;
const COMMAND_BUFFER_ID: u64 = 37;
const FENCE_ID: u64 = 38;

/// A Vulkan struct with every field zero (null pointers, no flags).
fn zeroed<T>() -> T {
    // SAFETY: Vulkan's structs are integers, floats and raw pointers, for
    // which all zeros is a value.
    unsafe { core::mem::zeroed() }
}

/// One Venus session: a context, and memory the host shares as its reply
/// stream. Everything made is let go after.
struct Venus<'a, H: Host> {
    host: &'a mut H,
    /// Where the reply stream is, in this side's view.
    reply: usize,
}

impl<H: Host> Venus<'_, H> {
    /// Sends one command, which `encode` writes with [`GENERATE_REPLY`], and
    /// returns its reply to read: the stream is sought to its start first,
    /// and the reply waited for. The submit is answered before the render
    /// server has run it (Mesa's driver waits on a fence); here the
    /// command's type appearing in the reply says it ran.
    fn call(
        &mut self,
        kind: u32,
        encode: impl FnOnce(&mut Encoder),
    ) -> Result<Decoder<'static>, &'static str> {
        // SAFETY: the reply stream's first page, mapped for this side.
        unsafe { core::ptr::write_bytes(self.reply as *mut u8, 0, 4096) };
        // The reply's first word is its command's number, 0 for
        // vkCreateInstance: no reply yet is a word no command has.
        // A second command's reply at the stream's end says the first is
        // written whole: the host writes a reply a field at a time.
        let mark = (self.reply + REPLY_MARK) as *mut u32;
        // SAFETY: as above.
        unsafe {
            (self.reply as *mut u32).write_volatile(u32::MAX);
            mark.write_volatile(u32::MAX);
        }
        let mut e = Encoder::default();
        let mut version = 0u32;
        // SAFETY: values and a live local, whose reply is not read.
        unsafe {
            encode_vkSeekReplyCommandStreamMESA(&mut e, 0, 0);
            encode(&mut e);
            encode_vkSeekReplyCommandStreamMESA(&mut e, 0, REPLY_MARK);
            encode_vkEnumerateInstanceVersion(&mut e, GENERATE_REPLY, &mut version);
        }
        self.submit(&e)?;
        let first = || {
            // SAFETY: inside the reply stream.
            unsafe { (self.reply as *const u32).read_volatile() }
        };
        let deadline = self.host.now_ms() + 2000;
        // SAFETY: inside the reply stream.
        while unsafe { mark.read_volatile() } == u32::MAX && self.host.now_ms() < deadline {
            core::hint::spin_loop();
        }
        core::sync::atomic::fence(core::sync::atomic::Ordering::Acquire);
        if first() != kind {
            return Err("no reply in the reply stream");
        }
        // SAFETY: the reply stream, mapped for as long as the session.
        let bytes = unsafe { core::slice::from_raw_parts(self.reply as *const u8, REPLY_SIZE as usize) };
        Ok(Decoder::new(bytes))
    }

    /// Sends commands that write no reply.
    fn submit(&mut self, e: &Encoder) -> Result<(), &'static str> {
        match self.host.submit(&e.0) {
            true => Ok(()),
            false => Err("the command stream was refused"),
        }
    }

    /// A command answering a VkResult: VK_SUCCESS, and a reply that read whole.
    fn check(
        &mut self,
        kind: u32,
        what: &'static str,
        encode: impl FnOnce(&mut Encoder),
        decode: impl FnOnce(&mut Decoder) -> VkResult,
    ) -> Result<(), &'static str> {
        let mut d = self.call(kind, encode)?;
        if decode(&mut d) != VK_SUCCESS || d.fatal {
            return Err(what);
        }
        Ok(())
    }

    /// A first command on a GPU: a logical device and its queue, a buffer in
    /// memory the host shares, a command buffer that fills it with [`FILL`],
    /// submitted with a fence that is asked until signalled. Returns how
    /// many of the buffer's bytes read back as [`FILL`]. Everything made is
    /// let go after.
    fn fill(&mut self, physical: VkPhysicalDevice) -> Result<u32, &'static str> {
        // SAFETY (all the encoders and decoders below): every pointer points
        // at a live local of the type the command takes, or is null.
        // A queue family that can copy (graphics, compute or transfer).
        let mut count = 0u32;
        let mut d = self.call(
            COMMAND_VK_GET_PHYSICAL_DEVICE_QUEUE_FAMILY_PROPERTIES,
            |e| unsafe {
                encode_vkGetPhysicalDeviceQueueFamilyProperties(
                    e,
                    GENERATE_REPLY,
                    physical,
                    &mut count,
                    null_mut(),
                )
            },
        )?;
        unsafe {
            decode_vkGetPhysicalDeviceQueueFamilyProperties_reply(&mut d, physical, &mut count, null_mut())
        };
        let mut families: Vec<VkQueueFamilyProperties> = (0..count.min(16)).map(|_| zeroed()).collect();
        let mut count = families.len() as u32;
        let mut d = self.call(
            COMMAND_VK_GET_PHYSICAL_DEVICE_QUEUE_FAMILY_PROPERTIES,
            |e| unsafe {
                encode_vkGetPhysicalDeviceQueueFamilyProperties(
                    e,
                    GENERATE_REPLY,
                    physical,
                    &mut count,
                    families.as_mut_ptr(),
                )
            },
        )?;
        unsafe {
            decode_vkGetPhysicalDeviceQueueFamilyProperties_reply(
                &mut d,
                physical,
                &mut count,
                families.as_mut_ptr(),
            )
        };
        let copies = (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT) as u32;
        let family = families
            .iter()
            .take(count as usize)
            .position(|f| f.queueFlags & copies != 0)
            .ok_or("no queue family that can fill a buffer")? as u32;

        // The memory types.
        let mut memory_properties: VkPhysicalDeviceMemoryProperties = zeroed();
        let mut d = self.call(COMMAND_VK_GET_PHYSICAL_DEVICE_MEMORY_PROPERTIES, |e| unsafe {
            encode_vkGetPhysicalDeviceMemoryProperties(e, GENERATE_REPLY, physical, &mut memory_properties)
        })?;
        unsafe { decode_vkGetPhysicalDeviceMemoryProperties_reply(&mut d, physical, &mut memory_properties) };

        // The logical device: one queue of the family, priority 1.0.
        let priority = 1.0f32;
        let mut queue_info: VkDeviceQueueCreateInfo = zeroed();
        queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
        queue_info.queueFamilyIndex = family;
        queue_info.queueCount = 1;
        queue_info.pQueuePriorities = &priority;
        let mut device_info: VkDeviceCreateInfo = zeroed();
        device_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
        device_info.queueCreateInfoCount = 1;
        device_info.pQueueCreateInfos = &queue_info;
        let mut device = DEVICE_ID;
        let device_out = &raw mut device;
        self.check(
            COMMAND_VK_CREATE_DEVICE,
            "vkCreateDevice failed on the host",
            |e| unsafe {
                encode_vkCreateDevice(e, GENERATE_REPLY, physical, &device_info, null(), device_out)
            },
            |d| unsafe { decode_vkCreateDevice_reply(d, physical, &device_info, null(), device_out) },
        )?;
        let mut made_buffer = false;
        let mut made_pool = false;
        let mut made_memory = false;
        let mut made_fence = false;
        let mut mapped = None;
        let result = (|| {
            // Its queue, on ring 1: Venus takes queues by vkGetDeviceQueue2,
            // with the ring they are timed on.
            let mut timeline: VkDeviceQueueTimelineInfoMESA = zeroed();
            timeline.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_TIMELINE_INFO_MESA;
            timeline.ringIdx = 1;
            let mut queue_info: VkDeviceQueueInfo2 = zeroed();
            queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_INFO_2;
            queue_info.pNext = &timeline as *const _ as *const c_void;
            queue_info.queueFamilyIndex = family;
            let mut queue = QUEUE_ID;
            let mut d = self.call(COMMAND_VK_GET_DEVICE_QUEUE2, |e| unsafe {
                encode_vkGetDeviceQueue2(e, GENERATE_REPLY, DEVICE_ID, &queue_info, &mut queue)
            })?;
            unsafe { decode_vkGetDeviceQueue2_reply(&mut d, DEVICE_ID, &queue_info, &mut queue) };

            // The buffer, and what memory it may live in.
            let mut buffer_info: VkBufferCreateInfo = zeroed();
            buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
            buffer_info.size = FILL_SIZE;
            buffer_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT as u32;
            buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
            let mut buffer = BUFFER_ID;
            let buffer_out = &raw mut buffer;
            self.check(
                COMMAND_VK_CREATE_BUFFER,
                "vkCreateBuffer failed on the host",
                |e| unsafe {
                    encode_vkCreateBuffer(e, GENERATE_REPLY, DEVICE_ID, &buffer_info, null(), buffer_out)
                },
                |d| unsafe { decode_vkCreateBuffer_reply(d, DEVICE_ID, &buffer_info, null(), buffer_out) },
            )?;
            made_buffer = true;
            let mut requirements: VkMemoryRequirements = zeroed();
            let mut d = self.call(COMMAND_VK_GET_BUFFER_MEMORY_REQUIREMENTS, |e| unsafe {
                encode_vkGetBufferMemoryRequirements(
                    e,
                    GENERATE_REPLY,
                    DEVICE_ID,
                    BUFFER_ID,
                    &mut requirements,
                )
            })?;
            unsafe {
                decode_vkGetBufferMemoryRequirements_reply(&mut d, DEVICE_ID, BUFFER_ID, &mut requirements)
            };
            // Host-visible and coherent, so the host's writes are the
            // window's without a flush.
            let visible = (VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) as u32;
            let kind = (0..memory_properties.memoryTypeCount.min(32))
                .find(|&i| {
                    requirements.memoryTypeBits & 1 << i != 0
                        && memory_properties.memoryTypes[i as usize].propertyFlags & visible == visible
                })
                .ok_or("no host-visible memory for the buffer")?;
            let mut allocate_info: VkMemoryAllocateInfo = zeroed();
            allocate_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
            allocate_info.allocationSize = FILL_SIZE;
            allocate_info.memoryTypeIndex = kind;
            let mut memory = MEMORY_ID;
            let memory_out = &raw mut memory;
            self.check(
                COMMAND_VK_ALLOCATE_MEMORY,
                "vkAllocateMemory failed on the host",
                |e| unsafe {
                    encode_vkAllocateMemory(e, GENERATE_REPLY, DEVICE_ID, &allocate_info, null(), memory_out)
                },
                |d| unsafe {
                    decode_vkAllocateMemory_reply(d, DEVICE_ID, &allocate_info, null(), memory_out)
                },
            )?;
            made_memory = true;
            self.check(
                COMMAND_VK_BIND_BUFFER_MEMORY,
                "vkBindBufferMemory failed on the host",
                |e| unsafe {
                    encode_vkBindBufferMemory(e, GENERATE_REPLY, DEVICE_ID, BUFFER_ID, MEMORY_ID, 0)
                },
                |d| unsafe { decode_vkBindBufferMemory_reply(d, DEVICE_ID, BUFFER_ID, MEMORY_ID, 0) },
            )?;

            // The memory, shared: a blob of it (its id the memory's).
            let (_, shared) = self
                .host
                .blob(MEMORY_ID, FILL_SIZE)
                .ok_or("the buffer's memory was not shared")?;
            let base = H::address(&shared);
            mapped = Some(shared);

            // A command buffer that fills the buffer.
            let mut pool_info: VkCommandPoolCreateInfo = zeroed();
            pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
            pool_info.queueFamilyIndex = family;
            let mut pool = POOL_ID;
            let pool_out = &raw mut pool;
            self.check(
                COMMAND_VK_CREATE_COMMAND_POOL,
                "vkCreateCommandPool failed on the host",
                |e| unsafe {
                    encode_vkCreateCommandPool(e, GENERATE_REPLY, DEVICE_ID, &pool_info, null(), pool_out)
                },
                |d| unsafe { decode_vkCreateCommandPool_reply(d, DEVICE_ID, &pool_info, null(), pool_out) },
            )?;
            made_pool = true;
            let mut allocate_info: VkCommandBufferAllocateInfo = zeroed();
            allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
            allocate_info.commandPool = POOL_ID;
            allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
            allocate_info.commandBufferCount = 1;
            let mut command_buffer = COMMAND_BUFFER_ID;
            let command_buffer_out = &raw mut command_buffer;
            self.check(
                COMMAND_VK_ALLOCATE_COMMAND_BUFFERS,
                "vkAllocateCommandBuffers failed on the host",
                |e| unsafe {
                    encode_vkAllocateCommandBuffers(
                        e,
                        GENERATE_REPLY,
                        DEVICE_ID,
                        &allocate_info,
                        command_buffer_out,
                    )
                },
                |d| unsafe {
                    decode_vkAllocateCommandBuffers_reply(d, DEVICE_ID, &allocate_info, command_buffer_out)
                },
            )?;
            let mut begin_info: VkCommandBufferBeginInfo = zeroed();
            begin_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
            begin_info.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT as u32;
            self.check(
                COMMAND_VK_BEGIN_COMMAND_BUFFER,
                "vkBeginCommandBuffer failed on the host",
                |e| unsafe { encode_vkBeginCommandBuffer(e, GENERATE_REPLY, COMMAND_BUFFER_ID, &begin_info) },
                |d| unsafe { decode_vkBeginCommandBuffer_reply(d, COMMAND_BUFFER_ID, &begin_info) },
            )?;
            let mut e = Encoder::default();
            unsafe { encode_vkCmdFillBuffer(&mut e, 0, COMMAND_BUFFER_ID, BUFFER_ID, 0, FILL_SIZE, FILL) };
            self.submit(&e)?;
            self.check(
                COMMAND_VK_END_COMMAND_BUFFER,
                "vkEndCommandBuffer failed on the host",
                |e| unsafe { encode_vkEndCommandBuffer(e, GENERATE_REPLY, COMMAND_BUFFER_ID) },
                |d| unsafe { decode_vkEndCommandBuffer_reply(d, COMMAND_BUFFER_ID) },
            )?;

            // Submitted with a fence, asked until signalled: Venus refuses a
            // call that would block the host (vkQueueWaitIdle ends the context).
            let mut fence_info: VkFenceCreateInfo = zeroed();
            fence_info.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
            let mut fence = FENCE_ID;
            let fence_out = &raw mut fence;
            self.check(
                COMMAND_VK_CREATE_FENCE,
                "vkCreateFence failed on the host",
                |e| unsafe {
                    encode_vkCreateFence(e, GENERATE_REPLY, DEVICE_ID, &fence_info, null(), fence_out)
                },
                |d| unsafe { decode_vkCreateFence_reply(d, DEVICE_ID, &fence_info, null(), fence_out) },
            )?;
            made_fence = true;
            let mut submit: VkSubmitInfo = zeroed();
            submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
            submit.commandBufferCount = 1;
            submit.pCommandBuffers = &command_buffer;
            self.check(
                COMMAND_VK_QUEUE_SUBMIT,
                "vkQueueSubmit failed on the host",
                |e| unsafe { encode_vkQueueSubmit(e, GENERATE_REPLY, QUEUE_ID, 1, &submit, FENCE_ID) },
                |d| unsafe { decode_vkQueueSubmit_reply(d, QUEUE_ID, 1, &submit, FENCE_ID) },
            )?;
            let deadline = self.host.now_ms() + 2000;
            loop {
                let mut d = self.call(COMMAND_VK_GET_FENCE_STATUS, |e| unsafe {
                    encode_vkGetFenceStatus(e, GENERATE_REPLY, DEVICE_ID, FENCE_ID)
                })?;
                match unsafe { decode_vkGetFenceStatus_reply(&mut d, DEVICE_ID, FENCE_ID) } {
                    VK_SUCCESS => break,
                    VK_NOT_READY if self.host.now_ms() < deadline => {}
                    VK_NOT_READY => return Err("the GPU did not finish the command"),
                    _ => return Err("vkGetFenceStatus failed on the host"),
                }
            }

            // What the GPU wrote, as this side sees it.
            let words = (FILL_SIZE / 4) as usize;
            let filled = (0..words)
                .filter(|&i| unsafe { ((base + 4 * i) as *const u32).read_volatile() } == FILL)
                .count();
            Ok(filled as u32 * 4)
        })();

        // Let go of what was made, the newest first; none of these replies.
        let mut e = Encoder::default();
        unsafe {
            if made_fence {
                encode_vkDestroyFence(&mut e, 0, DEVICE_ID, FENCE_ID, null());
            }
            if made_pool {
                encode_vkDestroyCommandPool(&mut e, 0, DEVICE_ID, POOL_ID, null());
            }
            if made_buffer {
                encode_vkDestroyBuffer(&mut e, 0, DEVICE_ID, BUFFER_ID, null());
            }
        }
        if let Some(shared) = mapped {
            self.host.free(shared);
        }
        unsafe {
            if made_memory {
                encode_vkFreeMemory(&mut e, 0, DEVICE_ID, MEMORY_ID, null());
            }
            encode_vkDestroyDevice(&mut e, 0, DEVICE_ID, null());
        }
        let _ = self.submit(&e);
        result
    }
}

/// Asks the host's Vulkan, through Venus, for its version, then makes an
/// instance, lists its physical devices and reads each one's properties,
/// and runs a first command on the first.
pub fn hello<H: Host>(host: &mut H) -> Result<Hello, &'static str> {
    // The reply stream: memory of Venus's own (blob 0).
    let (resource, memory) = host.blob(0, REPLY_SIZE).ok_or("no memory for the reply stream")?;
    let reply = H::address(&memory);
    let mut venus = Venus { host, reply };
    // SAFETY (all the encoders and decoders below): every pointer points at
    // a live local of the type the command takes, or is null.
    let result = (|| {
        let mut stream: VkCommandStreamDescriptionMESA = zeroed();
        stream.resourceId = resource;
        stream.size = REPLY_SIZE as usize;
        let mut e = Encoder::default();
        unsafe { encode_vkSetReplyCommandStreamMESA(&mut e, 0, &stream) };
        venus.submit(&e)?;

        let mut version = 0u32;
        let version_out = &raw mut version;
        venus.check(
            COMMAND_VK_ENUMERATE_INSTANCE_VERSION,
            "vkEnumerateInstanceVersion failed on the host",
            |e| unsafe { encode_vkEnumerateInstanceVersion(e, GENERATE_REPLY, version_out) },
            |d| unsafe { decode_vkEnumerateInstanceVersion_reply(d, version_out) },
        )?;

        // An instance: Vulkan 1.1, no layers or extensions.
        let mut app: VkApplicationInfo = zeroed();
        app.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
        app.pApplicationName = c"Pinnacle".as_ptr();
        app.apiVersion = 1 << 22 | 1 << 12;
        let mut create_info: VkInstanceCreateInfo = zeroed();
        create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
        create_info.pApplicationInfo = &app;
        let mut instance = INSTANCE_ID;
        let instance_out = &raw mut instance;
        venus.check(
            COMMAND_VK_CREATE_INSTANCE,
            "vkCreateInstance failed on the host",
            |e| unsafe { encode_vkCreateInstance(e, GENERATE_REPLY, &create_info, null(), instance_out) },
            |d| unsafe { decode_vkCreateInstance_reply(d, &create_info, null(), instance_out) },
        )?;

        let result = (|| {
            // Its physical devices: the count, then the devices under ids of
            // ours.
            let mut count = 0u32;
            let count_out = &raw mut count;
            venus.check(
                COMMAND_VK_ENUMERATE_PHYSICAL_DEVICES,
                "vkEnumeratePhysicalDevices failed on the host",
                |e| unsafe {
                    encode_vkEnumeratePhysicalDevices(e, GENERATE_REPLY, INSTANCE_ID, count_out, null_mut())
                },
                |d| unsafe { decode_vkEnumeratePhysicalDevices_reply(d, INSTANCE_ID, count_out, null_mut()) },
            )?;
            let mut physical: Vec<VkPhysicalDevice> = (0..count.min(MAX_PHYSICAL_DEVICES) as u64)
                .map(|i| PHYSICAL_DEVICE_IDS + i)
                .collect();
            let mut count = physical.len() as u32;
            let mut d = venus.call(COMMAND_VK_ENUMERATE_PHYSICAL_DEVICES, |e| unsafe {
                encode_vkEnumeratePhysicalDevices(
                    e,
                    GENERATE_REPLY,
                    INSTANCE_ID,
                    &mut count,
                    physical.as_mut_ptr(),
                )
            })?;
            // VK_INCOMPLETE when there were more than asked for.
            let ret = unsafe {
                decode_vkEnumeratePhysicalDevices_reply(
                    &mut d,
                    INSTANCE_ID,
                    &mut count,
                    physical.as_mut_ptr(),
                )
            };
            if !matches!(ret, VK_SUCCESS | VK_INCOMPLETE) || d.fatal {
                return Err("vkEnumeratePhysicalDevices failed on the host");
            }
            physical.truncate(count as usize);

            let mut devices = Vec::new();
            for &device in &physical {
                let mut properties: VkPhysicalDeviceProperties = zeroed();
                let mut d = venus.call(COMMAND_VK_GET_PHYSICAL_DEVICE_PROPERTIES, |e| unsafe {
                    encode_vkGetPhysicalDeviceProperties(e, GENERATE_REPLY, device, &mut properties)
                })?;
                unsafe { decode_vkGetPhysicalDeviceProperties_reply(&mut d, device, &mut properties) };
                // c_char is u8 on ARM, i8 on a PC: its byte either way.
                let raw = properties.deviceName.map(|c| c.to_ne_bytes()[0]);
                let len = raw.iter().position(|&b| b == 0).unwrap_or(raw.len());
                let name = String::from_utf8_lossy(&raw[..len]).into_owned();
                devices.push((
                    name,
                    properties.vendorID,
                    properties.deviceID,
                    properties.deviceType as u32,
                ));
            }
            // A first command, on the first GPU.
            let filled = match physical.first() {
                Some(&first) => venus.fill(first)?,
                None => 0,
            };
            Ok((devices, filled))
        })();
        let mut e = Encoder::default();
        unsafe { encode_vkDestroyInstance(&mut e, 0, INSTANCE_ID, null()) };
        let _ = venus.submit(&e);
        let (devices, filled) = result?;
        Ok(Hello {
            version,
            devices,
            filled,
        })
    })();
    venus.host.free(memory);
    result
}