jay-compositor 1.14.0

The Jay compositor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
use {
    crate::{
        cpu_worker::{AsyncCpuWork, CpuJob, CpuWork, CpuWorker},
        gfx_apis::vulkan::{VulkanError, device::VulkanDevice, renderer::VulkanRenderer},
        utils::{numcell::NumCell, page_size::page_size, ptr_ext::MutPtrExt},
        vulkan_core::gpu_alloc_ash::{self, AshMemoryDevice},
    },
    ash::{
        Device,
        vk::{DeviceMemory, DeviceSize, MappedMemoryRange, MemoryRequirements},
    },
    gpu_alloc::{Config, GpuAllocator, MemoryBlock, MemoryPropertyFlags, Request, UsageFlags},
    parking_lot::Mutex,
    std::{
        cell::{Cell, UnsafeCell},
        rc::Rc,
        sync::Arc,
    },
};

pub struct SyncAllocatorStorage {
    allocator: Arc<Mutex<GpuAllocator<DeviceMemory>>>,
    device: Rc<VulkanDevice>,
}

pub struct UnsyncAllocatorStorage {
    allocator: UnsafeCell<GpuAllocator<DeviceMemory>>,
    device: Rc<VulkanDevice>,
}

pub struct VulkanAllocatorType<T> {
    storage: T,
    non_coherent_atom_mask: u64,
    total: NumCell<u64>,
}

pub type VulkanAllocator = VulkanAllocatorType<UnsyncAllocatorStorage>;
pub type VulkanThreadedAllocator = VulkanAllocatorType<SyncAllocatorStorage>;

enum AllocatorType {
    Local(Rc<VulkanAllocator>),
    Threaded {
        allocator: Rc<VulkanThreadedAllocator>,
        renderer: Rc<VulkanRenderer>,
        cpu: Rc<CpuWorker>,
    },
}

pub struct VulkanAllocation {
    allocator: AllocatorType,
    pub(super) memory: DeviceMemory,
    pub(super) offset: DeviceSize,
    pub(super) mem: Option<*mut u8>,
    pub(super) size: DeviceSize,
    pub(super) coherency_mask: Option<u64>,
    block: Cell<Option<MemoryBlock<DeviceMemory>>>,
}

impl VulkanAllocation {
    unsafe fn free_locally<T>(
        &self,
        allocator: &VulkanAllocatorType<T>,
        device: &VulkanDevice,
        gpu: &mut GpuAllocator<DeviceMemory>,
    ) {
        allocator.total.fetch_sub(self.size);
        let block = self.block.take().unwrap();
        unsafe {
            do_free(gpu, &device.device, block, self.mem);
        }
    }

    pub fn upload<T, F>(&self, f: F) -> Result<T, VulkanError>
    where
        F: FnOnce(*mut u8, usize) -> T,
    {
        let t = f(self.mem.unwrap(), self.size as usize);
        unsafe {
            self.flush_range(0, self.size)?;
        }
        Ok(t)
    }

    pub unsafe fn upload_range<T, F>(
        &self,
        offset: usize,
        size: usize,
        f: F,
    ) -> Result<T, VulkanError>
    where
        F: FnOnce(*mut u8) -> T,
    {
        let t = f(unsafe { self.mem.unwrap().add(offset) });
        unsafe {
            self.flush_range(offset as DeviceSize, size as DeviceSize)?;
        }
        Ok(t)
    }

    unsafe fn flush_range(&self, offset: DeviceSize, size: DeviceSize) -> Result<(), VulkanError> {
        let Some(mask) = self.coherency_mask else {
            return Ok(());
        };
        let range = self.incoherent_range(offset, size, mask);
        let res = unsafe { self.device().device.flush_mapped_memory_ranges(&[range]) };
        res.map_err(VulkanError::FlushMemory)?;
        Ok(())
    }

    pub fn download<T, F>(&self, f: F) -> Result<T, VulkanError>
    where
        F: FnOnce(*const u8, usize) -> T,
    {
        if let Some(mask) = self.coherency_mask {
            let range = self.incoherent_range(0, self.size, mask);
            let res = unsafe {
                self.device()
                    .device
                    .invalidate_mapped_memory_ranges(&[range])
            };
            res.map_err(VulkanError::FlushMemory)?;
        }
        Ok(f(self.mem.unwrap(), self.size as usize))
    }

    fn incoherent_range(&self, offset: u64, size: u64, mask: u64) -> MappedMemoryRange<'static> {
        let offset = self.offset + offset;
        let lo = offset & !mask;
        let hi = (offset + size + mask) & !mask;
        MappedMemoryRange::default()
            .memory(self.memory)
            .offset(lo)
            .size(hi - lo)
    }

    fn device(&self) -> &VulkanDevice {
        match &self.allocator {
            AllocatorType::Local(l) => &l.storage.device,
            AllocatorType::Threaded { allocator, .. } => &allocator.storage.device,
        }
    }
}

impl Drop for VulkanAllocation {
    fn drop(&mut self) {
        unsafe {
            match &self.allocator {
                AllocatorType::Local(a) => self.free_locally(a, &a.storage.device, a.allocator()),
                AllocatorType::Threaded {
                    allocator,
                    renderer,
                    cpu,
                } => {
                    if renderer.defunct.get() {
                        self.free_locally(
                            allocator,
                            &allocator.storage.device,
                            &mut allocator.storage.allocator.lock(),
                        );
                    } else {
                        let id = renderer.allocate_point();
                        let job = FreeJob {
                            id,
                            renderer: renderer.clone(),
                            allocator: allocator.clone(),
                            size: self.size,
                            work: FreeWork {
                                device: allocator.storage.device.device.clone(),
                                allocator: allocator.storage.allocator.clone(),
                                allocation: Some(UnsafeAllocation {
                                    block: self.block.take().unwrap(),
                                    ptr: self.mem,
                                }),
                            },
                        };
                        let pending = cpu.submit(Box::new(job));
                        renderer.pending_cpu_jobs.set(id, pending);
                    }
                }
            }
        }
    }
}

impl VulkanDevice {
    fn create_allocator_<T>(
        self: &Rc<Self>,
        map: impl FnOnce(GpuAllocator<DeviceMemory>) -> T,
    ) -> Result<Rc<VulkanAllocatorType<T>>, VulkanError> {
        let config = Config::i_am_prototyping();
        let props = unsafe {
            gpu_alloc_ash::device_properties(&self.instance.instance, self.physical_device)
        };
        let mut props = props.map_err(VulkanError::GetDeviceProperties)?;
        props.buffer_device_address = self.uses_descriptor_memory();
        let non_coherent_atom_size = props.non_coherent_atom_size;
        let allocator = GpuAllocator::new(config, props);
        Ok(Rc::new(VulkanAllocatorType {
            non_coherent_atom_mask: non_coherent_atom_size - 1,
            storage: map(allocator),
            total: Default::default(),
        }))
    }

    pub fn create_allocator(self: &Rc<Self>) -> Result<Rc<VulkanAllocator>, VulkanError> {
        self.create_allocator_(|a| UnsyncAllocatorStorage {
            allocator: UnsafeCell::new(a),
            device: self.clone(),
        })
    }

    pub fn create_threaded_allocator(
        self: &Rc<Self>,
    ) -> Result<Rc<VulkanThreadedAllocator>, VulkanError> {
        self.create_allocator_(|a| SyncAllocatorStorage {
            allocator: Arc::new(Mutex::new(a)),
            device: self.clone(),
        })
    }
}

impl<T> VulkanAllocatorType<T> {
    fn commit_allocation(
        self: &Rc<Self>,
        ua: UnsafeAllocation,
        allocator: AllocatorType,
    ) -> VulkanAllocation {
        let UnsafeAllocation { block, ptr } = ua;
        self.total.fetch_add(block.size());
        VulkanAllocation {
            allocator,
            memory: *block.memory(),
            offset: block.offset(),
            mem: ptr,
            size: block.size(),
            coherency_mask: match block.props().contains(MemoryPropertyFlags::HOST_COHERENT) {
                true => None,
                false => Some(self.non_coherent_atom_mask),
            },
            block: Cell::new(Some(block)),
        }
    }
}

impl VulkanAllocator {
    fn allocator(&self) -> &mut GpuAllocator<DeviceMemory> {
        unsafe { self.storage.allocator.get().deref_mut() }
    }

    pub fn alloc(
        self: &Rc<Self>,
        req: &MemoryRequirements,
        usage: UsageFlags,
        map: bool,
    ) -> Result<VulkanAllocation, VulkanError> {
        let ua = do_alloc(
            self.allocator(),
            &self.storage.device.device,
            req,
            usage,
            map,
        )?;
        Ok(self.commit_allocation(ua, AllocatorType::Local(self.clone())))
    }
}

impl VulkanThreadedAllocator {
    pub fn async_alloc(
        self: &Rc<Self>,
        renderer: &Rc<VulkanRenderer>,
        cpu: &Rc<CpuWorker>,
        req: MemoryRequirements,
        usage: UsageFlags,
        map: bool,
        cb: impl FnOnce(Result<VulkanAllocation, VulkanError>) + 'static,
    ) -> Result<(), VulkanError> {
        renderer.check_defunct()?;
        let id = renderer.allocate_point();
        let job = AllocJob {
            id,
            renderer: renderer.clone(),
            cpu: cpu.clone(),
            allocator: self.clone(),
            cb: Some(cb),
            work: AllocWork {
                req,
                usage,
                map,
                device: self.storage.device.device.clone(),
                allocator: self.storage.allocator.clone(),
                res: None,
            },
        };
        let pending = cpu.submit(Box::new(job));
        renderer.pending_cpu_jobs.set(id, pending);
        Ok(())
    }
}

struct AllocJob<T> {
    id: u64,
    renderer: Rc<VulkanRenderer>,
    cpu: Rc<CpuWorker>,
    allocator: Rc<VulkanThreadedAllocator>,
    cb: Option<T>,
    work: AllocWork,
}

struct AllocWork {
    req: MemoryRequirements,
    usage: UsageFlags,
    map: bool,
    device: Arc<Device>,
    allocator: Arc<Mutex<GpuAllocator<DeviceMemory>>>,
    res: Option<Result<UnsafeAllocation, VulkanError>>,
}

impl CpuWork for AllocWork {
    fn run(&mut self) -> Option<Box<dyn AsyncCpuWork>> {
        zone!("AllocWork");
        let r = do_alloc(
            &mut self.allocator.lock(),
            &self.device,
            &self.req,
            self.usage,
            self.map,
        );
        if self.usage.contains(UsageFlags::UPLOAD)
            && let Ok(r) = &r
            && let Some(ptr) = r.ptr
        {
            let page_size = page_size() as u64;
            let mut offset = 0;
            while offset < r.block.size() {
                unsafe {
                    *ptr.add(offset as usize) = 0;
                }
                offset += page_size;
            }
        }
        self.res = Some(r);
        None
    }
}

impl<T> CpuJob for AllocJob<T>
where
    T: FnOnce(Result<VulkanAllocation, VulkanError>),
{
    fn work(&mut self) -> &mut dyn CpuWork {
        &mut self.work
    }

    fn completed(mut self: Box<Self>) {
        self.renderer.pending_cpu_jobs.remove(&self.id);
        let res = self.work.res.take().unwrap().map(|ua| {
            self.allocator.commit_allocation(
                ua,
                AllocatorType::Threaded {
                    allocator: self.allocator.clone(),
                    renderer: self.renderer.clone(),
                    cpu: self.cpu.clone(),
                },
            )
        });
        self.cb.take().unwrap()(res);
    }
}

struct FreeJob {
    id: u64,
    renderer: Rc<VulkanRenderer>,
    allocator: Rc<VulkanThreadedAllocator>,
    size: u64,
    work: FreeWork,
}

struct FreeWork {
    device: Arc<Device>,
    allocator: Arc<Mutex<GpuAllocator<DeviceMemory>>>,
    allocation: Option<UnsafeAllocation>,
}

impl CpuWork for FreeWork {
    fn run(&mut self) -> Option<Box<dyn AsyncCpuWork>> {
        zone!("FreeWork");
        let ua = self.allocation.take().unwrap();
        unsafe {
            do_free(&mut self.allocator.lock(), &self.device, ua.block, ua.ptr);
        }
        None
    }
}

impl CpuJob for FreeJob {
    fn work(&mut self) -> &mut dyn CpuWork {
        &mut self.work
    }

    fn completed(self: Box<Self>) {
        self.renderer.pending_cpu_jobs.remove(&self.id);
        self.allocator.total.fetch_sub(self.size);
    }
}

pub struct UnsafeAllocation {
    block: MemoryBlock<DeviceMemory>,
    ptr: Option<*mut u8>,
}

unsafe impl Send for UnsafeAllocation {}

fn do_alloc(
    allocator: &mut GpuAllocator<DeviceMemory>,
    device: &Device,
    req: &MemoryRequirements,
    usage: UsageFlags,
    map: bool,
) -> Result<UnsafeAllocation, VulkanError> {
    let request = Request {
        size: req.size,
        align_mask: req.alignment - 1,
        usage,
        memory_types: req.memory_type_bits,
    };
    let device = AshMemoryDevice::wrap(device);
    let block = unsafe { allocator.alloc(device, request) };
    let mut block = block.map_err(VulkanError::AllocateMemory2)?;
    let ptr = match map {
        true => {
            let ptr = unsafe { block.map(device, 0, block.size() as usize) };
            Some(ptr.map_err(VulkanError::MapMemory)?.as_ptr())
        }
        false => None,
    };
    Ok(UnsafeAllocation { block, ptr })
}

unsafe fn do_free(
    gpu: &mut GpuAllocator<DeviceMemory>,
    device: &Device,
    mut block: MemoryBlock<DeviceMemory>,
    ptr: Option<*mut u8>,
) {
    unsafe {
        let device = AshMemoryDevice::wrap(device);
        if let Some(_ptr) = ptr {
            // log::info!("free = {:?} - {:?} ({})", ptr, ptr.add(block.size() as usize), block.size());
            block.unmap(device);
        }
        gpu.dealloc(device, block);
    }
}

impl Drop for UnsyncAllocatorStorage {
    fn drop(&mut self) {
        let device = AshMemoryDevice::wrap(&self.device.device);
        unsafe {
            self.allocator.get_mut().cleanup(device);
        }
    }
}

impl Drop for SyncAllocatorStorage {
    fn drop(&mut self) {
        let device = AshMemoryDevice::wrap(&self.device.device);
        unsafe {
            self.allocator.lock().cleanup(device);
        }
    }
}