atagen

monolith

public
Star0
Watch0
5cd954fce34b6d52c70fde84e2baab0c8df4ad0a
1
ssh://brewery@pls.lobotomise.me:33/atagen/monolith.git
crates/render-vk/src/device.rsRust221 lines8.4 KB
1
use crate::Error;
2
use ash::vk;
3
use gpu_allocator::vulkan::{Allocator, AllocatorCreateDesc};
4
use std::sync::Mutex;
5
6
/// Everything that must outlive every Vulkan object the renderer hands out.
7
/// Fields drop in declaration order, so the allocator frees its memory before
8
/// the device is destroyed.
9
pub(crate) struct Shared {
10
    pub allocator: Mutex<Allocator>,
11
    pub device: Device,
12
}
13
14
/// Loaders for the extensions that dmabuf import, export and fence export
15
/// need. Absent when the device lacks any of them.
16
pub(crate) struct DmabufExt {
17
    pub memory_fd: ash::khr::external_memory_fd::Device,
18
    pub fence_fd: ash::khr::external_fence_fd::Device,
19
    pub modifier: ash::ext::image_drm_format_modifier::Device,
20
}
21
22
const DMABUF_EXTENSIONS: [&std::ffi::CStr; 5] = [
23
    ash::khr::external_memory_fd::NAME,
24
    ash::ext::external_memory_dma_buf::NAME,
25
    ash::ext::image_drm_format_modifier::NAME,
26
    ash::ext::queue_family_foreign::NAME,
27
    ash::khr::external_fence_fd::NAME,
28
];
29
30
pub(crate) struct Device {
31
    pub _entry: ash::Entry,
32
    pub instance: ash::Instance,
33
    pub physical: vk::PhysicalDevice,
34
    pub device: ash::Device,
35
    pub queue: Mutex<vk::Queue>,
36
    pub queue_family: u32,
37
    pub push_descriptor: ash::khr::push_descriptor::Device,
38
    pub dmabuf: Option<DmabufExt>,
39
    pub name: String,
40
    /// Signalled fences kept for reuse, see `FenceInner`.
41
    pub spare_fences: Mutex<Vec<vk::Fence>>,
42
}
43
44
impl Drop for Device {
45
    fn drop(&mut self) {
46
        unsafe {
47
            let _ = self.device.device_wait_idle();
48
            for f in self
49
                .spare_fences
50
                .get_mut()
51
                .unwrap_or_else(|e| e.into_inner())
52
                .drain(..)
53
            {
54
                self.device.destroy_fence(f, None);
55
            }
56
            self.device.destroy_device(None);
57
            self.instance.destroy_instance(None);
58
        }
59
    }
60
}
61
62
impl Shared {
63
    /// Opens the first suitable device, or the one whose name contains
64
    /// `MONOLITH_VK_DEVICE` when that is set. With `node`, only the device
65
    /// behind that DRM device number qualifies.
66
    pub fn new(node: Option<u64>) -> Result<Self, Error> {
67
        let entry = unsafe { ash::Entry::load()? };
68
        let app = vk::ApplicationInfo::default()
69
            .application_name(c"monolith")
70
            .engine_name(c"monolith")
71
            .api_version(vk::API_VERSION_1_3);
72
        let instance = unsafe {
73
            entry.create_instance(
74
                &vk::InstanceCreateInfo::default().application_info(&app),
75
                None,
76
            )?
77
        };
78
        let wanted = std::env::var("MONOLITH_VK_DEVICE").ok();
79
        let picked = unsafe { pick_physical(&instance, wanted.as_deref(), node) };
80
        let Some((physical, queue_family, name)) = picked else {
81
            unsafe { instance.destroy_instance(None) };
82
            return Err(Error::NoSuitableDevice);
83
        };
84
        let priorities = [1.0];
85
        let queues = [vk::DeviceQueueCreateInfo::default()
86
            .queue_family_index(queue_family)
87
            .queue_priorities(&priorities)];
88
        let available: Vec<_> = unsafe { instance.enumerate_device_extension_properties(physical) }
89
            .unwrap_or_default()
90
            .iter()
91
            .filter_map(|e| e.extension_name_as_c_str().ok().map(ToOwned::to_owned))
92
            .collect();
93
        let has_dmabuf = DMABUF_EXTENSIONS
94
            .iter()
95
            .all(|n| available.iter().any(|a| a.as_c_str() == *n));
96
        let mut extensions = vec![ash::khr::push_descriptor::NAME.as_ptr()];
97
        if has_dmabuf {
98
            extensions.extend(DMABUF_EXTENSIONS.iter().map(|n| n.as_ptr()));
99
        }
100
        let mut features13 = vk::PhysicalDeviceVulkan13Features::default()
101
            .dynamic_rendering(true)
102
            .synchronization2(true);
103
        let info = vk::DeviceCreateInfo::default()
104
            .queue_create_infos(&queues)
105
            .enabled_extension_names(&extensions)
106
            .push_next(&mut features13);
107
        let device = match unsafe { instance.create_device(physical, &info, None) } {
108
            Ok(d) => d,
109
            Err(e) => {
110
                unsafe { instance.destroy_instance(None) };
111
                return Err(e.into());
112
            }
113
        };
114
        let queue = unsafe { device.get_device_queue(queue_family, 0) };
115
        let push_descriptor = ash::khr::push_descriptor::Device::new(&instance, &device);
116
        let dmabuf = has_dmabuf.then(|| DmabufExt {
117
            memory_fd: ash::khr::external_memory_fd::Device::new(&instance, &device),
118
            fence_fd: ash::khr::external_fence_fd::Device::new(&instance, &device),
119
            modifier: ash::ext::image_drm_format_modifier::Device::new(&instance, &device),
120
        });
121
        let allocator = Allocator::new(&AllocatorCreateDesc {
122
            instance: instance.clone(),
123
            device: device.clone(),
124
            physical_device: physical,
125
            debug_settings: Default::default(),
126
            buffer_device_address: false,
127
            allocation_sizes: Default::default(),
128
        });
129
        let device = Device {
130
            _entry: entry,
131
            instance,
132
            physical,
133
            device,
134
            queue: Mutex::new(queue),
135
            queue_family,
136
            push_descriptor,
137
            dmabuf,
138
            name,
139
            spare_fences: Mutex::new(Vec::new()),
140
        };
141
        Ok(Self {
142
            allocator: Mutex::new(allocator?),
143
            device,
144
        })
145
    }
146
}
147
148
/// Whether `physical` is the device behind DRM device number `node`, as its
149
/// primary or render node.
150
unsafe fn serves_node(instance: &ash::Instance, physical: vk::PhysicalDevice, node: u64) -> bool {
151
    let mut drm = vk::PhysicalDeviceDrmPropertiesEXT::default();
152
    let mut props = vk::PhysicalDeviceProperties2::default().push_next(&mut drm);
153
    unsafe { instance.get_physical_device_properties2(physical, &mut props) };
154
    let (major, minor) = (
155
        rustix::fs::major(node) as i64,
156
        rustix::fs::minor(node) as i64,
157
    );
158
    (drm.has_primary == vk::TRUE && (drm.primary_major, drm.primary_minor) == (major, minor))
159
        || (drm.has_render == vk::TRUE && (drm.render_major, drm.render_minor) == (major, minor))
160
}
161
162
unsafe fn pick_physical(
163
    instance: &ash::Instance,
164
    wanted: Option<&str>,
165
    node: Option<u64>,
166
) -> Option<(vk::PhysicalDevice, u32, String)> {
167
    let devices = unsafe { instance.enumerate_physical_devices() }.ok()?;
168
    let mut candidates = Vec::new();
169
    for physical in devices {
170
        let props = unsafe { instance.get_physical_device_properties(physical) };
171
        if props.api_version < vk::API_VERSION_1_3 {
172
            continue;
173
        }
174
        let name = props
175
            .device_name_as_c_str()
176
            .unwrap_or(c"unknown")
177
            .to_string_lossy()
178
            .into_owned();
179
        if wanted.is_some_and(|w| !name.contains(w)) {
180
            continue;
181
        }
182
        let mut f13 = vk::PhysicalDeviceVulkan13Features::default();
183
        let mut f2 = vk::PhysicalDeviceFeatures2::default().push_next(&mut f13);
184
        unsafe { instance.get_physical_device_features2(physical, &mut f2) };
185
        if f13.dynamic_rendering == vk::FALSE || f13.synchronization2 == vk::FALSE {
186
            continue;
187
        }
188
        let extensions =
189
            unsafe { instance.enumerate_device_extension_properties(physical) }.unwrap_or_default();
190
        let has = |n: &std::ffi::CStr| {
191
            extensions
192
                .iter()
193
                .any(|e| e.extension_name_as_c_str().ok() == Some(n))
194
        };
195
        if !has(ash::khr::push_descriptor::NAME) {
196
            continue;
197
        }
198
        if let Some(node) = node
199
            && !(has(ash::ext::physical_device_drm::NAME)
200
                && unsafe { serves_node(instance, physical, node) })
201
        {
202
            continue;
203
        }
204
        let families = unsafe { instance.get_physical_device_queue_family_properties(physical) };
205
        let Some(family) = families
206
            .iter()
207
            .position(|f| f.queue_flags.contains(vk::QueueFlags::GRAPHICS))
208
        else {
209
            continue;
210
        };
211
        let rank = match props.device_type {
212
            vk::PhysicalDeviceType::DISCRETE_GPU => 0,
213
            vk::PhysicalDeviceType::INTEGRATED_GPU => 1,
214
            vk::PhysicalDeviceType::VIRTUAL_GPU => 2,
215
            _ => 3,
216
        };
217
        candidates.push((rank, physical, family as u32, name));
218
    }
219
    candidates.sort_by_key(|c| c.0);
220
    candidates.into_iter().next().map(|(_, p, f, n)| (p, f, n))
221
}