Runtime: read the loader's instance extensions once per instance

The making of an instance asked the loader for its instance extension list
once per question: portability enumeration, debug utils and layer settings,
three vkEnumerateInstanceExtensionProperties calls, and the drivers' keeper
asked a fourth time for portability on the process's first device. Each such
call makes the loader scan its driver and layer manifests again and ask each
driver it finds; reims measured about 7 s per process on a host with several
manifests.

Now the making reads the list once (ListedExtensions) and answers every
question from it, and the keeper takes portability from the extensions the
device's instance enabled (the runtime enables it exactly where the loader
listed it), asking the loader nothing: four reads per process's first device
become one, and three per later instance become one.

Verified: tests::listed_extensions builds a fake loader that counts the reads
and refuses the instance; it reads 1 at this commit (3 before it, the
negative control).

(cherry picked from commit a58d2cd51a2fbe17326ce09c8a718ffec5d43776)
This commit is contained in:
Anees Iqbal committed 2026-11-09 23:30:14 -08:00
1 parent 4d187515d7
commit 5c0c2236ad
4 files changed
+184 -33

No files matched your search

@@ -641,19 +641,27 @@ pub(super) unsafe extern "system" fn deliver(
vk::FALSE
}
/// Whether `entry`'s loader lists `VK_KHR_portability_enumeration`.
pub(super) fn lists_portability(entry: &ash::Entry) -> Result<bool, Error> {
lists_instance_extension(entry, ash::khr::portability_enumeration::NAME)
}
/// The instance extensions a loader lists, read with one `vkEnumerateInstanceExtensionProperties`:
/// the loader scans its driver and layer manifests again at each such call, and asks each driver
/// it finds, so the making of an instance reads the list once and answers every question of it
/// from this.
pub(crate) struct ListedExtensions(Vec<vk::ExtensionProperties>);
/// Whether the loader lists the instance extension `name`.
fn lists_instance_extension(entry: &ash::Entry, name: &CStr) -> Result<bool, Error> {
// SAFETY: a global command of a loaded entry.
let available =
unsafe { entry.enumerate_instance_extension_properties(None) }.map_err(vulkan)?;
Ok(available
.iter()
.any(|extension| extension.extension_name_as_c_str() == Ok(name)))
impl ListedExtensions {
/// The instance extensions `entry`'s loader lists.
pub(crate) fn of(entry: &ash::Entry) -> Result<ListedExtensions, Error> {
// SAFETY: a global command of a loaded entry.
let listed =
unsafe { entry.enumerate_instance_extension_properties(None) }.map_err(vulkan)?;
Ok(ListedExtensions(listed))
}
/// Whether the loader listed the instance extension `name`.
pub(crate) fn lists(&self, name: &CStr) -> bool {
self.0
.iter()
.any(|extension| extension.extension_name_as_c_str() == Ok(name))
}
}
/// The instance API version `requested` asks for (`DeviceOptions::instance_api_version`):
@@ -742,22 +750,31 @@ pub(super) unsafe fn new_instance(
/// The instance of `options`.
fn create_instance(options: &DeviceOptions) -> Result<Arc<InstanceShared>, Error> {
let entry = open_loader(options.loader.as_deref())?;
let portability = lists_portability(&entry)?;
instance_of(open_loader(options.loader.as_deref())?, options)
}
/// The instance of `options` from the loader `entry`, which lists its instance extensions once
/// ([`ListedExtensions`]).
pub(crate) fn instance_of(
entry: ash::Entry,
options: &DeviceOptions,
) -> Result<Arc<InstanceShared>, Error> {
let listed = ListedExtensions::of(&entry)?;
let portability = listed.lists(ash::khr::portability_enumeration::NAME);
let mut extensions: Vec<&CStr> = Vec::new();
if portability {
extensions.push(ash::khr::portability_enumeration::NAME);
}
// The relay of a driver's command-buffer failures needs a messenger of its own
// (`relay.rs`): debug utils wherever the instance lists them.
let relays = lists_instance_extension(&entry, ash::ext::debug_utils::NAME)?;
let relays = listed.lists(ash::ext::debug_utils::NAME);
if options.messages.is_some() || relays {
extensions.push(ash::ext::debug_utils::NAME);
}
// MoltenVK's Metal argument buffers, asked for where the instance can take layer settings,
// ahead of the consumer's own, which win (`argument_buffers.rs`); and, where the relay hears
// its failures, that it keep a device after a command buffer fails (`relay.rs`).
let asks = lists_instance_extension(&entry, ash::ext::layer_settings::NAME)?;
let asks = listed.lists(ash::ext::layer_settings::NAME);
let chained_settings: Vec<LayerSetting> = asks
.then(super::argument_buffers::setting)
.into_iter()
@@ -2194,7 +2211,7 @@ impl Device {
for physical in ranked(&instance, options)? {
match device_of(&mut made[at], &instance, physical, options, &cache) {
Ok(device) => {
keep_drivers_loaded(&instance.entry);
keep_drivers_loaded(&instance);
return Ok(device);
}
Err(error) => {
@@ -2298,7 +2315,7 @@ impl Device {
return Err(Error::NoDevice);
};
let device = device_of(&mut made[at], &instance, physical, options, &cache)?;
keep_drivers_loaded(&instance.entry);
keep_drivers_loaded(&instance);
Ok(device)
}
@@ -2327,7 +2344,7 @@ impl Device {
}
}
if !devices.is_empty() {
keep_drivers_loaded(&instance.entry);
keep_drivers_loaded(&instance);
}
Ok(devices)
}
@@ -10,13 +10,14 @@
//! anyway.
//!
//! The keeper is bare: no layers, no messenger, and no extension but
//! `VK_KHR_portability_enumeration` where the loader lists it (without it, a loader that sees only
//! a portability driver refuses the instance). Nothing is made from it and it is never
//! destroyed. It is made only after a device was made, while that device's instance is alive, so
//! it loads no driver itself; adopted devices never make one.
//! `VK_KHR_portability_enumeration` where the device's instance enabled it, which the runtime does
//! where the loader lists it (without it, a loader that sees only a portability driver refuses the
//! instance): the keeper asks the loader nothing of its own. Nothing is made from it and it is
//! never destroyed. It is made only after a device was made, while that device's instance is
//! alive, so it loads no driver itself; adopted devices never make one.
use super::create::{lists_portability, new_instance};
use super::lock;
use super::create::new_instance;
use super::{lock, InstanceShared};
use ash::vk;
use std::sync::Mutex;
@@ -71,13 +72,18 @@ struct Keeper {
/// library for the life of the process.
static KEEPERS: Kept<usize, Keeper> = Kept::new();
/// Keep the drivers `entry`'s loader library loaded for the life of the process. Called after a
/// device was made from an instance of `entry`, while that instance is alive. A keeper that
/// cannot be made leaves the device as it is, and the next device tries again.
pub(super) fn keep_drivers_loaded(entry: &ash::Entry) {
/// Keep the drivers of `instance`'s loader library loaded for the life of the process. Called
/// after a device was made from `instance`, which the runtime created, while it is alive. A keeper
/// that cannot be made leaves the device as it is, and the next device tries again.
pub(super) fn keep_drivers_loaded(instance: &InstanceShared) {
let entry = &instance.entry;
let library = entry.static_fn().get_instance_proc_addr as usize;
let portability = instance
.extensions
.iter()
.any(|name| name.as_c_str() == ash::khr::portability_enumeration::NAME);
KEEPERS.keep(library, || {
let instance = bare_instance(entry)?;
let instance = bare_instance(entry, portability)?;
Some(Keeper {
_entry: entry.clone(),
_instance: instance,
@@ -85,9 +91,9 @@ pub(super) fn keep_drivers_loaded(entry: &ash::Entry) {
});
}
/// A bare instance of `entry`: no layers, no messenger, portability enumeration where listed.
fn bare_instance(entry: &ash::Entry) -> Option<vk::Instance> {
let portability = lists_portability(entry).ok()?;
/// A bare instance of `entry`: no layers, no messenger, portability enumeration where
/// `portability` says the device's instance enabled it.
fn bare_instance(entry: &ash::Entry, portability: bool) -> Option<vk::Instance> {
let extensions = [ash::khr::portability_enumeration::NAME.as_ptr()];
let application = vk::ApplicationInfo::default()
.engine_name(c"metal2vulkan")
@@ -0,0 +1,127 @@
//! `device/create.rs`: the making of an instance reads the loader's instance extensions once
//! (`ListedExtensions`), whatever it asks of them. Each `vkEnumerateInstanceExtensionProperties`
//! makes the loader scan its driver and layer manifests again and ask each driver it finds, so a
//! read per question multiplied that cost by the questions asked. A fake loader counts the reads
//! and refuses the instance, so no driver and no device take part.
use crate::device::create::instance_of;
use crate::{DeviceOptions, Error};
use ash::vk;
use std::ffi::{c_char, CStr};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
/// The instance extensions the fake loader lists: each one the making asks about.
const LISTED: [&CStr; 3] = [
ash::khr::portability_enumeration::NAME,
ash::ext::debug_utils::NAME,
ash::ext::layer_settings::NAME,
];
/// The fake loader's reads of its instance extensions: the calls that ask for their count, the
/// first of each two-call read.
static READS: AtomicUsize = AtomicUsize::new(0);
/// The instance extensions the fake loader's `vkCreateInstance` was asked to enable.
static ENABLED: Mutex<Vec<String>> = Mutex::new(Vec::new());
/// `vkEnumerateInstanceExtensionProperties`: [`LISTED`], counted in [`READS`].
unsafe extern "system" fn enumerate_instance_extension_properties(
_layer: *const c_char,
count: *mut u32,
properties: *mut vk::ExtensionProperties,
) -> vk::Result {
if properties.is_null() {
READS.fetch_add(1, Ordering::SeqCst);
// SAFETY: the caller's count, written once.
unsafe { count.write(LISTED.len() as u32) };
return vk::Result::SUCCESS;
}
// SAFETY: the caller's count, which says how many properties `properties` has room for.
let room = unsafe { count.read() } as usize;
let written = room.min(LISTED.len());
for (at, name) in LISTED.iter().take(written).enumerate() {
let property = vk::ExtensionProperties::default()
.extension_name(name)
.expect("an extension name fits");
// SAFETY: `at` is below the room the caller gave.
unsafe { properties.add(at).write(property) };
}
// SAFETY: the caller's count.
unsafe { count.write(written as u32) };
if written < LISTED.len() {
vk::Result::INCOMPLETE
} else {
vk::Result::SUCCESS
}
}
/// `vkCreateInstance`: records the extensions asked for in [`ENABLED`], and refuses the instance as
/// a loader with no driver does.
unsafe extern "system" fn create_instance(
info: *const vk::InstanceCreateInfo<'_>,
_allocator: *const vk::AllocationCallbacks<'_>,
_instance: *mut vk::Instance,
) -> vk::Result {
// SAFETY: the caller's create info, live for the call.
let info = unsafe { &*info };
let names = (0..info.enabled_extension_count as usize).map(|at| {
// SAFETY: `at` is below the count of NUL-terminated names the create info points at.
let name = unsafe { CStr::from_ptr(*info.pp_enabled_extension_names.add(at)) };
name.to_string_lossy().into_owned()
});
*ENABLED.lock().unwrap() = names.collect();
vk::Result::ERROR_INCOMPATIBLE_DRIVER
}
/// The fake loader's `vkGetInstanceProcAddr`: the two global commands above, and nothing else.
unsafe extern "system" fn get_instance_proc_addr(
_instance: vk::Instance,
name: *const c_char,
) -> vk::PFN_vkVoidFunction {
// SAFETY: the caller names an entry point with a NUL-terminated string.
let name = unsafe { CStr::from_ptr(name) }.to_bytes();
// SAFETY (both arms): the caller casts the pointer back to the named entry point's type,
// which is the type of the function returned.
match name {
b"vkEnumerateInstanceExtensionProperties" => Some(unsafe {
std::mem::transmute::<
vk::PFN_vkEnumerateInstanceExtensionProperties,
unsafe extern "system" fn(),
>(enumerate_instance_extension_properties)
}),
b"vkCreateInstance" => Some(unsafe {
std::mem::transmute::<vk::PFN_vkCreateInstance, unsafe extern "system" fn()>(
create_instance,
)
}),
_ => None,
}
}
#[test]
fn an_instance_reads_the_loaders_extensions_once() {
let static_fn = ash::StaticFn {
get_instance_proc_addr,
};
// SAFETY: the fake answers the global commands the making calls; ash's stand-in for any other
// panics if called.
let entry = unsafe { ash::Entry::from_static_fn(static_fn) };
match instance_of(entry, &DeviceOptions::default()) {
Err(Error::NoDevice) => {}
Err(other) => panic!("the fake loader's refusal became {other}"),
Ok(_) => panic!("the fake loader made an instance"),
}
assert_eq!(
READS.load(Ordering::SeqCst),
1,
"the making read the loader's instance extensions more than once"
);
// Every question was asked, and answered from the one read: each listed extension the
// making enables where listed was asked for.
let enabled = ENABLED.lock().unwrap().clone();
for name in LISTED {
let name = name.to_string_lossy().into_owned();
assert!(enabled.contains(&name), "{name} not enabled: {enabled:?}");
}
}
@@ -291,6 +291,7 @@ mod linear_plan;
mod linear_runs;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod linked_pipelines_shared;
mod listed_extensions;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod mac_class;
mod making;