| 1 | use crate::Error; |
| 2 | use crate::device::Shared; |
| 3 | use crate::format::{components, vk_format}; |
| 4 | use ash::vk; |
| 5 | use gpu_allocator::MemoryLocation; |
| 6 | use gpu_allocator::vulkan::{Allocation, AllocationCreateDesc, AllocationScheme}; |
| 7 | use smithay::backend::allocator::Fourcc; |
| 8 | use smithay::backend::renderer::{Texture, TextureMapping}; |
| 9 | use std::fmt; |
| 10 | use std::marker::PhantomData; |
| 11 | use std::sync::{Arc, Mutex}; |
| 12 | use std::time::{Duration, Instant}; |
| 13 | |
| 14 | pub(crate) enum Memory { |
| 15 | Allocated(Allocation), |
| 16 | /// Memory imported from a dmabuf, owned directly. |
| 17 | Imported(vk::DeviceMemory), |
| 18 | } |
| 19 | |
| 20 | pub(crate) struct ImageInner { |
| 21 | pub shared: Arc<Shared>, |
| 22 | pub image: vk::Image, |
| 23 | pub view: vk::ImageView, |
| 24 | pub memory: Mutex<Option<Memory>>, |
| 25 | pub fourcc: Fourcc, |
| 26 | pub format: vk::Format, |
| 27 | pub width: u32, |
| 28 | pub height: u32, |
| 29 | pub layout: Mutex<vk::ImageLayout>, |
| 30 | /// Shared with other devices or processes through a dmabuf. Every use |
| 31 | /// acquires the image from the foreign queue family and releases it after. |
| 32 | pub external: bool, |
| 33 | } |
| 34 | |
| 35 | impl fmt::Debug for ImageInner { |
| 36 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 37 | f.debug_struct("ImageInner") |
| 38 | .field("image", &self.image) |
| 39 | .field("fourcc", &self.fourcc) |
| 40 | .field("size", &(self.width, self.height)) |
| 41 | .field("external", &self.external) |
| 42 | .finish() |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl Drop for ImageInner { |
| 47 | fn drop(&mut self) { |
| 48 | let d = &self.shared.device.device; |
| 49 | unsafe { |
| 50 | d.destroy_image_view(self.view, None); |
| 51 | d.destroy_image(self.image, None); |
| 52 | } |
| 53 | match self.memory.lock().unwrap_or_else(|e| e.into_inner()).take() { |
| 54 | Some(Memory::Allocated(a)) => { |
| 55 | let _ = self |
| 56 | .shared |
| 57 | .allocator |
| 58 | .lock() |
| 59 | .unwrap_or_else(|e| e.into_inner()) |
| 60 | .free(a); |
| 61 | } |
| 62 | Some(Memory::Imported(m)) => unsafe { d.free_memory(m, None) }, |
| 63 | None => {} |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | impl ImageInner { |
| 69 | pub fn create( |
| 70 | shared: &Arc<Shared>, |
| 71 | fourcc: Fourcc, |
| 72 | width: u32, |
| 73 | height: u32, |
| 74 | usage: vk::ImageUsageFlags, |
| 75 | ) -> Result<Arc<Self>, Error> { |
| 76 | let fmt = vk_format(fourcc).ok_or(Error::UnsupportedFormat(fourcc))?; |
| 77 | if width == 0 || height == 0 { |
| 78 | return Err(Error::InvalidSize(width as i32, height as i32)); |
| 79 | } |
| 80 | let d = &shared.device.device; |
| 81 | let info = vk::ImageCreateInfo::default() |
| 82 | .image_type(vk::ImageType::TYPE_2D) |
| 83 | .format(fmt.format) |
| 84 | .extent(vk::Extent3D { |
| 85 | width, |
| 86 | height, |
| 87 | depth: 1, |
| 88 | }) |
| 89 | .mip_levels(1) |
| 90 | .array_layers(1) |
| 91 | .samples(vk::SampleCountFlags::TYPE_1) |
| 92 | .tiling(vk::ImageTiling::OPTIMAL) |
| 93 | .usage(usage) |
| 94 | .initial_layout(vk::ImageLayout::UNDEFINED); |
| 95 | let image = unsafe { d.create_image(&info, None)? }; |
| 96 | let requirements = unsafe { d.get_image_memory_requirements(image) }; |
| 97 | let allocation = shared |
| 98 | .allocator |
| 99 | .lock() |
| 100 | .unwrap_or_else(|e| e.into_inner()) |
| 101 | .allocate(&AllocationCreateDesc { |
| 102 | name: "image", |
| 103 | requirements, |
| 104 | location: MemoryLocation::GpuOnly, |
| 105 | linear: false, |
| 106 | allocation_scheme: AllocationScheme::GpuAllocatorManaged, |
| 107 | }); |
| 108 | let allocation = match allocation { |
| 109 | Ok(a) => a, |
| 110 | Err(e) => { |
| 111 | unsafe { d.destroy_image(image, None) }; |
| 112 | return Err(e.into()); |
| 113 | } |
| 114 | }; |
| 115 | let memory = Memory::Allocated(allocation); |
| 116 | let (mem, offset) = match &memory { |
| 117 | Memory::Allocated(a) => (unsafe { a.memory() }, a.offset()), |
| 118 | Memory::Imported(m) => (*m, 0), |
| 119 | }; |
| 120 | Self::finish( |
| 121 | shared, image, memory, mem, offset, fourcc, width, height, false, |
| 122 | ) |
| 123 | } |
| 124 | |
| 125 | /// Binds memory, creates the view and wraps everything up. Takes |
| 126 | /// ownership of `image` and `memory`, releasing both on failure. |
| 127 | #[expect(clippy::too_many_arguments)] |
| 128 | pub fn finish( |
| 129 | shared: &Arc<Shared>, |
| 130 | image: vk::Image, |
| 131 | memory: Memory, |
| 132 | mem: vk::DeviceMemory, |
| 133 | offset: u64, |
| 134 | fourcc: Fourcc, |
| 135 | width: u32, |
| 136 | height: u32, |
| 137 | external: bool, |
| 138 | ) -> Result<Arc<Self>, Error> { |
| 139 | let fmt = vk_format(fourcc).ok_or(Error::UnsupportedFormat(fourcc))?; |
| 140 | let d = &shared.device.device; |
| 141 | let mut inner = Self { |
| 142 | shared: shared.clone(), |
| 143 | image, |
| 144 | view: vk::ImageView::null(), |
| 145 | memory: Mutex::new(Some(memory)), |
| 146 | fourcc, |
| 147 | format: fmt.format, |
| 148 | width, |
| 149 | height, |
| 150 | layout: Mutex::new(if external { |
| 151 | vk::ImageLayout::GENERAL |
| 152 | } else { |
| 153 | vk::ImageLayout::UNDEFINED |
| 154 | }), |
| 155 | external, |
| 156 | }; |
| 157 | unsafe { d.bind_image_memory(image, mem, offset)? }; |
| 158 | let view_info = vk::ImageViewCreateInfo::default() |
| 159 | .image(image) |
| 160 | .view_type(vk::ImageViewType::TYPE_2D) |
| 161 | .format(fmt.format) |
| 162 | .components(components(fmt.opaque)) |
| 163 | .subresource_range(color_range()); |
| 164 | inner.view = unsafe { d.create_image_view(&view_info, None)? }; |
| 165 | Ok(Arc::new(inner)) |
| 166 | } |
| 167 | |
| 168 | pub fn layout(&self) -> vk::ImageLayout { |
| 169 | *self.layout.lock().unwrap_or_else(|e| e.into_inner()) |
| 170 | } |
| 171 | |
| 172 | pub fn set_layout(&self, layout: vk::ImageLayout) { |
| 173 | *self.layout.lock().unwrap_or_else(|e| e.into_inner()) = layout; |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | pub(crate) fn color_range() -> vk::ImageSubresourceRange { |
| 178 | vk::ImageSubresourceRange::default() |
| 179 | .aspect_mask(vk::ImageAspectFlags::COLOR) |
| 180 | .level_count(1) |
| 181 | .layer_count(1) |
| 182 | } |
| 183 | |
| 184 | /// A host-visible buffer for uploads and readbacks. Dropped ones go back to |
| 185 | /// a pool on `Shared` instead of being freed. Allocating and freeing large |
| 186 | /// host-visible memory takes a driver lock on NVIDIA that `vkQueueSubmit` |
| 187 | /// also waits on, so a staging buffer made per upload on the import worker |
| 188 | /// stalled the main thread's submits for 1 to 3 ms. |
| 189 | pub(crate) struct Staging { |
| 190 | pub shared: Arc<Shared>, |
| 191 | pub buffer: vk::Buffer, |
| 192 | pub allocation: Option<Allocation>, |
| 193 | size: usize, |
| 194 | usage: vk::BufferUsageFlags, |
| 195 | location: MemoryLocation, |
| 196 | } |
| 197 | |
| 198 | pub(crate) struct Pooled { |
| 199 | pub buffer: vk::Buffer, |
| 200 | pub allocation: Allocation, |
| 201 | size: usize, |
| 202 | usage: vk::BufferUsageFlags, |
| 203 | location: MemoryLocation, |
| 204 | returned: Instant, |
| 205 | } |
| 206 | |
| 207 | /// Pooled staging memory kept at most, past which dropped buffers are freed. |
| 208 | const POOL_BYTES: usize = 32 * 1024 * 1024; |
| 209 | |
| 210 | /// How long a pooled buffer may go unused before it is freed. |
| 211 | const POOL_IDLE: Duration = Duration::from_secs(2); |
| 212 | |
| 213 | /// Frees pooled staging buffers that have sat unused for [`POOL_IDLE`]. |
| 214 | pub(crate) fn trim_staging(shared: &Shared) { |
| 215 | let now = Instant::now(); |
| 216 | let expired: Vec<Pooled> = { |
| 217 | let mut pool = shared |
| 218 | .staging_pool |
| 219 | .lock() |
| 220 | .unwrap_or_else(|e| e.into_inner()); |
| 221 | let (stale, kept) = std::mem::take(&mut *pool) |
| 222 | .into_iter() |
| 223 | .partition(|p| now - p.returned >= POOL_IDLE); |
| 224 | *pool = kept; |
| 225 | stale |
| 226 | }; |
| 227 | if expired.is_empty() { |
| 228 | return; |
| 229 | } |
| 230 | let mut allocator = shared.allocator.lock().unwrap_or_else(|e| e.into_inner()); |
| 231 | for p in expired { |
| 232 | unsafe { shared.device.device.destroy_buffer(p.buffer, None) }; |
| 233 | let _ = allocator.free(p.allocation); |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | impl Staging { |
| 238 | pub fn new( |
| 239 | shared: &Arc<Shared>, |
| 240 | size: usize, |
| 241 | usage: vk::BufferUsageFlags, |
| 242 | location: MemoryLocation, |
| 243 | ) -> Result<Self, Error> { |
| 244 | let reused = { |
| 245 | let mut pool = shared |
| 246 | .staging_pool |
| 247 | .lock() |
| 248 | .unwrap_or_else(|e| e.into_inner()); |
| 249 | let fits = |p: &Pooled| { |
| 250 | p.usage == usage && p.location == location && p.size >= size && p.size <= size * 2 |
| 251 | }; |
| 252 | pool.iter().position(fits).map(|i| pool.swap_remove(i)) |
| 253 | }; |
| 254 | if let Some(p) = reused { |
| 255 | return Ok(Self { |
| 256 | shared: shared.clone(), |
| 257 | buffer: p.buffer, |
| 258 | allocation: Some(p.allocation), |
| 259 | size: p.size, |
| 260 | usage, |
| 261 | location, |
| 262 | }); |
| 263 | } |
| 264 | let d = &shared.device.device; |
| 265 | let buffer = unsafe { |
| 266 | d.create_buffer( |
| 267 | &vk::BufferCreateInfo::default() |
| 268 | .size(size as u64) |
| 269 | .usage(usage), |
| 270 | None, |
| 271 | )? |
| 272 | }; |
| 273 | let requirements = unsafe { d.get_buffer_memory_requirements(buffer) }; |
| 274 | let allocation = shared |
| 275 | .allocator |
| 276 | .lock() |
| 277 | .unwrap_or_else(|e| e.into_inner()) |
| 278 | .allocate(&AllocationCreateDesc { |
| 279 | name: "staging", |
| 280 | requirements, |
| 281 | location, |
| 282 | linear: true, |
| 283 | allocation_scheme: AllocationScheme::GpuAllocatorManaged, |
| 284 | }); |
| 285 | let allocation = match allocation { |
| 286 | Ok(a) => a, |
| 287 | Err(e) => { |
| 288 | unsafe { d.destroy_buffer(buffer, None) }; |
| 289 | return Err(e.into()); |
| 290 | } |
| 291 | }; |
| 292 | unsafe { d.bind_buffer_memory(buffer, allocation.memory(), allocation.offset())? }; |
| 293 | Ok(Self { |
| 294 | shared: shared.clone(), |
| 295 | buffer, |
| 296 | allocation: Some(allocation), |
| 297 | size, |
| 298 | usage, |
| 299 | location, |
| 300 | }) |
| 301 | } |
| 302 | |
| 303 | pub fn bytes(&self) -> &[u8] { |
| 304 | self.allocation |
| 305 | .as_ref() |
| 306 | .and_then(|a| a.mapped_slice()) |
| 307 | .unwrap_or(&[]) |
| 308 | } |
| 309 | |
| 310 | pub fn bytes_mut(&mut self) -> &mut [u8] { |
| 311 | self.allocation |
| 312 | .as_mut() |
| 313 | .and_then(|a| a.mapped_slice_mut()) |
| 314 | .unwrap_or(&mut []) |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | impl Drop for Staging { |
| 319 | fn drop(&mut self) { |
| 320 | let Some(allocation) = self.allocation.take() else { |
| 321 | return; |
| 322 | }; |
| 323 | let mut pool = self |
| 324 | .shared |
| 325 | .staging_pool |
| 326 | .lock() |
| 327 | .unwrap_or_else(|e| e.into_inner()); |
| 328 | let pooled: usize = pool.iter().map(|p| p.size).sum(); |
| 329 | if pooled + self.size <= POOL_BYTES { |
| 330 | pool.push(Pooled { |
| 331 | buffer: self.buffer, |
| 332 | allocation, |
| 333 | size: self.size, |
| 334 | usage: self.usage, |
| 335 | location: self.location, |
| 336 | returned: Instant::now(), |
| 337 | }); |
| 338 | return; |
| 339 | } |
| 340 | drop(pool); |
| 341 | unsafe { self.shared.device.device.destroy_buffer(self.buffer, None) }; |
| 342 | let _ = self |
| 343 | .shared |
| 344 | .allocator |
| 345 | .lock() |
| 346 | .unwrap_or_else(|e| e.into_inner()) |
| 347 | .free(allocation); |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | /// A sampled texture. |
| 352 | #[derive(Clone, Debug)] |
| 353 | pub struct VulkanTexture(pub(crate) Arc<ImageInner>); |
| 354 | |
| 355 | /// An image the renderer can draw into, from [`smithay::backend::renderer::Offscreen`]. |
| 356 | #[derive(Debug)] |
| 357 | pub struct VulkanImage(pub(crate) Arc<ImageInner>); |
| 358 | |
| 359 | impl VulkanImage { |
| 360 | /// The image's contents as a texture, for drawing it elsewhere. |
| 361 | pub fn texture(&self) -> VulkanTexture { |
| 362 | VulkanTexture(self.0.clone()) |
| 363 | } |
| 364 | } |
| 365 | |
| 366 | /// A bound render target, borrowing whatever it was bound from. |
| 367 | #[derive(Debug)] |
| 368 | pub struct VulkanTarget<'a>( |
| 369 | pub(crate) Arc<ImageInner>, |
| 370 | pub(crate) PhantomData<&'a mut ()>, |
| 371 | ); |
| 372 | |
| 373 | /// Pixels read back from the GPU. |
| 374 | #[derive(Debug)] |
| 375 | pub struct VulkanMapping { |
| 376 | pub(crate) data: Vec<u8>, |
| 377 | pub(crate) width: u32, |
| 378 | pub(crate) height: u32, |
| 379 | pub(crate) fourcc: Fourcc, |
| 380 | } |
| 381 | |
| 382 | macro_rules! texture_impl { |
| 383 | ($t:ty, |$s:ident| $inner:expr) => { |
| 384 | impl Texture for $t { |
| 385 | fn width(&self) -> u32 { |
| 386 | let $s = self; |
| 387 | $inner.width |
| 388 | } |
| 389 | fn height(&self) -> u32 { |
| 390 | let $s = self; |
| 391 | $inner.height |
| 392 | } |
| 393 | fn format(&self) -> Option<Fourcc> { |
| 394 | let $s = self; |
| 395 | Some($inner.fourcc) |
| 396 | } |
| 397 | } |
| 398 | }; |
| 399 | } |
| 400 | |
| 401 | texture_impl!(VulkanTexture, |s| s.0); |
| 402 | texture_impl!(VulkanImage, |s| s.0); |
| 403 | texture_impl!(VulkanTarget<'_>, |s| s.0); |
| 404 | texture_impl!(VulkanMapping, |s| s); |
| 405 | |
| 406 | impl TextureMapping for VulkanMapping { |
| 407 | fn flipped(&self) -> bool { |
| 408 | false |
| 409 | } |
| 410 | } |