atagen

monolith

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